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 WorkHistory from '../Common/WorkHistory';
import Materials from '../Common/Materials';
import Header from '~/Components/Layouts/Header';
import { useAuth } from '~/Components/Hooks';
import Accidents from '../Common/Accidents';
import { View } from 'react-native';

// 작업진행 관리 (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 workRequestId = navigation.getParam('workRequestId', 0);
    const workProgressId = navigation.getParam('workProgressId', 4);
    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 { prompt } = usePrompt();
    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/WorkResult/Get?siteId=${siteId}&workRequestId=${workRequestId}`);
                setData(result);
                setFacilities(result.FmsWorkResultToFacility);
                setAccidents(result.FmsWorkRequestToAccident);
                navigation.setParams({workProgressId: result.WorkProgressId});
            } catch(error) {
                showMessage(error.message);
            }
        }

        setLoading(false);
    }

    // action receive
    const onAction = async (action) => {
        console.log('onAction - ', action);
        if(action == 'continue') {
            continueWork();
        } else if(action == 'reject') {
            rejectWork();
        }
    }

    // 작업 진행
    const continueWork = async () => {
        if(loading) {
            showMessage('처리중입니다. 잠시만기다려주세요.');
            return;
        }
        confirm('작업 재진행', '작업보류를 작업진행으로 변경하시겠습니까?', async () => {
            setLoading(true);

            try {
                const result = await fetchPost(`api/app/WorkResult/Continue`, { SiteId: siteId, WorkRequestId: workRequestId });
                refreshList();
                navigation.pop();
            } catch(error) {
                showMessage(error.message);
            }

            setLoading(false);
        });
    }

    const rejectProcess = (reason, useSchedule=false, confirmDate=new Date(), promptConfirmEvent=null) => {
        confirm('반려', '반려하시겠습니까?', async () => {
            if(promptConfirmEvent != null && promptConfirmEvent.close) {
                promptConfirmEvent.close();
            }

            setLoading(true);

            try {
                console.log('.');
                console.log('.');
                console.log(`#################################################################################`);
                console.log(`api/app/WorkRequest/Reject?useSchedule=${useSchedule}&confirmDate=${confirmDate}`);
                console.log('.');
                console.log('.');
                const result = await fetchPost(`api/app/WorkRequest/Reject?useSchedule=${useSchedule}&confirmDate=${confirmDate}`, { 
                    SiteId: siteId, 
                    WorkRequestId: workRequestId,
                    RejectReason: reason,
                    RejectUserId: session.getUserInfo("UserId"),
                });
                refreshList();
                navigation.pop();
            } catch(error) {
                showMessage(error.message);
            }

            setLoading(false);
        });
    }

    // 반려 처리
    const rejectWork = async () => {
        if(loading) {
            showMessage('처리중입니다. 잠시만기다려주세요.');
            return;
        }

        if([1,2].includes(data.WorkTypeId)) {
            const avail = await fetchGet(`api/app/WorkResult/GetAvailDueDate?siteId=${siteId}&workRequestId=${workRequestId}`);
            console.log("getavailduedate : ", avail);

            prompt({title:'반려사유입력', message: '반려사유를 입력하세요.', 
                defaultValue:{reason:'', useSchedule:avail.IsUse, confirmDate:avail.WorkDueDate},
                component:PromptContent, componentProps:{initialDate:avail.WorkDueDate, minimumDate:avail.EndDate, initialIsUse:avail.IsUse},
                confirm: (value, event) => {
                    event.autoClose = false;
                    rejectProcess(value.reason, value.useSchedule, value.confirmDate, event);
                }
            });
        } else {
            prompt({title:'반려사유입력', message: '반려사유를 입력하세요.', 
                confirm: (text, event) => {
                    event.autoClose = false;
                    rejectProcess(text, false, null, event);
                }
            });
        }
    }

    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>
                            {accidents && accidents.length > 0 && (
                                <TabTitle onPress={() => {
                                    navigation.setParams({ tab: 'accidents' });
                                }} active={tab=='accidents'?true:false} title="사고목록" />
                            )}
                            <TabTitle onPress={() => {
                                navigation.setParams({ tab: 'history' });
                            }} active={tab=='history'?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="work-process-form" onAction={onAction}>
                                <Form.Field>
                                    <Form.Title><Form.Label>업무명</Form.Label></Form.Title>
                                    <Form.Input defaultValue={Util.get(data, "Title")} 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, "StartDate")} editable={false} />
                                </Form.Field>

                                <Form.Field>
                                    <Form.Title><Form.Label>종료일</Form.Label></Form.Title>
                                    <Form.Input defaultValue={Util.getDateString(data, "EndDate")} editable={false} />
                                </Form.Field>

                                <Form.Field>
                                    <Form.Title><Form.Label>작업자</Form.Label></Form.Title>
                                    <Form.Input defaultValue={Util.get(data, "WorkerUser.Name")} 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 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>
                        )}
                        <TabItem active={tab=='history'?true:false} lazy={true}>
                            <WorkHistory siteId={siteId} workRequestId={workRequestId} 
                                startDate={Util.getDateString(data, "StartDate")}
                                endDate={Util.getDateString(data, "EndDate")} auth={auth}
                                editable={workProgressId==7?false:true} 
                                onCallback={(action) => {
                                    console.log('onCallback - action : ' + action);
                                    refresh();
                                    if(action == 'close') {
                                        navigation.pop();
                                    }
                                }} />
                        </TabItem>
                        <TabItem active={tab=='material'?true:false} alwaysReload={true}>
                            <Materials siteId={siteId} workRequestId={workRequestId} />
                        </TabItem>
                    </TabContent>
                </Tab>
                {loading && <Form.Loading />}
            </Fragment>
        </BottomTabBarLayout>
    );
};

