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 './Accidents';
import { InputFilters } from '~/Components/UIControls/Input';
import { UploadFileType } from '~/Components/UIControls/UploadFile';
import { usePopup } from '~/Components/UIControls/Popup';
import Complaints from './Complaints';

const titleWidth = 100;

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 [complaints, setComplaints] = useState([]);
    const { prompt } = usePrompt();
    const { openPopup } = usePopup();

    // 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);
                setComplaints(result.FmsWorkRequestToComplaint);
                setEditable(editable);
            } catch(error) {
                showMessage(error.message);
            }
        }

        setLoading(false);
    }

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

    // cancel edit
    const onCancelEdit = async () => {
        if(action == Form.EDIT) {
            refreshList();
            navigation.pop();
        } else {
            setFacilities(data.FmsWorkRequestToFacility);
            setAccidents(data.FmsWorkRequestToAccident);
            setComplaints(data.FmsWorkRequestToComplaint);
            setEditable(false);
        }
    }

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

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

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

    const onDelete = async () => {
        confirm('삭제','삭제하시겠습니까?', async () => {
            try {
                await fetchDelete(`api/app/WorkSchedule/DeleteWithResult/${siteId}/${workRequestId}`);

                showMessage('삭제되었습니다.');
                refreshList();
                navigation.pop();
            } catch(error) {
                console.log(error.message);
                showMessage(error.message);
            }
        });
    }

    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="시설목록" />
                            {Util.get(data, 'WorkDetailType.Code') == 'ACCIDENT' && (
                                <TabTitle onPress={() => {
                                    navigation.setParams({ tab: 'accidents' });
                                }} active={tab=='accidents'?true:false} title="사고목록" />
                            )}
                            {Util.get(data, 'WorkDetailType.Code') == 'COMPLAINT' && (
                                <TabTitle onPress={() => {
                                    navigation.setParams({ tab: 'complaints' });
                                }} active={tab=='complaints'?true:false} title="민원목록" />
                            )}
                        </TabTitleGroup>
                    </TabHeader>
                    <TabContent>
                        <TabItem active={tab=='info'?true:false}>
                            <Form.Container onSave={handleSubmit(onSave)} onDelete={onDelete} onEdit={onEdit} onCancelEdit={onCancelEdit}>
                                <Form.Regist name="WorkDetailTypeId" />

                                <Form.Field>
                                    <Form.Require style={{width:titleWidth}}><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 style={{width:titleWidth}}><Form.Label>업무구분</Form.Label></Form.Title>
                                    <Form.Input defaultValue={Util.get(data, "WorkType.Name")} editable={false} />
                                </Form.Field>

                                {(Util.get(data, 'WorkTypeId') == '5' || Util.get(data, 'WorkTypeId') == '6') && (
                                    <Fragment>
                                        <Form.Field>
                                            <Form.Require style={{width:titleWidth}}><Form.Label>구분</Form.Label></Form.Require>
                                            <Form.EntitySelect entity="FmsWorkCodeDetailType" defaultLabel="구분"
                                                        id="WorkDetailTypeId" name="Name" where={`WorkTypeId = ${Util.get(data, 'WorkTypeId')}`} fields="Code"
                                                        selectedValue={data.WorkDetailTypeId} selectedText={Util.get(data, "WorkDetailType.Name")} editable={editable} useCheck={true}
                                                        onChange={(item) => { 
                                                            setValue('WorkDetailTypeId', item.value, true);
                                                            Util.set(data, "WorkDetailType.Code", item.Code);
                                                            setData({...data});
                                                        }} />
                                        </Form.Field>
                                        <Form.Regist editable={editable} name="WorkDetailTypeId" rule={{required:'구분을 선택하세요.'}} error={errors.WorkDetailTypeId} />
                                    </Fragment>
                                )}

                                <Form.Field>
                                    <Form.Title style={{width:titleWidth}}><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 style={{width:titleWidth}}><Form.Label></Form.Label></Form.Title>
                                    <Form.DatePicker date={data.WorkEndDate} minimumDate={Util.addMonth(-1)}
                                        onChange={(newDate) => setValue('WorkEndDate', newDate, true)} editable={editable} />
                                </Form.Field>
                                <Form.Regist editable={editable} name="WorkEndDate" />

                                {!!data.WorkScheduleId && (
                                    <Fragment>
                                        <Form.Field>
                                            <Form.Title style={{width:titleWidth}}><Form.Label>휴일작업</Form.Label></Form.Title>
                                            <Form.Input defaultValue={Util.get(data, "HolidayWorkTypeName", '')} editable={false} />
                                        </Form.Field>

                                        <Form.Field>
                                            <Form.Title style={{width:titleWidth}}><Form.Label>작업주기</Form.Label></Form.Title>
                                            <Form.Input defaultValue={`${Util.get(data, "CycleSize", '')} ${Util.get(data, "CycleUnitName", '')}`} editable={false} />
                                        </Form.Field>
                                    </Fragment>
                                )}

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

                                <Form.Field>
                                    <Form.Require style={{width:titleWidth}}><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.Title style={{width:titleWidth}}><Form.Label>업체명</Form.Label></Form.Title>
                                    <Form.PopupSelect path="/Popup/Partner/Index" popupProps={{navigation, siteId}} 
                                        emptyLabel="업체" defaultLabel={data.WorkPartnerName} editable={editable}
                                        onSelect={(result) => {
                                            setValue('WorkPartnerId', result.PartnerId);
                                        }}
                                    />
                                </Form.Field>
                                <Form.Regist editable={editable} name="WorkPartnerId" />

                                <Form.Field>
                                    <Form.Title style={{width:titleWidth}}><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.TitleTop style={{width:titleWidth}}><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>
                                    <Form.TitleTop style={{width:titleWidth}}><Form.Label>첨부파일</Form.Label></Form.TitleTop>
                                    <Form.UploadFile type={UploadFileType.Image} editable={editable} defaultFile={data.CmFile}
                                    onUpload={(isUpload, result) => {
                                        Form.uploadFile("CmFile", isUpload, result);
                                    }} onDelete={() => {
                                        Form.deleteFile("CmFile");
                                    }} />
                                </Form.Field>
                                <Form.RegistFile editable={editable} name="CmFile" value={data.CmFile} />

                                <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>
                        {Util.get(data, 'WorkDetailType.Code') == 'ACCIDENT' && (
                            <TabItem active={tab=='accidents'?true:false}>
                                <Accidents navigation={navigation} 
                                    keys={{SiteId:siteId, WorkRequestId: workRequestId}}
                                    accidents={accidents} setAccidents={setAccidents} editable={editable} />
                            </TabItem>
                        )}
                        {Util.get(data, 'WorkDetailType.Code') == 'COMPLAINT' && (
                            <TabItem active={tab=='complaints'?true:false}>
                                <Complaints navigation={navigation} 
                                    keys={{SiteId:siteId, WorkRequestId: workRequestId}}
                                    complaints={complaints} setComplaints={setComplaints} 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 readonly = navigation.getParam('readonly', false);
    const { auth } = useAuth(navigation);

    return { 
        header: () => (
            <Header 
                navigation={navigation} 
                title={'작업계획상세'}
                main={false}
                buttons={
                    <Fragment>
                    {!readonly && !editable && (
                        <Fragment>
                            {auth.Update && <Form.EditButton navigation={navigation} type="primary" />}
                            {auth.Delete && <Form.DeleteButton navigation={navigation} />}
                        </Fragment>
                    )}
                    {!readonly && editable && (
                        <Fragment>
                            {auth.Update && <Form.SaveButton type="primary" />}
                            {auth.Update && action != Form.CREATE && <Form.CancelEditButton navigation={navigation} />}
                        </Fragment>
                    )}
                    </Fragment>
                }
            /> 
        )
    } 
};

export default Screen;