import React, { Fragment, useState, useEffect, useLayoutEffect, useContext } from 'react';
import { ActivityIndicator } from 'react-native';
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 Button from '~/Components/UIControls/Button';
import { useForm } from 'react-hook-form';
import BottomTabBarLayout from '~/Components/Layouts/BottomTabBarLayout';
import { UploadFileType } from '~/Components/UIControls/UploadFile';
import { usePopup } from '~/Components/UIControls/Popup';
import { Util } from '~/Utils/utils';
import { useAuth } from '~/Components/Hooks';

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

    const [ready, setReady] = useState(false);
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState({ IsInsurance: false });
    const [companyId, setCompanyId] = useState('');
    // mount
    useEffect(() => {
        fetch();
    }, [editable]);

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

    // popup
    const { openPopup } = usePopup();

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

    // search
    const fetch = async () => {
        setLoading(true);
        await session.load();

        if (action != Form.CREATE) {
            try {
                console.log('get - ', `api/app/Accident/Get?siteId=${siteId}&accidentId=${accidentId}`);
                const result = await fetchGet(`api/app/Accident/Get?siteId=${siteId}&accidentId=${accidentId}`);
                setData(result);
                Form.setFormData(result);
            } catch (error) {
                showMessage(error.message);
            }
        } else {
            Form.setFormData(data);
        }

        setReady(false);
        setReady(true);
        setLoading(false);
    };

    // edit
    const onEdit = async () => {
        await fetch();
        setEditable(true);
    };

    // cancel edit
    const onCancelEdit = async () => {
        await fetch();
        setEditable(false);
    };

    // save
    const onSave = async (form) => {
        if (loading) {
            showMessage('저장중입니다. 잠시만기다려 주세요.');
            return;
        }
        confirm('저장', '저장하시겠습니까?', async () => {
            setLoading(true);

            const submit = {
                ...form,
                SiteId: siteId,
                AccidentId: accidentId,
                CmFile1: !form.CmFile1.IsUpload && !form.CmFile1.IsDelete ? null : form.CmFile1,
                CmFile2: !form.CmFile2.IsUpload && !form.CmFile2.IsDelete ? null : form.CmFile2,
                CmFile3: !form.CmFile3.IsUpload && !form.CmFile3.IsDelete ? null : form.CmFile3,
            };
            console.log('submit data', submit);
            try {
                const result = await fetchPost('api/app/Accident/Save', submit);

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

    // delete
    const onDelete = async () => {
        if (loading) {
            showMessage('처리중입니다. 잠시만기다려 주세요.');
            return;
        }
        confirm('삭제', '삭제하시겠습니까?', async () => {
            setLoading(true);
            try {
                await fetchDelete(`api/app/Accident/${siteId}/${accidentId}`);

                showMessage('삭제되었습니다.');
                refreshList();
                navigation.pop();
            } catch (error) {
                showMessage(error.message);
            }
            setLoading(false);
        });
    };
    console.log(data);
    return (
        <BottomTabBarLayout>
            {ready ? (
                <Form.Container
                    onSave={handleSubmit(onSave)}
                    onDelete={onDelete}
                    onEdit={onEdit}
                    onCancelEdit={onCancelEdit}
                    loading={loading}
                >
                    <Form.Field>
                        <Form.Require style={{ width: 100 }}>
                            <Form.Label>사고제목</Form.Label>
                        </Form.Require>
                        <Form.Input defaultValue={data.Name} onChangeText={(text) => setValue('Name', text, true)} editable={editable} />
                    </Form.Field>
                    <Form.Regist editable={editable} name="Name" rule={{ required: '사고명을 입력하세요.' }} error={errors.Name} />

                    <Form.Field>
                        <Form.Require style={{ width: 100 }}>
                            <Form.Label>사고유형</Form.Label>
                        </Form.Require>
                        <Form.EntitySelect
                            entity="FmsAccidentCodeType"
                            defaultLabel="사고유형"
                            id="AccidentTypeId"
                            selectedValue={data.AccidentTypeId}
                            selectedText={data.AccidentTypeName}
                            editable={editable}
                            useCheck={true}
                            onChange={(item) => {
                                setValue('AccidentTypeId', item.value, true);
                            }}
                        />
                    </Form.Field>
                    <Form.Regist
                        editable={editable}
                        name="AccidentTypeId"
                        rule={{ required: '사고유형을 선택하세요.' }}
                        error={errors.AccidentTypeId}
                    />

                    <Form.Field>
                        <Form.Title style={{ width: 100 }}>
                            <Form.Label>발생일시</Form.Label>
                        </Form.Title>
                        <Form.DatePicker
                            mode="datetime"
                            date={data.StartDate}
                            onChange={(newDate) => setValue('StartDate', newDate, true)}
                            editable={editable}
                        />
                    </Form.Field>
                    <Form.Regist editable={editable} name="StartDate" />

                    <Form.Field>
                        <Form.Title style={{ width: 100 }}>
                            <Form.Label>발생장소</Form.Label>
                        </Form.Title>
                        <Form.Input
                            defaultValue={data.AccidentLocation}
                            onChangeText={(text) => setValue('AccidentLocation', text, true)}
                            editable={editable}
                        />
                    </Form.Field>
                    <Form.Regist editable={editable} name="AccidentLocation" />

                    <Form.Field>
                        <Form.Title style={{ width: 100 }}>
                            <Form.Label>최초목격자</Form.Label>
                        </Form.Title>
                        <Form.Input
                            defaultValue={data.Firstwitness}
                            onChangeText={(text) => setValue('Firstwitness', text, true)}
                            editable={editable}
                        />
                    </Form.Field>
                    <Form.Regist editable={editable} name="Firstwitness" />

                    <Form.Field>
                        <Form.TitleTop style={{ width: 100 }}>
                            <Form.Label>발생경위</Form.Label>
                        </Form.TitleTop>
                        <Form.Input
                            defaultValue={data.Reason}
                            onChangeText={(text) => setValue('Reason', text, true)}
                            multiline={true}
                            editable={editable}
                        />
                    </Form.Field>
                    <Form.Regist editable={editable} name="Reason" />

                    <Form.Field>
                        <Form.Title style={{ width: 100 }}>
                            <Form.Label>피해자명</Form.Label>
                        </Form.Title>
                        <Form.Input
                            defaultValue={data.VictimName}
                            onChangeText={(text) => setValue('VictimName', text, true)}
                            editable={editable}
                        />
                    </Form.Field>
                    <Form.Regist editable={editable} name="VictimName" />

                    <Form.Field>
                        <Form.Title style={{ width: 100 }}>
                            <Form.Label>피해자관계</Form.Label>
                        </Form.Title>
                        <Form.Input
                            defaultValue={data.VictimRelation}
                            onChangeText={(text) => setValue('VictimRelation', text, true)}
                            editable={editable}
                        />
                    </Form.Field>
                    <Form.Regist editable={editable} name="VictimRelation" />

                    <Form.Field>
                        <Form.Title style={{ width: 100 }}>
                            <Form.Label>피해자연령</Form.Label>
                        </Form.Title>
                        <Form.Input
                            defaultValue={data.VictimAge}
                            onChangeText={(text) => setValue('VictimAge', text, true)}
                            editable={editable}
                        />
                    </Form.Field>
                    <Form.Regist editable={editable} name="VictimAge" />

                    <Form.Field>
                        <Form.TitleTop style={{ width: 100 }}>
                            <Form.Label>피해현황</Form.Label>
                        </Form.TitleTop>
                        <Form.Input
                            defaultValue={data.Damage}
                            onChangeText={(text) => setValue('Damage', text, true)}
                            multiline={true}
                            editable={editable}
                        />
                    </Form.Field>
                    <Form.Regist editable={editable} name="Damage" />

                    <Form.Field>
                        <Form.TitleTop style={{ width: 100 }}>
                            <Form.Label>조치사항1</Form.Label>
                        </Form.TitleTop>
                        <Form.Input
                            defaultValue={data.Action}
                            onChangeText={(text) => setValue('Action', text, true)}
                            multiline={true}
                            editable={editable}
                        />
                    </Form.Field>
                    <Form.Regist editable={editable} name="Action" />

                    <Form.Field>
                        <Form.Title style={{ width: 100 }}>
                            <Form.Label>조치완료일</Form.Label>
                        </Form.Title>
                        <Form.DatePicker
                            date={data.EndDate}
                            onChange={(newDate) => setValue('EndDate', newDate, true)}
                            editable={editable}
                        />
                    </Form.Field>
                    <Form.Regist editable={editable} name="EndDate" />

                    <Form.Field>
                        <Form.TitleTop style={{ width: 100 }}>
                            <Form.Label>조치사항2</Form.Label>
                        </Form.TitleTop>
                        <Form.Input
                            defaultValue={data.Action2}
                            onChangeText={(text) => setValue('Action2', text, true)}
                            multiline={true}
                            editable={editable}
                        />
                    </Form.Field>
                    <Form.Regist editable={editable} name="Action2" />

                    <Form.Field>
                        <Form.Title style={{ width: 100 }}>
                            <Form.Label>종결일</Form.Label>
                        </Form.Title>
                        <Form.DatePicker
                            date={data.ClosingDate}
                            onChange={(newDate) => setValue('ClosingDate', newDate, true)}
                            editable={editable}
                        />
                    </Form.Field>
                    <Form.Regist editable={editable} name="ClosingDate" />

                    <Form.Field>
                        <Form.TitleTop style={{ width: 100 }}>
                            <Form.Label>보험처리여부</Form.Label>
                        </Form.TitleTop>
                        <Form.Switch initialValue={data.IsInsurance} onValueChange={(newValue) => { setValue('IsInsurance', newValue) }} editable={editable} />
                    </Form.Field>
                    <Form.Regist editable={editable} name="IsInsurance" />

                    <Form.Field>
                        <Form.TitleTop style={{ width: 100 }}>
                            <Form.Label>보험처리내용</Form.Label>
                        </Form.TitleTop>
                        <Form.Input
                            defaultValue={data.InsuranceContent}
                            onChangeText={(text) => setValue('InsuranceContent', text, true)}
                            multiline={true}
                            editable={editable}
                        />
                    </Form.Field>
                    <Form.Regist editable={editable} name="InsuranceContent" />

                    <Form.Field>
                        <Form.TitleTop style={{ width: 100 }}>
                            <Form.Label>향후대책</Form.Label>
                        </Form.TitleTop>
                        <Form.Input
                            defaultValue={data.Measurement}
                            onChangeText={(text) => setValue('Measurement', text, true)}
                            multiline={true}
                            editable={editable}
                        />
                    </Form.Field>
                    <Form.Regist editable={editable} name="Measurement" />

                    {/*
                    <Form.Field>
                        <Form.Title style={{ width: 100 }}>
                            <Form.Label>회사</Form.Label>
                        </Form.Title>
                        <Form.EntitySelect
                            entity="CmCompany"
                            defaultLabel="회사"
                            siteId={session.getSiteId()}
                            selectedValue={data.CompanyId}
                            selectedText={data.CompanyName}
                            editable={editable}
                            useCheck={true}
                            onChange={(item) => {
                                setValue('CompanyId', item.value, true);
                                setCompanyId(item.value);
                            }}
                        />
                    </Form.Field>
                    <Form.Regist editable={editable} name="CompanyId" />

                    <Form.Field>
                        <Form.Title style={{ width: 100 }}>
                            <Form.Label>부서</Form.Label>
                        </Form.Title>
                        <Form.EntitySelect
                            entity="CmDepartment"
                            defaultLabel="부서"
                            siteId={session.getSiteId()}
                            where={companyId != '' ? `CompanyId=${companyId}` : ``}
                            selectedValue={data.DepartmentId}
                            selectedText={data.DepartmentName}
                            editable={editable}
                            useCheck={true}
                            onChange={(item) => {
                                setValue('DepartmentId', item.value, true);
                            }}
                        />
                    </Form.Field>
                    <Form.Regist editable={editable} name="DepartmentId" />
                    */}

                    <Form.Field>
                        <Form.TitleTop style={{ width: 100 }}>
                            <Form.Label>첨부파일1</Form.Label>
                        </Form.TitleTop>
                        <Form.UploadFile
                            type={UploadFileType.Image}
                            editable={editable}
                            defaultFile={data.CmFile1}
                            onUpload={(isUpload, result) => {
                                Form.uploadFile('CmFile1', isUpload, result);
                            }}
                            onDelete={() => {
                                Form.deleteFile('CmFile1');
                            }}
                        />
                    </Form.Field>
                    <Form.RegistFile editable={editable} name="CmFile1" value={Util.get(data, 'CmFile1')} />

                    <Form.Field>
                        <Form.TitleTop style={{ width: 100 }}>
                            <Form.Label>첨부파일2</Form.Label>
                        </Form.TitleTop>
                        <Form.UploadFile
                            type={UploadFileType.Image}
                            editable={editable}
                            defaultFile={data.CmFile2}
                            onUpload={(isUpload, result) => {
                                Form.uploadFile('CmFile2', isUpload, result);
                            }}
                            onDelete={() => {
                                Form.deleteFile('CmFile2');
                            }}
                        />
                    </Form.Field>
                    <Form.RegistFile editable={editable} name="CmFile2" value={Util.get(data, 'CmFile2')} />

                    <Form.Field>
                        <Form.TitleTop style={{ width: 100 }}>
                            <Form.Label>첨부파일3</Form.Label>
                        </Form.TitleTop>
                        <Form.UploadFile
                            type={UploadFileType.Image}
                            editable={editable}
                            defaultFile={data.CmFile3}
                            onUpload={(isUpload, result) => {
                                Form.uploadFile('CmFile3', isUpload, result);
                            }}
                            onDelete={() => {
                                Form.deleteFile('CmFile3');
                            }}
                        />
                    </Form.Field>
                    <Form.RegistFile editable={editable} name="CmFile3" value={Util.get(data, 'CmFile3')} />


                    <Form.Field>
                        <Form.TitleTop style={{ width: 100 }}>
                            <Form.Label>첨부파일4</Form.Label>
                        </Form.TitleTop>
                        <Form.UploadFile
                            type={UploadFileType.Image}
                            editable={editable}
                            defaultFile={data.CmFile4}
                            onUpload={(isUpload, result) => {
                                Form.uploadFile('CmFile4', isUpload, result);
                            }}
                            onDelete={() => {
                                Form.deleteFile('CmFile4');
                            }}
                        />
                    </Form.Field>
                    <Form.RegistFile editable={editable} name="CmFile4" value={Util.get(data, 'CmFile4')} />

                    <Form.Field style={{ height: 50 }}></Form.Field>
                </Form.Container>
            ) : (
                <Form.Loading />
            )}
        </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);

    const siteId = navigation.getParam('siteId', '');
    const accidentId = navigation.getParam('accidentId', 0);

    return {
        header: () => (
            <Header
                navigation={navigation}
                title={`사고관리`}
                main={false}
                buttons={
                    <Fragment>
                        {!editable && (
                            <Fragment>
                                <Form.PrimaryButton
                                    buttonStyle={{ width:60 }}
                                    onPress={() => {
                                        navigation.navigate('PrintForm', {
                                            siteId: siteId,
                                            accidentId: accidentId,
                                        });
                                    }}
                                >
                                    리포트
                                </Form.PrimaryButton>
                                {auth.Update && <Form.EditButton navigation={navigation} buttonStyle={{ width:50 }} type="primary" />}
                                {auth.Delete && <Form.DeleteButton buttonStyle={{ width:50 }} />}
                            </Fragment>
                        )}
                        {editable && (
                            <Fragment>
                                {auth.Update && <Form.SaveButton type="primary" buttonStyle={{ width:50 }} />}
                                {action != Form.CREATE && <Form.CancelEditButton buttonStyle={{ width:50 }} navigation={navigation} />}
                            </Fragment>
                        )}
                    </Fragment>
                }
            />
        ),
    };
};

export default Screen;
