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, drawingId}) => {
    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/Drawing/${siteId}/${drawingId}`);
                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,
                DrawingId: drawingId,
            };
            console.log('submit data', submit);

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

                    showMessage('저장되었습니다.');
                    refreshList();
    
                    navigation.pop();
                } else {
                    const result = await fetchPost(`api/Drawing/${siteId}/${drawingId}`, 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/Drawing/${siteId}/${drawingId}`);
                
                showMessage('삭제되었습니다.');
                refreshList();
                navigation.pop();
            } catch(error) {
                showMessage(error.message);
            }
            setLoading(false);
        });
    }

    return ( 
        <EmptyLayout>
            <Form.Container id="drawing-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="FmsDrawingCodeGroup" defaultLabel="도면분류" 
                        id="DrawingGroupId" name="Name" useCheck={true}
                        selectedValue={data.DrawingGroupId} selectedText={Util.get(data, "DrawingGroupName")} editable={editable}
                        onChange={(item) => { setValue('DrawingGroupId', item.value, true) }}  />
                </Form.Field>
                <Form.Regist editable={editable} name="DrawingGroupId" rule={{required:'도면분류를 선택하세요.'}} error={errors.DrawingGroupId} />

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

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

                <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" />

                {!drawingId && (
                    <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;