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 Header from '~/Components/Layouts/Header';
import { UploadFileType } from '~/Components/UIControls/UploadFile';

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', 0);
    const drawingId = navigation.getParam('drawingId', 0);
    const historyId = navigation.getParam('historyId', 0);
    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/DrawingHistory/${siteId}/${drawingId}/${historyId}`);
                setData(result);
                Form.setFormData(result);
                setEditable(editable);
            } catch(error) {
                showMessage(error.message);
            }
        } else {
            try {
                const nextRevisionNo = await fetchGet(`api/DrawingHistory/${siteId}/${drawingId}`);
                const result = { RevisionNo: nextRevisionNo };
                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,
                HistoryId: historyId,
                UpdatedUserId: userinfo.UserId
            };
            console.log('submit data', submit);

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

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

    const getName = () => {
        if(action == Form.CREATE) {
            return session.getUserInfo("Name");
        } else {
            return Util.get(data, "CmUser.Name");
        }
    }

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

                <Form.Field>
                    <Form.Require><Form.Label>Rev. 번호</Form.Label></Form.Require>
                    <Form.Input placeholder="번호" defaultValue={data.RevisionNo} editable={false} />
                </Form.Field>
                <Form.Regist editable={false} name="RevisionNo" />

                <Form.Field>
                    <Form.Require><Form.Label>이름</Form.Label></Form.Require>
                    <Form.Input placeholder="이름" defaultValue={getName()} editable={false} />
                </Form.Field>

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

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

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

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

const ScreenHeader = ({navigation}) => {
    const action = navigation.getParam('action', Form.VIEW);    // create, edit, view
    const editable = navigation.getParam('editable', action == Form.VIEW ? false : true);
    const { auth, userinfo } = useAuth(navigation);

    return (
        <Header 
            navigation={navigation} 
            title={`도면이력정보`}
            main={false}
            buttons={
                <Fragment>
                {!editable && (
                    <Fragment>
                        {auth.Update && (<Form.EditButton id="drawinghistory-form" navigation={navigation} type="primary" />)}
                        {auth.Delete && (<Form.DeleteButton id="drawinghistory-form" />)}
                    </Fragment>
                )}
                {editable && (
                    <Fragment>
                        {auth.Update && (<Form.SaveButton id="drawinghistory-form" type="primary" />)}
                        {action != Form.CREATE && auth.Update && <Form.CancelEditButton id="drawinghistory-form" navigation={navigation} />}
                    </Fragment>
                )}
                </Fragment>
            }
        /> 
    )
}

Screen.navigationOptions = ({navigation}) => { 
    return { 
        header: () => (
            <ScreenHeader navigation={navigation} />
        )
    } 
};

export default Screen;