import React, {Fragment, useState, useEffect, useLayoutEffect } from 'react';
import session from '~/Utils/session';
import fetchGet, { fetchPost, fetchDelete } from '~/Utils/fetch';
import { Search, SearchIcon, Line, TextInput, checkFilter, filterValue, ListStyle, DetailIcon, RightArrow, CreateButton, SearchBoxIcon, DefaultButton, PrimaryButton } from '~/Components/Listing/Search';
import { DefaultAction } from '~/Components/UIControls/Popup/Context';
import { PopupLayout, useLayoutAction } from '~/Components/Layouts/PopupLayout';
import { useToast, confirm } from '~/Components/UIControls/Message';
import { UploadFileType } from '~/Components/UIControls/UploadFile';
import Form from '~/Components/Form';
import { useForm } from 'react-hook-form';
import EmptyLayout from '~/Components/Layouts/EmptyLayout';
import { Util } from '~/Utils/utils';

const Screen = ({refreshList, siteId, manualId, historyId, isView, isCreate, popup=DefaultAction}) => {
    const [loading, setLoadingValue] = useState(false);
    const [data, setData] = useState({});    
    const [editable,setEditable] = useState(isCreate);
    const { showMessage } = useToast();
    //

    const setLoading = (value) => {
        console.log('===============> change loading ', value);
        setLoadingValue(value);
    }

    
    // mount
    useEffect(() => {
        fetch();
    }, [editable]);

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

    // react hook form initialize
    const { register, setValue, handleSubmit, errors, getValues } = useForm();

    if(isCreate){
        setValue('UpdatedUserId', session.getUserInfo("UserId"), true);
    }

    useLayoutEffect(() => {
        Form.setUseFormFunctions(register, setValue);
    }, [register]);
    
    // search
    const fetch = async () => {
        setLoading(true);
        await session.load();

        if(true) {
            try {
                console.log(`api/app/ManualHistory/Get?siteId=${siteId}&manualId=${manualId}&historyId=${historyId}&userId=${session.getUserInfo("UserId")}&isCreate=${isCreate}`);
                const result = await fetchGet(`api/app/ManualHistory/Get?siteId=${siteId}&manualId=${manualId}&historyId=${historyId}&userId=${session.getUserInfo("UserId")}&isCreate=${isCreate}`);
                setData(result);
                Form.setFormData(result);
            } catch(error) {
                showMessage(error.message);
            }
        }

        setLoading(false);
    }

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

    // header button handler
    const actionHandler = (action, parameter = {}) => {
        console.log('in actionhandler - loading : ', loading);
        const actions = {
            onSave: () => {
                console.log('in actionhandler 2 - loading : ', loading);
                const submit = handleSubmit(onSave);
                console.log('in actionhandler 3 - loading : ', loading);
                submit();
                console.log('in actionhandler 4 - loading : ', loading);
            },
            close: () => {
                console.log('close...');
                popup.close();
            },
        }
        actions[action]();
    }

    // save
    const onSave = async form => {
        console.log('여기 온다', loading);
        if(loading) {
            showMessage('저장중입니다. 잠시만기다려 주세요.');
            return;
        }
        confirm('저장', '저장하시겠습니까?', async () => {
            setLoading(true);
            console.log('manualId : ' + manualId);
            const submit = {...form,
                SiteId: siteId,
                ManualId: manualId,
                HistoryId: historyId
            };
            console.log('submit data', submit);

            try {
                const result = await fetchPost('api/app/ManualHistory/Save', submit);

                showMessage('저장되었습니다.');
                refreshList();
                if(isCreate) {
                    popup.close();
                } else {
                    setEditable(false);
                }
            } catch(error) {
                showMessage(error.message);
            }
            setLoading(false);
        });
    }

    console.log('Values : ', getValues());
    console.log('CmFile : ', Util.get(data, "CmFile"));
    console.log(errors);
    return ( 
        <EmptyLayout>
            <PopupLayout title={`매뉴얼 이력 ${isCreate ? '추가':(editable?'변경':'')}`} 
                header={Header} headerProps={{isCreate,editable,setEditable}} actionHandler={actionHandler}>
            <Form.Container noEvent={true}>
                <Form.Field>
                    <Form.Title><Form.Label>Rev.번호</Form.Label></Form.Title>
                    <Form.Input placeholder="Rev.번호" defaultValue={data.RevisionNo} onChangeText={text => setValue('RevisionNo', text, true)} editable={false} />
                </Form.Field>
                <Form.Regist editable={editable} name="RevisionNo"/>
                { isCreate && (
                <Form.Field>
                    <Form.Title><Form.Label>이름</Form.Label></Form.Title>
                    <Form.Input placeholder="이름" defaultValue={session.getUserInfo("UserId")} onChangeText={text => setValue('UpdatedUserId', text, true)} editable={false} />
                    <Form.Regist editable={editable} name="UpdatedUserId" rule={{required:'이름을 입력하세요.'}} error={errors.UpdatedUserId} />
                </Form.Field>
                )}
                { !isCreate && (
                <Form.Field>
                    <Form.Title><Form.Label>이름</Form.Label></Form.Title>
                    <Form.Input placeholder="이름" defaultValue={data.UpdatedUserId} onChangeText={text => setValue('UpdatedUserId', text, true)} editable={false} />
                    <Form.Regist editable={editable} name="UpdatedUserId" rule={{required:'이름을 입력하세요.'}} error={errors.UpdatedUserId} />
                </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} numberOfLines={3} style={{height:100, textAlignVertical:'top'}}
                        editable={editable} />
                </Form.Field>
                <Form.Regist editable={editable} name="Description" />
                <Form.Field>
                    <Form.RequireTop><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")} />

                <Form.Field style={{ height:30 }}>
                </Form.Field>
            </Form.Container>
            </PopupLayout>
            {loading && <Form.Loading />}
        </EmptyLayout>
    );
    
};

const Header = ({isCreate,editable,setEditable}) => {
    const { callAction } = useLayoutAction();
    return (
        <Fragment>
            {(() => {
                if(isCreate){
                    return (
                        <Fragment>
                            <PrimaryButton onPress={() => { callAction('onSave') }}>등록</PrimaryButton>
                            <DefaultButton onPress={() => { callAction('close') }}>닫기</DefaultButton>
                        </Fragment>
                    )
                }else{
                    if(editable){
                        return (
                            <Fragment>
                                <PrimaryButton onPress={() => { callAction('onSave') }}>저장</PrimaryButton>
                                <DefaultButton onPress={() => { setEditable(false) }}>취소</DefaultButton>
                                <DefaultButton onPress={() => { callAction('close') }}>닫기</DefaultButton>
                            </Fragment>
                        )
                    }
                    else{
                        return (
                            <Fragment>
                                <PrimaryButton onPress={() => { setEditable(true) }}>편집</PrimaryButton>
                                <DefaultButton onPress={() => { callAction('close') }}>닫기</DefaultButton>
                            </Fragment>
                        )
                    }
                }
            })()}
        </Fragment>
    )
}

export default Screen;