import React, { useState, useEffect, useLayoutEffect } 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 EmptyLayout from '~/Components/Layouts/EmptyLayout';
import { useAuth } from '~/Components/Hooks';
import { Util } from '~/Utils/utils';
import { InputFilters } from '~/Components/UIControls/Input';

const Screen = ({navigation, facilities, setFacilities}) => {
    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', 7);
    const { auth, userinfo, config } = useAuth(navigation);
    const { showMessage } = useToast();

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

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

    // unmount
    useEffect(() => () => {
    }, []);

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

        if(action != Form.CREATE) {
            try {
                const result = await fetchGet(`api/app/WorkSchedule/Legal?siteId=${siteId}&workScheduleId=${workScheduleId}`);
                console.log('fetch result - ', result);
                setData(result);
                Form.setFormData(result);
                setFacilities(result.FmsWorkScheduleToFacility);
                setEditable(editable);
            } catch(error) {
                showMessage(error.message);
            }
        } else {
            const initialData = {
                WorkDueDate: new Date(),
                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;
        }
        console.log('form - ', form);
        const saveProcess = async () => {
            setLoading(true);
            const submit = {...form,
                UpdateUserId: session.getUserInfo().UserId,
                SiteId: siteId,
                WorkScheduleId: workScheduleId,
                WorkTypeId: workTypeId,
                HolidayWorkTypeId: 0,
                IsAutoOrder: false,
                FmsWorkScheduleToFacility: facilities,
            };
            console.log('submit data', submit);

            try {
                const result = await fetchPost('api/app/WorkSchedule/SaveExpectedRequest', 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 ( 
        workTypeId == 7 ? (
        <EmptyLayout>
            <Form.Container id="legal-edu-form" onSave={handleSubmit(onSave)} onEdit={onEdit} onCancelEdit={onCancelEdit} loading={loading}>
                <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} useCheck={true} auth={auth}
                                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.Input placeholder="업체명" defaultValue={data.WorkPartnerName} 
                                onChangeText={text => setValue('WorkPartnerName', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="WorkPartnerName" />

                <Form.Field>
                    <Form.Title><Form.Label>금액</Form.Label></Form.Title>
                    <Form.Input placeholder="금액" defaultValue={data.WorkPrice} 
                                filter={text => {
                                    return InputFilters.number(text);
                                }}
                                onChangeText={text => {
                                    setValue('WorkPrice', text, true);
                                }} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="WorkPrice" />

                <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.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]} />
                
                <Form.Field>
                    <Form.Require><Form.Label>교육기관</Form.Label></Form.Require>
                    <Form.EntitySelect entity="CmPartner" defaultLabel="법정교육기관" siteId={siteId} 
                                where="PartnerTypeId = 1" useCheck={true} auth={auth} editable={editable}
                                selectedValue={data.InspectionAgencyId} selectedText={Util.get(data, "InspectionAgency.Name")}
                                onChange={(item) => { 
                                    setValue('InspectionAgencyId', item.value, true);
                                }}  />
                </Form.Field>
                <Form.Regist editable={editable} name="InspectionAgencyId" rule={{required:'법정검사기관을 선택하세요.'}} error={errors.InspectionAgencyId} />

                <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>
        </EmptyLayout>
        ) : null
    );
};

export default Screen;