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

const Screen = ({navigation, siteId, manualId}) => {
    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 [ready, setReady] = useState(false);
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState({});
    const { showMessage } = useToast();
    
    // mount
    useEffect(() => {
        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 () => {
        setLoading(true);
        await session.load();

        if(action != Form.CREATE) {
            try {
                const result = await fetchGet(`api/app/Manual/Get?siteId=${siteId}&manualId=${manualId}`);
                setData(result);
                Form.setFormData(result);
            } catch(error) {
                showMessage(error.message);
            }
        }

        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,
                ManualId: manualId,
            };
            console.log('submit data', submit);

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

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

                <Form.Field>
                    <Form.Require style={{width:90}}><Form.Label>매뉴얼분류</Form.Label></Form.Require>
                    <Form.EntitySelect entity="FmsManualGroup" defaultLabel="매뉴얼분류" 
                        id="ManualGroupId" name="Name" useCheck={true}
                        selectedValue={data.ManualGroupId} selectedText={data.ManualGroupName} editable={editable}
                        onChange={(item) => { setValue('ManualGroupId', item.value, true) }}  />
                </Form.Field>
                <Form.Regist editable={editable} name="ManualGroupId" rule={{required:'매뉴얼분류를 선택하세요.'}} error={errors.ManualGroupId} />
                <Form.Field>
                    <Form.Require style={{width:90}}><Form.Label>매뉴얼유형</Form.Label></Form.Require>
                    <Form.EntitySelect entity="FmsManualType" defaultLabel="매뉴얼유형" 
                        id="ManualTypeId" name="Name" useCheck={true}
                        selectedValue={data.ManualTypeId} selectedText={data.ManualTypeName} editable={editable}
                        onChange={(item) => { setValue('ManualTypeId', item.value, true) }}  />
                </Form.Field>
                <Form.Regist editable={editable} name="ManualTypeId" rule={{required:'매뉴얼유형을 선택하세요.'}} error={errors.ManualTypeId} />
                <Form.Field>
                    <Form.Require style={{width:90}}><Form.Label>매뉴얼번호</Form.Label></Form.Require>
                    <Form.Input placeholder="매뉴얼번호" defaultValue={data.ManualNo} onChangeText={text => setValue('ManualNo', text, true)} editable={editable} />
                </Form.Field>
                <Form.Regist editable={editable} name="ManualNo" rule={{required:'매뉴얼번호를 입력하세요.'}} error={errors.ManualNo} />

                <Form.Field>
                    <Form.Require style={{width:90}}><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 style={{width:90}}><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" />
                { action == Form.CREATE  && (
                    <Fragment>
                        <Form.Field>
                            <Form.RequireTop style={{width:90}}><Form.Label>매뉴얼파일</Form.Label></Form.RequireTop>
                            <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={Util.get(data, "CmFile")} rule={{required:'첨부파일을 선택하세요.'}} error={Util.get(errors, "CmFile.Name")} />
                    </Fragment>
                )}
                
                <Form.Field style={{ height:30 }}>
                </Form.Field>
                

            </Form.Container>
        ) : (
            <Form.Loading />
        )}
        </EmptyLayout>
    );
};

export default Screen;