import React, { Fragment, useState, useEffect, useLayoutEffect } from 'react';
import session from '~/Utils/session';
import { useToast, confirm } from '~/Components/UIControls/Message';
import Form from '~/Components/Form';
import { useForm } from 'react-hook-form';
import { Util } from '~/Utils/utils';
import { PopupLayout, useLayoutAction } from '~/Components/Layouts/PopupLayout';
import { PrimaryButton, DefaultButton } from '~/Components/Listing/Search';
import { DefaultAction } from '~/Components/UIControls/Popup/Context';
import { fetchPost } from '~/Utils/fetch';

// 작업대기 관리 (base WorkOrder, next WorkResult)
export default Screen = ({siteId, workRequestId, data, popup=DefaultAction}) => {
    const [loading, setLoading] = useState(false);
    const { showMessage } = useToast();

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

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

    // react hook form initialize
    const { register, setValue, handleSubmit, errors, getValues } = useForm();
    useLayoutEffect(() => {
        Form.setUseFormFunctions(register, setValue);
    }, [register]);
    
    // search
    const load = async () => {
        setLoading(true);
        await session.load();
        setLoading(false);
    }

    // header action handler
    const actionHandler = (action, parameter = {}) => {
        const actions = {
            onClose: () => {
                popup.close();
            },
            onProcess: () => {
                const submit = handleSubmit(process);
                submit();
            },
        }
        actions[action]();
    }

    // 작업수행
    const process = async form => {
        if(loading) {
            showMessage('작업수행중입니다. 잠시만기다려 주세요.');
            return;
        }
        confirm('작업수행', '작업수행 처리 하시겠습니까?', async () => {
            setLoading(true);
            const submit = {
                ...form,
                SiteId: siteId,
                WorkRequestId: workRequestId,
                WorkerUserId: session.getUserInfo("UserId"),
            };
            try {
                await fetchPost(`api/app/WorkOrder/Process`, submit);
                showMessage('처리되었습니다.');
                popup.select();
            } catch(error) {
                showMessage(error.message);
            }
            setLoading(false);
        });
    }

    return ( 
        <PopupLayout title="작업수행" header={Header} actionHandler={actionHandler}>
            <Fragment>
                <Form.Container noEvent={true}>
                    <Form.Field>
                        <Form.Title><Form.Label>업무분야</Form.Label></Form.Title>
                        <Form.Input defaultValue={Util.get(data, "BusinessField.Name")} editable={false} />
                    </Form.Field>

                    <Form.Field>
                        <Form.Title><Form.Label>작업구분</Form.Label></Form.Title>
                        <Form.Input defaultValue={Util.get(data, "WorkType.Name")} editable={false} />
                    </Form.Field>

                    <Form.Field>
                        <Form.Title><Form.Label>작업상태</Form.Label></Form.Title>
                        <Form.Input defaultValue={Util.get(data, "WorkProgress.Name")} editable={false} />
                    </Form.Field>

                    <Form.Field>
                        <Form.Require><Form.Label>작업시작일</Form.Label></Form.Require>
                        <Form.DatePicker date={Util.getDateString(data, "StartWorkDate")} minimumDate={Util.getDate(data, "StartWorkDate")}
                                        onChange={(newDate) => setValue('StartDate', newDate, true)} editable={true} />
                    </Form.Field>
                    <Form.Regist editable={true} name="StartDate" value={Util.getDateString(data, "StartWorkDate")} 
                        rule={{required:'작업시작일을 선택하세요.'}} error={errors.StartDate} />

                    <Form.Field>
                        <Form.Require><Form.Label>종료예정일</Form.Label></Form.Require>
                        <Form.DatePicker date={Util.getDateString(data, "StartWorkDate")} minimumDate={Util.getDate(data, "StartWorkDate")}
                                        onChange={(newDate) => setValue('EndDate', newDate, true)} editable={true} />
                    </Form.Field>
                    <Form.Regist editable={true} name="EndDate" value={Util.getDateString(data, "StartWorkDate")}
                        rule={{required:'종료예정일을 선택하세요.'}} error={errors.EndDate} />

                    <Form.Field>
                        <Form.Title><Form.Label>작업지시자</Form.Label></Form.Title>
                        <Form.Input defaultValue={Util.get(data, "OrderUser.Name")} editable={false} />
                    </Form.Field>

                    <Form.Field>
                        <Form.Title><Form.Label>지시제목</Form.Label></Form.Title>
                        <Form.Input defaultValue={Util.get(data, "Title")} editable={false} />
                    </Form.Field>

                    <Form.Field>
                        <Form.TitleTop><Form.Label>작업요약</Form.Label></Form.TitleTop>
                        <Form.Input placeholder="작업요약" defaultValue={data.Content} 
                                        onChangeText={text => setValue('Content', text, true)} 
                                        multiline={true} editable={true} />
                    </Form.Field>
                    <Form.Regist editable={true} name="Content" value={data.Content} />

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

const Header = () => {
    const { callAction } = useLayoutAction();

    return (
        <Fragment>
            <PrimaryButton style={{marginRight:5}} onPress={() => { callAction('onProcess') }}>수행</PrimaryButton>
            <DefaultButton onPress={() => { callAction('onClose') }}>닫기</DefaultButton>
        </Fragment>
    )
}
