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, Controller } 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 Accidents from '../Common/Accidents';
import Complaints from '../Common/Complaints';
import { Util } from '~/Utils/utils';
import { usePopup } from '~/Components/UIControls/Popup';
import WorkHistory from '../Common/WorkHistory';
import Materials from '../Common/Materials';
import Header from '~/Components/Layouts/Header';
import { View } from 'react-native';
import { useAuth } from '~/Components/Hooks';
import moment from 'moment';
import { UploadFileType } from '~/Components/UIControls/UploadFile';

const titleWidth = 100;

// 작업이력 관리
const Screen = ({ navigation }) => {
    const refreshList = navigation.getParam('refreshList', () => {});
    const siteId = navigation.getParam('siteId', '');
    const workRequestId = navigation.getParam('workRequestId', 0);
    const tab = navigation.getParam('tab', 'info');
    const { auth, userinfo, config } = useAuth(navigation);

    const [loading, setLoading] = useState(false);
    const [data, setData] = useState({});
    const [facilities, setFacilities] = useState([]);
    const [accidents, setAccidents] = useState([]);
    const [complaints, setComplaints] = useState([]);
    const { prompt } = usePrompt();
    const { showMessage } = useToast();

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

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

    // react hook form initialize
    const { register, setValue, handleSubmit, errors, getValues, control } = useForm();
    useLayoutEffect(() => {
        Form.setUseFormFunctions(register, setValue);
    }, [register]);

    // search
    const fetch = async () => {
        setLoading(true);

        try {
            const result = await fetchGet(`api/app/WorkHistory/Get?siteId=${siteId}&workRequestId=${workRequestId}`);
            setData(result);
            setFacilities(result.FmsWorkRequestToFacility);
            setAccidents(result.FmsWorkRequestToAccident);
            setComplaints(result.FmsWorkRequestToComplaint);
        } catch (error) {
            showMessage(error.message);
        }

        setLoading(false);
    };

    // delete
    const onDelete = () => {
        confirm('삭제', '삭제하시겠습니까?', async () => {
            try {
                await fetchDelete(`api/app/WorkResult/${siteId}/${workRequestId}`);

                showMessage('삭제되었습니다.');
                refreshList();
                navigation.pop();
            } catch (error) {
                console.log(error.message);
                showMessage(error.message);
            }
        });
    };

    const refresh = async () => {
        refreshList();
        fetch();
    };

    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="시설목록"
                            />
                        </TabTitleGroup>
                        <TabTitleGroup>
                            <TabTitle
                                onPress={() => {
                                    navigation.setParams({ tab: 'history' });
                                }}
                                active={tab == 'history' ? true : false}
                                title="작업이력"
                            />
                            {accidents && accidents.length > 0 && (
                                <TabTitle
                                    onPress={() => {
                                        navigation.setParams({ tab: 'accidents' });
                                    }}
                                    active={tab == 'accidents' ? true : false}
                                    title="사고목록"
                                />
                            )}
                            {complaints && complaints.length > 0 && (
                                <TabTitle
                                    onPress={() => {
                                        navigation.setParams({ tab: 'complaints' });
                                    }}
                                    active={tab == 'complaints' ? true : false}
                                    title="민원목록"
                                />
                            )}
                            <TabTitle
                                onPress={() => {
                                    navigation.setParams({ tab: 'material' });
                                }}
                                active={tab == 'material' ? true : false}
                                title="자재목록"
                            />
                        </TabTitleGroup>
                    </TabHeader>
                    <TabContent>
                        <TabItem active={tab == 'info' ? true : false}>
                            <Form.Container id="history-manage-form" onDelete={onDelete}>
                                <Form.Field>
                                    <Form.Title style={{ width: titleWidth }}>
                                        <Form.Label>지시제목</Form.Label>
                                    </Form.Title>
                                    <Controller
                                        control={control}
                                        name="Title"
                                        as={<Form.Input defaultValue={Util.get(data, 'Title')} editable={false} />}
                                    />
                                </Form.Field>

                                <Form.Field>
                                    <Form.Title style={{ width: titleWidth }}>
                                        <Form.Label>작업상태</Form.Label>
                                    </Form.Title>
                                    <Controller
                                        control={control}
                                        name="WorkProgress.Name"
                                        as={<Form.Input defaultValue={Util.get(data, 'WorkProgress.Name')} editable={false} />}
                                    />
                                </Form.Field>

                                <Form.Field>
                                    <Form.Title style={{ width: titleWidth }}>
                                        <Form.Label>작업예정일</Form.Label>
                                    </Form.Title>
                                    <Controller
                                        control={control}
                                        name="StartWorkDate"
                                        as={<Form.Input defaultValue={Util.getDateString(data, 'StartWorkDate')} editable={false} />}
                                    />
                                </Form.Field>
                                <Form.Field>
                                    <Form.Title style={{ width: titleWidth }}>
                                        <Form.Label></Form.Label>
                                    </Form.Title>
                                    <Controller
                                        name="WorkEndDate"
                                        control={control}
                                        as={<Form.DatePicker date={data.WorkEndDate} editable={false} />}
                                    />
                                </Form.Field>

                                <Form.Field>
                                    <Form.Title style={{ width: titleWidth }}>
                                        <Form.Label>작업일시</Form.Label>
                                    </Form.Title>
                                    <Controller
                                        control={control}
                                        name="FmsWorkResult.StartDate"
                                        as={
                                            <Form.Input
                                                defaultValue={Util.getDateTimeString(data, 'FmsWorkResult.StartDate')}
                                                editable={false}
                                            />
                                        }
                                    />
                                </Form.Field>

                                <Form.Field>
                                    <Form.Title style={{ width: titleWidth }}>
                                        <Form.Label></Form.Label>
                                    </Form.Title>
                                    <Controller
                                        control={control}
                                        name="FmsWorkResult.EndDate"
                                        as={
                                            <Form.Input
                                                defaultValue={Util.getDateTimeString(data, 'FmsWorkResult.EndDate')}
                                                editable={false}
                                            />
                                        }
                                    />
                                </Form.Field>

                                <Form.Field>
                                    <Form.Title style={{ width: titleWidth }}>
                                        <Form.Label>작업자</Form.Label>
                                    </Form.Title>
                                    <Controller
                                        control={control}
                                        name="FmsWorkResult.WorkerUserName"
                                        as={
                                            <Form.Input
                                                defaultValue={
                                                    Util.get(data, 'FmsWorkResult.WorkerUserName') +
                                                    (Util.get(data, 'WorkUsers') != null ? ' - ' + Util.get(data, 'WorkUsers') : '')
                                                }
                                                editable={false}
                                            />
                                        }
                                    />
                                </Form.Field>

                                <Form.Field>
                                    <Form.Title style={{ width: titleWidth }}>
                                        <Form.Label>업체명</Form.Label>
                                    </Form.Title>
                                    <Controller
                                        name="WorkPartnerName"
                                        control={control}
                                        as={<Form.Input defaultValue={data.WorkPartnerName} editable={false} />}
                                    />
                                </Form.Field>

                                <Form.Field>
                                    <Form.Title style={{ width: titleWidth }}>
                                        <Form.Label>금액</Form.Label>
                                    </Form.Title>
                                    <Controller
                                        name="WorkPrice"
                                        control={control}
                                        as={<Form.Input defaultValue={data.WorkPrice} editable={false} />}
                                    />
                                </Form.Field>

                                <Form.Field>
                                    <Form.TitleTop style={{ width: titleWidth }}>
                                        <Form.Label>신청내용</Form.Label>
                                    </Form.TitleTop>
                                    <Controller
                                        control={control}
                                        name="Content"
                                        as={<Form.Input defaultValue={Util.get(data, 'Content')} multiline={true} editable={false} />}
                                    />
                                </Form.Field>

                                {!config.UseWorkAutoOrder && (
                                    <Fragment>
                                        <Form.Field>
                                            <Form.TitleTop style={{ width: titleWidth }}>
                                                <Form.Label>지시내용</Form.Label>
                                            </Form.TitleTop>
                                            <Controller
                                                control={control}
                                                name="FmsWorkOrder.Content"
                                                as={
                                                    <Form.Input
                                                        defaultValue={Util.get(data, 'FmsWorkOrder.Content')}
                                                        multiline={true}
                                                        editable={false}
                                                    />
                                                }
                                            />
                                        </Form.Field>

                                        <Form.Field>
                                            <Form.TitleTop style={{ width: titleWidth }}>
                                                <Form.Label>작업요약</Form.Label>
                                            </Form.TitleTop>
                                            <Controller
                                                control={control}
                                                name="FmsWorkResult.Content"
                                                as={
                                                    <Form.Input
                                                        defaultValue={Util.get(data, 'FmsWorkResult.Content')}
                                                        multiline={true}
                                                        editable={false}
                                                    />
                                                }
                                            />
                                        </Form.Field>
                                    </Fragment>
                                )}

                                {data.WorkProgressId == 6 && (
                                    <Form.Field>
                                        <Form.TitleTop style={{ width: titleWidth }}>
                                            <Form.Label>승인내역</Form.Label>
                                        </Form.TitleTop>
                                        <Controller
                                            control={control}
                                            name="FmsWorkResult.ConfirmDesc"
                                            as={
                                                <Form.Input
                                                    defaultValue={Util.get(data, 'FmsWorkResult.ConfirmDesc')}
                                                    multiline={true}
                                                    editable={false}
                                                />
                                            }
                                        />
                                    </Form.Field>
                                )}

                                <Form.Field>
                                    <Form.TitleTop style={{ width: titleWidth }}>
                                        <Form.Label>첨부파일</Form.Label>
                                    </Form.TitleTop>
                                    <Controller
                                        name="CmFile"
                                        control={control}
                                        as={<Form.UploadFile type={UploadFileType.Image} editable={false} defaultFile={data.CmFile} />}
                                    />
                                </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>
                        <TabItem active={tab == 'history' ? true : false} lazy={true}>
                            <WorkHistory
                                siteId={siteId}
                                workRequestId={workRequestId}
                                startDate={Util.getDateString(data, 'FmsWorkResult.StartDate')}
                                endDate={Util.getDateString(data, 'FmsWorkResult.EndDate')}
                                editable={false}
                                creatable={false}
                                auth={auth}
                                onCallback={(action) => {
                                    refresh();
                                }}
                            />
                        </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>
                        )}
                        {complaints && complaints.length > 0 && (
                            <TabItem active={tab == 'complaints' ? true : false}>
                                <Complaints
                                    navigation={navigation}
                                    keys={{ SiteId: siteId, WorkRequestId: workRequestId }}
                                    complaints={complaints}
                                    setComplaints={setComplaints}
                                    editable={false}
                                />
                            </TabItem>
                        )}
                        <TabItem active={tab == 'material' ? true : false} alwaysReload={true}>
                            <Materials siteId={siteId} workRequestId={workRequestId} />
                        </TabItem>
                    </TabContent>
                </Tab>
                {loading && <Form.Loading />}
            </Fragment>
        </BottomTabBarLayout>
    );
};

Screen.navigationOptions = ({ navigation }) => {
    const readonly = navigation.getParam('readonly', false);
    const { auth } = useAuth(navigation);

    return {
        header: () => (
            <Header
                navigation={navigation}
                title={`이력관리`}
                main={false}
                buttons={
                    <Fragment>
                        {!readonly && auth.Update && <Form.DeleteButton id="history-manage-form" navigation={navigation} />}
                    </Fragment>
                }
            />
        ),
    };
};

export default Screen;