const PromptContent = ({onChange=(value)=>{}, initialDate=new Date(), minimumDate=new Date(), initialIsUse=true}) => {
    const [result, setResult] = useState({reason:'', useSchedule:initialIsUse, confirmDate:initialDate});

    useEffect(() => {
        onChange(result);
    }, [result]);

    return (
        <View style={{paddingTop:10, paddingBottom:10, height:250}}>
            <Form.Field>
                <Form.Title><Form.Label>계획사용</Form.Label></Form.Title>
                <Form.Switch initialValue={result.useSchedule} onValueChange={(newValue) => {
                    setResult({...result, useSchedule:newValue});
                }} />
            </Form.Field>
            {result.useSchedule && (
                <Form.Field>
                    <Form.Title><Form.Label>확정일자</Form.Label></Form.Title>
                    <Form.DatePicker date={initialDate} minimumDate={Util.toDate(minimumDate)} placeholder="확정일자" onChange={(date) => {
                        setResult({...result, confirmDate:date});
                    }} />
                </Form.Field>
            )}
            <Form.Field>
                <Form.TitleTop><Form.Label>반려사유</Form.Label></Form.TitleTop>
                <Form.Input style={{height:100}} placeholder="반려사유" returnKeyType="next" multiline={true} onChangeText={text => {
                    setResult({...result, reason:text});
                }} />
            </Form.Field>
        </View>
    )
}

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

    console.log("workTypeId:", workTypeId);

    return { 
        header: () => (
            <Header 
                navigation={navigation} 
                title={`작업진행 관리`}
                main={false}
                buttons={
                    auth.Update && (
                        <Fragment>
                            {workProgressId == 7 /* 보류 */ ? (
                                <Form.ActionButton id="work-process-form" navigation={navigation} type="success" action="continue" title="작업진행" />
                            ) : (
                                auth.Action1 ? (
                                    <Form.ActionButton id="work-process-form" navigation={navigation} type="error" action="reject" title="반려" />
                                ) : (
                                    <Fragment />
                                )
                            )}
                        </Fragment>
                    )
                }
            /> 
        )
    } 
};

export default Screen;