import React, { useState, useEffect, useLayoutEffect, Fragment } from 'react';
import session from '~/Utils/session';
import fetchGet, { fetchPost, fetchDelete, fetchPut } 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 { UploadFileType } from '~/Components/UIControls/UploadFile';

const Screen = ({navigation, siteId, investigationId}) => {
    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 { auth, userinfo } = useAuth(navigation);
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState({});
    const { showMessage } = useToast();

    // 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/Investigation2/${siteId}/${investigationId}`);
                setData(result);
                Form.setFormData(result);
                setEditable(editable);
            } catch(error) {
                showMessage(error.message);
            }
        }

        setLoading(false);
    }

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

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

    // save
    const onSave = async form => {

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

            try {
                if(action == Form.CREATE) {
                    const result = await fetchPut('api/Investigation2', submit);

                    showMessage('저장되었습니다.');
                    refreshList();
    
                    navigation.pop();
                } else {
                    const result = await fetchPost(`api/Investigation2/${siteId}/${investigationId}`, submit);

                    showMessage('저장되었습니다.');
                    refreshList();

                    fetch(false);
                }
            } catch(error) {
                showMessage(error.message);
            }
            setLoading(false);
        });
    }

    // delete
    const onDelete = async () => {
        if(loading) {
            showMessage('처리중입니다. 잠시만기다려 주세요.');
            return;
        }
        confirm('삭제','삭제하시겠습니까?', async () => {
            setLoading(true);
            try {
                await fetchDelete(`api/Investigation2/${siteId}/${investigationId}`);
                
                showMessage('삭제되었습니다.');
                refreshList();
                navigation.pop();
            } catch(error) {
                showMessage(error.message);
            }
            setLoading(false);
        });
    }

    return ( 
        <EmptyLayout>
            <Form.Container id="investigation2-info" onSave={handleSubmit(onSave)} onDelete={onDelete} onEdit={onEdit} onCancelEdit={onCancelEdit} loading={loading}>

                <Form.Field>
                    <Form.Require><Form.Label>분류</Form.Label></Form.Require>
                    <Form.EntitySelect entity="CmInvestigation2CodeGroup" defaultLabel="분류" 
                        id="InvestigationGroupId" name="Name" useCheck={true}
                        selectedValue={data.InvestigationGroupId} selectedText={Util.get(data, "CmInvestigation2CodeGroup.Name")} editable={editable}
                        onChange={(item) => { setValue('InvestigationGroupId', item.value, true) }}  />
                </Form.Field>
                <Form.Regist editable={editable} name="InvestigationGroupId" rule={{required:'분류를 선택하세요.'}} error={errors.InvestigationGroupId} />

                <Form.Field>
                    <Form.Require><Form.Label>유형</Form.Label></Form.Require>
                    <Form.EntitySelect entity="CmInvestigation2CodeType" defaultLabel="유형" 
                        id="InvestigationTypeId" name="Name" useCheck={true}
                        selectedValue={data.InvestigationTypeId} selectedText={Util.get(data, "CmInvestigation2CodeType.Name")} editable={editable}
                        onChange={(item) => { setValue('InvestigationTypeId', item.value, true) }}  />
                </Form.Field>
                <Form.Regist editable={editable} name="InvestigationTypeId" rule={{required:'유형을 선택하세요.'}} error={errors.InvestigationTypeId} />

                <Form.Field>
                    <Form.Require><Form.Label>번호</Form.Label></Form.Require>
                    <Form.Input placeholder="번호" defaultValue={data.InvestigationNo} onChangeText={text => setValue('InvestigationNo', text, true)} editable={editable} />
                </Form.Field>
                <Form.Regist editable={editable} name="InvestigationNo" rule={{required:'번호를 입력하세요.'}} error={errors.InvestigationNo} />

                <Form.Field>
                    <Form.Require><Form.Label>이름</Form.Label></Form.Require>
                    <Form.Input placeholder="이름" 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.TitleTop><Form.Label>설명</Form.Label></Form.TitleTop>
                    <Form.Input placeholder="설명" defaultValue={data.Description} 
                        onChangeText={text => setValue('Description', text, true)} 
                        multiline={true} editable={editable} />
                </Form.Field>
                <Form.Regist editable={editable} name="Description" />

                {!investigationId && (
                    <Fragment>
                        <Form.Field>
                            <Form.TitleTop><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} />
                    </Fragment>
                )}

                <Form.Field style={{ height:30 }}>
                </Form.Field>

            </Form.Container>
        </EmptyLayout>
    );
};

export default Screen;