import React, { Fragment, useState, useEffect, useLayoutEffect, useContext } from 'react';
import session from '~/Utils/session';
import fetchGet, { fetchPost, fetchDelete } from '~/Utils/fetch';
import { useToast, confirm, usePrompt } from '~/Components/UIControls/Message';
import Form from '~/Components/Form';
import { useForm } from 'react-hook-form';
import BottomTabBarLayout from '~/Components/Layouts/BottomTabBarLayout';
import { Tab, TabItem, TabTitleGroup, TabHeader, TabContent, TabTitle } from '~/Components/UIControls/Tab';
import Facilities from '~/Screens/Root/Facility/Common/Facilities';
import { Util } from '~/Utils/utils';
import { usePopup } from '~/Components/UIControls/Popup';
import FormProcess from './FormProcess';
import { useAuth } from '~/Components/Hooks';
import Accidents from '../Common/Accidents';

// 작업대기 관리 (base WorkOrder, next WorkResult)
const Screen = ({navigation}) => {
    const action = navigation.getParam('action', Form.VIEW);
    const refreshList = navigation.getParam('refreshList', ()=>{});
    const siteId = navigation.getParam('siteId', '');
    const workProgressId = navigation.getParam('workProgressId', 0);
    const workRequestId = navigation.getParam('workRequestId', 0);
    const tab = navigation.getParam('tab', 'info');
    const { auth } = useAuth(navigation);

    const [loading, setLoading] = useState(false);
    const [data, setData] = useState({});
    const [facilities, setFacilities] = useState([]);
    const [accidents, setAccidents] = useState([]);
    const { openPopup } = usePopup();
    const { showMessage } = useToast();

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

    // unmount
    useEffect(() => () => {
    }, []);
    
    // search
    const fetch = async () => {
        setLoading(true);
        await session.load();

        if(action != Form.CREATE) {
            try {
                const result = await fetchGet(`api/app/WorkOrder/Get?siteId=${siteId}&workRequestId=${workRequestId}`);
                setData(result);
                setFacilities(result.FmsWorkOrderToFacility);
                setAccidents(result.FmsWorkRequestToAccident);
            } catch(error) {
                showMessage(error.message);
            }
        }

        setLoading(false);
    }

    // 작업수행
    const onAction = async action => {
        openPopup(FormProcess, {siteId, workRequestId, data}, (result) => {
            refreshList();
            navigation.pop();
        });
    }

    return ( 
        <BottomTabBarLayout>
            <Fragment>
                <Tab>
                    <TabHeader>
                        <TabTitleGroup top={true}>
                            <TabTitle onPress={() => {
                                navigation.setParams({ tab: 'info' });
                            }} active={tab=='info'?true:false} title="업무내용" />
                            <TabTitle onPress={() => {
                                navigation.setParams({ tab: 'facilities' });
                            }} active={tab=='facilities'?true:false} title="시설목록" />
                            {accidents && accidents.length > 0 && (
                                <TabTitle onPress={() => {
                                    navigation.setParams({ tab: 'accidents' });
                                }} active={tab=='accidents'?true:false} title="사고목록" />
                            )}
                        </TabTitleGroup>
                    </TabHeader>
                    <TabContent>
                        <TabItem active={tab=='info'?true:false}>
                            <Form.Container id="work-wait-form" onAction={onAction}>
                                <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.Title><Form.Label>작업예정일</Form.Label></Form.Title>
                                    <Form.Input defaultValue={Util.getDateString(data, "WorkDueDate")} editable={false} />
                                </Form.Field>

                                <Form.Field>
                                    <Form.Title><Form.Label>작업시작일</Form.Label></Form.Title>
                                    <Form.Input defaultValue={Util.getDateString(data, "StartWorkDate")} editable={false} />
                                </Form.Field>

                                <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={Util.get(data, "Content")} 
                                        style={{height:100, textAlignVertical:'top', paddingTop:10, paddingBottom:10}}
                                        editable={false} />
                                </Form.Field>

                                <Form.Field>
                                    <Form.TitleTop><Form.Label>신청내용</Form.Label></Form.TitleTop>
                                    <Form.Input placeholder="신청내용" defaultValue={Util.get(data, "RequestContent")} 
                                        style={{height:100, textAlignVertical:'top', paddingTop:10, paddingBottom:10}}
                                        editable={false} />
                                </Form.Field>

                                <Form.Field style={{ height:30 }}>
                                </Form.Field>
                            </Form.Container>
                        </TabItem>
                        <TabItem active={tab=='facilities'?true:false}>
                            <Facilities navigation={navigation} 
                                keys={{SiteId:siteId, WorkRequestId: workRequestId}}
                                facilities={facilities} setFacilities={setFacilities} editable={false} />
                        </TabItem>
                        {accidents && accidents.length > 0 && (
                            <TabItem active={tab=='accidents'?true:false}>
                                <Accidents navigation={navigation} 
                                    keys={{SiteId:siteId, WorkRequestId: workRequestId}}
                                    accidents={accidents} setAccidents={setAccidents} editable={false} />
                            </TabItem>
                        )}
                    </TabContent>
                </Tab>
                {loading && <Form.Loading />}
            </Fragment>
        </BottomTabBarLayout>
    );
};

Screen.navigationOptions = ({navigation}) => { 
    const action = navigation.getParam('action', Form.VIEW);    // create, edit, view
    const workProgressId = navigation.getParam('workProgressId', 0);
    const { auth } = useAuth(navigation);

    return { 
        header: () => (
            <Header 
                navigation={navigation} 
                title={`작업대기 관리`}
                main={false}
                buttons={
                    <Fragment>
                        <Fragment>
                            {auth.Update && workProgressId != 7 && <Form.ActionButton id="work-wait-form" navigation={navigation} type="success" action="process" title="작업수행" />}
                        </Fragment>
                    </Fragment>
                }
            /> 
        )
    } 
};

export default Screen;