import React, { Fragment, useState, useEffect, useLayoutEffect, useContext } from 'react';
import session from '~/Utils/session';
import fetchGet, { fetchPost, fetchDelete } from '~/Utils/fetch';
import { useToast, confirm, usePrompt } from '~/Components/UIControls/Message';
import Form from '~/Components/Form';
import { useForm } from 'react-hook-form';
import BottomTabBarLayout from '~/Components/Layouts/BottomTabBarLayout';
import { Tab, TabItem, TabTitleGroup, TabHeader, TabContent, TabTitle } from '~/Components/UIControls/Tab';
import Facilities from '~/Screens/Root/Facility/Common/Facilities';
import { Util } from '~/Utils/utils';
import { useAuth } from '~/Components/Hooks';
import Accidents from '../Common/Accidents';

const Screen = ({navigation}) => {
    const action = navigation.getParam('action', Form.VIEW);
    const editable = navigation.getParam('editable', action == Form.VIEW ? false : true);
    const setEditable = (value) => { navigation.setParams({editable: value}) };
    const refreshList = navigation.getParam('refreshList', ()=>{});
    const siteId = navigation.getParam('siteId', '');
    const workRequestId = navigation.getParam('workRequestId', 0);
    const tab = navigation.getParam('tab', 'info');
    const { auth, userinfo } = useAuth(navigation);
    const { showMessage } = useToast();

    const [loading, setLoading] = useState(false);
    const [data, setData] = useState({});
    const [facilities, setFacilities] = useState([]);
    const [accidents, setAccidents] = useState([]);
    const { prompt } = usePrompt();

    // mount
    useEffect(() => {
        fetch(editable);
    }, []);

    // react hook form initialize
    const { register, setValue, handleSubmit, errors, getValues } = useForm();
    useLayoutEffect(() => {
        Form.setUseFormFunctions(register, setValue);
    }, [register]);
    
    // search
    const fetch = async (editable) => {
        setLoading(true);

        if(action != Form.CREATE) {
            try {
                const result = await fetchGet(`api/app/WorkRequest/Get?siteId=${siteId}&workRequestId=${workRequestId}`);
                setData(result);
                Form.setFormData(result);
                setFacilities(result.FmsWorkRequestToFacility);
                setAccidents(result.FmsWorkRequestToAccident);
                setEditable(editable);
            } catch(error) {
                showMessage(error.message);
            }
        }

        setLoading(false);
    }

    // edit
    const onEdit = async () => {
        setFacilities(data.FmsWorkRequestToFacility);
        setAccidents(data.FmsWorkRequestToAccident);
        setEditable(true);
    }

    // cancel edit
    const onCancelEdit = async () => {
        setFacilities(data.FmsWorkRequestToFacility);
        setAccidents(data.FmsWorkRequestToAccident);
        setEditable(false);
    }

    // save
    const onSave = async form => {
        if(loading) {
            showMessage('처리중입니다. 잠시만기다려 주세요.');
            return;
        }
        confirm('저장', '저장하시겠습니까?', async () => {
            setLoading(true);
            const submit = {...form,
                SiteId: siteId,
                WorkRequestId: workRequestId,
                FmsWorkRequestToFacility: facilities,
            };
            console.log('submit data', submit);

            try {
                const result = await fetchPost('api/app/WorkRequest/Save', submit);

                showMessage('저장되었습니다.');
                refreshList();
                fetch(false);
            } catch(error) {
                showMessage(error.message);
            }
            setLoading(false);
        });
    }

    // 작업지시
    const onAction = async action => {
        console.log(action);

        if(loading) {
            showMessage('처리중입니다. 잠시만기다려 주세요.');
            return;
        }
        prompt({title:'지시내용입력', message: '작업지시 내용을 입력하세요.', 
            confirm: (text) => {
                confirm('작업지시', '작업지시 처리 하시겠습니까?', async () => {
                    setLoading(true);
                    const submit = {
                        SiteId: siteId,
                        WorkRequestId: workRequestId,
                        OrderUserId: userinfo.UserId,
                        Content: text,
                    };
                    try {
                        const result = await fetchPost(`api/app/WorkRequest/Order`, submit);

                        showMessage('처리되었습니다.');
                        refreshList();
                        navigation.pop();
                    } catch(error) {
                        showMessage(error.message);
                    }
                    setLoading(false);
                });
            }
        });
    }

    return ( 
        <BottomTabBarLayout>
            <Fragment>
                <Tab>
                    <TabHeader>
                        <TabTitleGroup top={true}>
                            <TabTitle onPress={() => {
                                navigation.setParams({ tab: 'info' });
                            }} active={tab=='info'?true:false} title="업무내용" />
                            <TabTitle onPress={() => {
                                navigation.setParams({ tab: 'facilities' });
                            }} active={tab=='facilities'?true:false} title="시설목록" />
                            {accidents && accidents.length > 0 && (
                                <TabTitle onPress={() => {
                                    navigation.setParams({ tab: 'accidents' });
                                }} active={tab=='accidents'?true:false} title="사고목록" />
                            )}
                        </TabTitleGroup>
                    </TabHeader>
                    <TabContent>
                        <TabItem active={tab=='info'?true:false}>
                            <Form.Container onSave={handleSubmit(onSave)} onEdit={onEdit} onCancelEdit={onCancelEdit} onAction={onAction}>
                                <Form.Field>
                                    <Form.Require><Form.Label>업무분야</Form.Label></Form.Require>
                                    <Form.EntitySelect entity="CmBusinessField" defaultLabel="업무분야"
                                                selectedValue={data.BusinessFieldId} editable={editable} useCheck={true} auth={auth}
                                                selectedText={Util.get(data, "BusinessField.Name")}
                                                onChange={(item) => { 
                                                    setValue('BusinessFieldId', item.value, true);
                                                }}  />
                                </Form.Field>
                                <Form.Regist editable={editable} name="BusinessFieldId" rule={{required:'업무분야를 선택하세요.'}} error={errors.BusinessFieldId} />

                                <Form.Field>
                                    <Form.Title><Form.Label>작업구분</Form.Label></Form.Title>
                                    <Form.Input defaultValue={Util.get(data, "WorkType.Name")} editable={false} />
                                </Form.Field>

                                <Form.Field>
                                    <Form.Title><Form.Label>작업예정일</Form.Label></Form.Title>
                                    <Form.DatePicker date={data.StartWorkDate} minimumDate={Util.addMonth(-1)}
                                        onChange={(newDate) => setValue('StartWorkDate', newDate, true)} editable={editable} />
                                </Form.Field>
                                <Form.Regist editable={editable} name="StartWorkDate" rule={{required:'작업예정일을 선택하세요.'}} error={errors.StartWorkDate} />

                                <Form.Field>
                                    <Form.Title><Form.Label>신청자</Form.Label></Form.Title>
                                    <Form.Input defaultValue={Util.get(data, "CmUserNavigation.Name")} editable={false} />
                                </Form.Field>

                                <Form.Field>
                                    <Form.Require><Form.Label>업무명</Form.Label></Form.Require>
                                    <Form.Input placeholder="업무명" defaultValue={data.Title} 
                                                onChangeText={text => setValue('Title', text, true)} 
                                                editable={editable} returnKeyType="next" />
                                </Form.Field>
                                <Form.Regist editable={editable} name="Title" rule={{required:'업무명을 입력하세요.'}} error={errors.Title} />

                                <Form.Field>
                                    <Form.TitleTop><Form.Label>내용</Form.Label></Form.TitleTop>
                                    <Form.Input placeholder="내용" defaultValue={data.Content} 
                                        onChangeText={text => setValue('Content', text, true)} 
                                        multiline={true} editable={editable} />
                                </Form.Field>
                                <Form.Regist editable={editable} name="Content" />

                                <Form.Field style={{ height:30 }}>
                                </Form.Field>
                            </Form.Container>
                        </TabItem>
                        <TabItem active={tab=='facilities'?true:false}>
                            <Facilities navigation={navigation} 
                                keys={{SiteId:siteId, WorkRequestId: workRequestId}}
                                facilities={facilities} setFacilities={setFacilities} editable={editable} />
                        </TabItem>
                        {accidents && accidents.length > 0 && (
                            <TabItem active={tab=='accidents'?true:false}>
                                <Accidents navigation={navigation} 
                                    keys={{SiteId:siteId, WorkRequestId: workRequestId}}
                                    accidents={accidents} setAccidents={setAccidents} editable={false} />
                            </TabItem>
                        )}
                    </TabContent>
                </Tab>
                {loading && <Form.Loading />}
            </Fragment>
        </BottomTabBarLayout>
    );
};

Screen.navigationOptions = ({navigation}) => { 
    const action = navigation.getParam('action', Form.VIEW);    // create, edit, view
    const editable = navigation.getParam('editable', action == Form.VIEW ? false : true);
    const { auth } = useAuth(navigation);

    return { 
        header: () => (
            <Header 
                navigation={navigation} 
                title={`실행계획 관리`}
                main={false}
                buttons={
                    <Fragment>
                    {!editable && (
                        <Fragment>
                            {auth.Update && <Form.ActionButton navigation={navigation} type="success" action="order" title="작업지시" />}
                            {auth.Update && <Form.EditButton navigation={navigation} type="primary" />}
                        </Fragment>
                    )}
                    {editable && (
                        <Fragment>
                            {auth.Update && <Form.SaveButton type="primary" />}
                            {auth.Update && action != Form.CREATE && <Form.CancelEditButton navigation={navigation} />}
                        </Fragment>
                    )}
                    </Fragment>
                }
            /> 
        )
    } 
};

export default Screen;