import React, { Fragment, useState, useEffect, useLayoutEffect, useContext } from 'react';
import session from '~/Utils/session';
import fetchGet, { fetchPost, fetchDelete } from '~/Utils/fetch';
import { useToast, confirm } 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 { useAuth } from '~/Components/Hooks';
import { Util } from '~/Utils/utils';
import moment from 'moment';

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 workScheduleId = navigation.getParam('workScheduleId', 0);
    const workTypeId = navigation.getParam('workTypeId', 0);
    const tab = navigation.getParam('tab', 'info');
    const { auth, config } = useAuth(navigation);
    const { showMessage } = useToast();

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

    // 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);
        await session.load();

        if(action != Form.CREATE) {
            try {
                const result = await fetchGet(`api/app/WorkSchedule/Regular?siteId=${siteId}&workScheduleId=${workScheduleId}`);
                setData(result);
                Form.setFormData(result);
                setFacilities(result.FmsWorkScheduleToFacility);
                setEditable(editable);
            } catch(error) {
                showMessage(error.message);
            }
        } else {
            const initialData = {
                WorkDueDate: new Date(),
                WorkExpireDate: moment().endOf('year').format('YYYY-MM-DD'),
                HolidayWorkTypeId: 0,
                IsAutoOrder: false,
                IsUse: true,
            };
            setData(initialData);
            Form.setFormData(initialData);
        }

        setLoading(false);
    }

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

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

    // save
    const onSave = async form => {
        if(loading) {
            showMessage('저장중입니다. 잠시만기다려 주세요.');
            return;
        }
        const saveProcess = async () => {
            setLoading(true);
            const submit = {...form,
                UpdateUserId: session.getUserInfo().UserId,
                SiteId: siteId,
                WorkScheduleId: workScheduleId,
                WorkTypeId: workTypeId,
                FmsWorkScheduleToFacility: facilities,
            };
            console.log('submit data', submit);

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

                showMessage('저장되었습니다.');
                refreshList();
                if(action == Form.CREATE) {
                    navigation.pop();
                } else {
                    fetch(false);
                }
            } catch(error) {
                showMessage(error.message);
            }
            setLoading(false);
        };

        const confirmMessage = await fetchGet(`api/app/WorkSchedule/GetUpdateScheduleWarningMessage?siteId=${siteId}&workScheduleId=${workScheduleId}`);
        if(confirmMessage) {
            confirm('저장', confirmMessage, () => {
                saveProcess();
            });
        } else {
            confirm('저장', '저장하시겠습니까?', async () => {
                saveProcess();
            });
        }
    }

    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="시설목록" />
                        </TabTitleGroup>
                    </TabHeader>
                    <TabContent>
                        <TabItem active={tab=='info'?true:false}>
                            <Form.Container onSave={handleSubmit(onSave)} onEdit={onEdit} onCancelEdit={onCancelEdit}>
                                <Form.Field>
                                    <Form.Require><Form.Label>등록자</Form.Label></Form.Require>
                                    <Form.Input defaultValue={session.getUserInfo("Name")} editable={false} />
                                </Form.Field>
                                <Form.Regist editable={editable} name="UpdateUserId" value={session.getUserInfo("UserId")} />

                                <Form.Field>
                                    <Form.Require><Form.Label>업무분야</Form.Label></Form.Require>
                                    <Form.EntitySelect entity="CmBusinessField" defaultLabel="업무분야"
                                                selectedValue={data.BusinessFieldId} selectedText={Util.get(data, "BusinessField.Name")}
                                                editable={editable} auth={auth} useCheck={true}
                                                onChange={(item) => { 
                                                    setValue('BusinessFieldId', item.value, true);
                                                }}  />
                                </Form.Field>
                                <Form.Regist editable={editable} name="BusinessFieldId" rule={{required:'업무분야를 선택하세요.'}} error={errors.BusinessFieldId} />

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

                                <Form.Field>
                                    <Form.Title><Form.Label>작업예정일</Form.Label></Form.Title>
                                    <Form.DatePicker date={data.WorkDueDate} onChange={(newDate) => setValue('WorkDueDate', newDate, true)} editable={editable} />
                                </Form.Field>
                                <Form.Regist editable={editable} name="WorkDueDate" />

                                <Form.Field>
                                    <Form.Title><Form.Label>작업만료일</Form.Label></Form.Title>
                                    <Form.DatePicker date={data.WorkExpireDate} onChange={(newDate) => setValue('WorkExpireDate', newDate, true)} editable={editable} />
                                </Form.Field>
                                <Form.Regist editable={editable} name="WorkExpireDate" />

                                <Form.Field>
                                    <Form.Require><Form.Label>휴일작업</Form.Label></Form.Require>
                                    <Form.EntitySelect entity="FmsWorkCodeHolidayWorkType" useCheck={true} defaultLabel="휴일작업" siteId={siteId}
                                                id="HolidayWorkTypeId" name="Name" selectedValue={data.HolidayWorkTypeId} editable={editable}
                                                selectedText={Util.get(data, "HolidayWorkType.Name")}
                                                onChange={(item) => { 
                                                    setValue('HolidayWorkTypeId', item.value, true);
                                                }} />
                                </Form.Field>
                                <Form.Regist editable={editable} name="HolidayWorkTypeId" rule={{required:'휴일작업을 선택하세요.'}} error={errors.HolidayWorkTypeId} />

                                <Form.Field>
                                    <Form.Require><Form.Label>주기</Form.Label></Form.Require>
                                    <Form.Input placeholder="주기" defaultValue={data.CycleSize} style={{marginRight:10}}
                                                onChangeText={text => setValue('CycleSize', text, true)} 
                                                editable={editable} returnKeyType="next" keyboardType="numeric" />
                                    <Form.EntitySelect entity="FmsWorkCodeCycleUnit" defaultLabel="분기" siteId={siteId}
                                                id="CycleUnitId" name="Name" selectedValue={data.CycleUnitId} editable={editable}
                                                onChange={(item) => { 
                                                    setValue('CycleUnitId', item.value, true);
                                                }} />
                                </Form.Field>
                                <Form.Regist editable={editable} name="CycleSize" rule={{required:'주기를 입력하세요.'}} />
                                <Form.Regist editable={editable} name="CycleUnitId" rule={{required:'분기를 선택하세요.'}} />
                                <Form.Error message={[errors.CycleSize, errors.CycleUnitId]} />
                                
                                {!config.UseWorkAutoOrder && (
                                    <Fragment>
                                        <Form.Field>
                                            <Form.Title><Form.Label>자동지시</Form.Label></Form.Title>
                                            <Form.Switch initialValue={data.IsAutoOrder} onValueChange={(newValue) => { setValue('IsAutoOrder', newValue) }} editable={editable} />
                                        </Form.Field>
                                        <Form.Regist editable={editable} name="IsAutoOrder" />
                                    </Fragment>
                                )}

                                <Form.Field>
                                    <Form.Title><Form.Label>사용여부</Form.Label></Form.Title>
                                    <Form.Switch initialValue={data.IsUse} onValueChange={(newValue) => { setValue('IsUse', newValue) }} editable={editable} />
                                </Form.Field>
                                <Form.Regist editable={editable} name="IsUse" />

                                <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, WorkScheduleId:workScheduleId}}
                                facilities={facilities} setFacilities={setFacilities} editable={editable} />
                        </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.EditButton navigation={navigation} type="primary" />}
                        </Fragment>
                    )}
                    {editable && (
                        <Fragment>
                            {auth.Update && <Form.SaveButton type="primary" />}
                            {action != Form.CREATE && auth.Update && <Form.CancelEditButton navigation={navigation} />}
                        </Fragment>
                    )}
                    </Fragment>
                }
            /> 
        )
    } 
};

export default Screen;