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 { 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, Text } from 'react-native';
import { useAuth } from '~/Components/Hooks';
import Accidents from '../Common/Accidents';
import Theme from '~/Themes';
import { UploadFileType } from '~/Components/UIControls/UploadFile';


const PromptContent = ({
    nextWork=false, title='', message='', form={}, siteId=0, workRequestId=0,
    defaultValue={}, initialDate=new Date(), minimumDate=new Date(),
    navigation=null, setLoading=()=>{}, refreshList=()=>{}, setPromptParams=()=>{}
}) => {

    const { openPopup, closePopup } = usePopup();
    const [ data, setData ] = useState(defaultValue);
    const [ partnerName, setPartnerName ] = useState('');

    const { register, setValue, handleSubmit, errors, getValues, control } = useForm();
    useLayoutEffect(() => {
    }, [register]);


    const confirmProcess = async (confirmForm) => {
        console.log('confirm form - ', confirmForm);

        confirm('승인', '승인처리 하시겠습니까?', async () => {
            setLoading(true);
            try {
                const result = await fetchPost(`api/app/WorkResult/Confirm?date=${Util.toDateString(confirmForm.WorkDueDate)}`, { 
                    ...form,
                    ...confirmForm,
                    SiteId: siteId, 
                    WorkRequestId: workRequestId,
                });
                refreshList();
                navigation.pop();
            } catch(error) {
                showMessage(error.message);
            }
            setLoading(false);
        });
    }

    return (
        <>
            <View style={{position:"absolute",left:0,top:0,right:0,bottom:0, backgroundColor:'black', opacity:0.6}} />
            <View style={{position:"absolute",left:0,top:0,right:0,bottom:0, flexDirection:'column', alignItems:'center', justifyContent:'center'}}>
                <View style={{position:"relative", width:'90%', backgroundColor:'white', padding:20, borderRadius:5, overflow:'hidden'}}>
                    <View style={{}}>
                        <Text style={{fontFamily:Theme.Fonts.Regular, fontSize:20, marginBottom:20}}>{title}</Text>
                        <Text style={{fontFamily:Theme.Fonts.Regular, fontSize:14, marginBottom:10}}>{message}</Text>
                    </View>
                    {nextWork && (
                        <>
                            <Form.Field>
                                <Controller name="WorkDueDate" defaultValue={defaultValue.workDueDate} control={control} rules={{required:'확정일자를 선택하세요.'}}
                                    as={
                                        <Form.DatePicker date={defaultValue.workDueDate} minimumDate={Util.toDate(minimumDate)} placeholder="확정일자" 
                                            onChange={(date) => {
                                                setValue('WorkDueDate', date);
                                            }} />
                                    } />
                            </Form.Field>
                            <Form.Error message={Util.get(errors, 'WorkDueDate')} />
                        </>
                    )}
                    <Form.Field>
                        <Controller name="FmsWorkRequest.WorkUsers" control={control} rules={{required:'작업자를 입력하세요.'}}
                            as={
                                <Form.Input placeholder="작업자" defaultValue={defaultValue.workUsers} onChangeText={(text) => {
                                    setValue('FmsWorkRequest.WorkUsers', text);
                                }} />
                            } />
                    </Form.Field>
                    <Form.Error message={Util.get(errors, 'FmsWorkRequest.WorkUsers')} />

                    <Form.Field>
                        <Controller name="FmsWorkRequest.WorkPartnerId" control={control} rules={{required:'거래처를 선택하세요.'}}
                            as={
                                <Form.SelectButton defaultLabel="거래처"
                                    selectedLabel={partnerName}
                                    onPress={() => { 
                                        openPopup('/Popup/Partner/Index', {navigation, siteId}, (result) => {
                                            console.log('거래처 선택 - ', result);
                                            setValue('FmsWorkRequest.WorkPartnerId', result.PartnerId);
                                            setPartnerName(result.Name);
                                        });
                                    }}
                                />
                            } />
                    </Form.Field>
                    <Form.Error message={Util.get(errors, 'FmsWorkRequest.WorkPartnerId')} />

                    <Form.Field>
                        <Controller name="FmsWorkRequest.WorkStartDateTime" control={control} rules={{required:'시작일시를 선택하세요.'}}
                            as={
                                <Form.Input placeholder="시작일시" defaultValue={defaultValue.workStartDateTime} onChangeText={(text) => {
                                    setValue('FmsWorkRequest.WorkStartDateTime', text);
                                }} />
                            } />
                    </Form.Field>
                    <Form.Error message={Util.get(errors, 'FmsWorkRequest.WorkStartDateTime')} />

                    <Form.Field>
                        <Controller name="FmsWorkRequest.WorkEndDateTime" control={control} rules={{required:'종료일시를 선택하세요.'}}
                            as={
                                <Form.Input placeholder="종료일시" defaultValue={defaultValue.workEndDateTime} onChangeText={(text) => {
                                    setValue('FmsWorkRequest.WorkEndDateTime', text);
                                }} />
                            } />
                    </Form.Field>
                    <Form.Error message={Util.get(errors, 'FmsWorkRequest.WorkEndDateTime')} />

                    <Form.Field>
                        <Form.ButtonGroup style={{position:"relative", paddingRight:0}}>
                            <Form.DefaultButton onPress={() => { setPromptParams({show:false}) }}>취소</Form.DefaultButton>
                            <Form.PrimaryButton onPress={handleSubmit(confirmProcess)}>승인</Form.PrimaryButton>
                        </Form.ButtonGroup>
                    </Form.Field>
                </View>
            </View>
        </>
    )
}

// 작업완료 관리 
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 } = useAuth(navigation);

    const [loading, setLoading] = useState(false);
    const [data, setData] = useState({});
    const [facilities, setFacilities] = useState([]);
    const [accidents, setAccidents] = useState([]);
    const { prompt } = usePrompt();
    const { showMessage } = useToast();
    const [promptParams, setPromptParams] = useState({
        show: false,
        nextWork: false,
        title: '',
        message: '',
        form: {},
        siteId: 0,
        workRequestId: 0,
        defaultValue: {},
        initialDate: new Date(),
        minimumDate: new Date(),
    });

    // 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/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 == 'approval') {
            handleSubmit(confirmWork)();
        }
    }

    // 승인 처리
    const confirmWork = async (form) => {
        // 차기 계획일자 입력받은후 승인처리
        if(loading) {
            showMessage('처리중입니다. 잠시만기다려주세요.');
            return;
        }

        if(data.WorkScheduleId) {
            setLoading(true);
            const result = await fetchGet(`api/app/WorkResult/GetAvailDueDate?siteId=${siteId}&workRequestId=${workRequestId}`);
            console.log("getavailduedate : ", result);
            setLoading(false);
            setPromptParams({
                show: true,
                nextWork: true,
                title: '확정일 및 추가정보 입력',
                message: '차기작업 확정일자 및 추가정보를 입력하세요.',
                form: {...form},
                siteId: siteId,
                workRequestId: workRequestId,
                defaultValue: { 
                    workDueDate: result.WorkDueDate,
                    workUsers: '',
                    workParentId: null,
                    workStartDateTime: '',
                    workEndDateTime: '',
                },
                initialDate: result.WorkDueDate,
                minimumDate: result.EndDate,
            });
        } else {
            setPromptParams({
                show: true,
                nextWork: false,
                title: '추가정보 입력',
                message: '작업 추가정보를 입력하세요.',
                form: {...form},
                siteId: siteId,
                workRequestId: workRequestId,
                defaultValue: { 
                    workUsers: '',
                    workParentId: null,
                    workStartDateTime: '',
                    workEndDateTime: '',
                },
                initialDate: null,
                minimumDate: null,
            });
        }
    }

    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-complete-form" onAction={onAction}>
                                    <Form.Field>
                                        <Form.Title><Form.Label>업무명</Form.Label></Form.Title>
                                        <Controller name="Title" control={control}
                                            as={<Form.Input defaultValue={Util.get(data, "Title")} editable={false} />}
                                        />
                                    </Form.Field>

                                    <Form.Field>
                                        <Form.Title><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><Form.Label>금액</Form.Label></Form.Title>
                                        <Controller name="WorkPrice" control={control}
                                            as={<Form.Input defaultValue={data.WorkPrice} editable={false} />}
                                        />
                                    </Form.Field>

                                    <Form.Field>
                                        <Form.Title><Form.Label>종료예정일</Form.Label></Form.Title>
                                        <Controller name="WorkEndDate" control={control}
                                            as={<Form.DatePicker date={data.WorkEndDate} editable={false} />}
                                        />
                                    </Form.Field>

                                    <Form.Field>
                                        <Form.TitleTop><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>
                                        <Form.Title><Form.Label>작업상태</Form.Label></Form.Title>
                                        <Controller name="WorkProgress.Name" control={control}
                                            as={<Form.Input defaultValue={Util.get(data, "WorkProgress.Name")} editable={false} />}
                                        />
                                    </Form.Field>

                                    <Form.Field>
                                        <Form.Title><Form.Label>작업예정일</Form.Label></Form.Title>
                                        <Controller name="WorkDueDate" control={control}
                                            as={<Form.Input defaultValue={Util.getDateString(data, "WorkDueDate")} editable={false} />}
                                        />
                                    </Form.Field>

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

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

                                    <Form.Field>
                                        <Form.Title><Form.Label>작업자</Form.Label></Form.Title>
                                        <Controller name="WorkerUser.Name" control={control}
                                            as={<Form.Input defaultValue={Util.get(data, "WorkerUser.Name")} editable={false} />}
                                        />
                                    </Form.Field>

                                    <Form.Field>
                                        <Form.TitleTop><Form.Label>신청내용</Form.Label></Form.TitleTop>
                                        <Controller name="FmsWorkRequest.Content" control={control}
                                            as={
                                                <Form.Input placeholder="신청내용" defaultValue={Util.get(data, "FmsWorkRequest.Content")} 
                                                    onChangeText={(text) => {
                                                        setValue("FmsWorkRequest.Content", text);
                                                    }}
                                                    multiline={true} editable={true} />
                                            }
                                        />
                                    </Form.Field>
                                    <Form.Regist name="FmsWorkRequest.Content" value={Util.get(data, "FmsWorkRequest.Content")} />

                                    <Form.Field>
                                        <Form.TitleTop><Form.Label>지시내용</Form.Label></Form.TitleTop>
                                        <Controller name="FmsWorkOrder.Content" control={control}
                                            as={
                                                <Form.Input placeholder="지시내용" defaultValue={Util.get(data, "FmsWorkOrder.Content")} 
                                                    onChangeText={(text) => {
                                                        setValue("FmsWorkOrder.Content", text);
                                                    }}
                                                    multiline={true} editable={true} />
                                            }
                                        />
                                    </Form.Field>
                                    <Form.Regist name="FmsWorkOrder.Content" value={Util.get(data, "FmsWorkOrder.Content")} />

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

                                    <Form.Field>
                                        <Form.TitleTop><Form.Label>승인내역</Form.Label></Form.TitleTop>
                                        <Controller name="ConfirmDesc" control={control}
                                            as={                                    
                                                <Form.Input placeholder="승인내역" defaultValue={Util.get(data, "ConfirmDesc")} 
                                                    onChangeText={(text) => {
                                                        setValue("ConfirmDesc", text);
                                                    }}
                                                    multiline={true} editable={true} />
                                            }
                                        />
                                    </Form.Field>
                                    <Form.Regist name="ConfirmDesc" value={Util.get(data, "ConfirmDesc")} />

                                    <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")} 
                                    editable={true} creatable={false} auth={auth} 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>
            {promptParams.show && (
                <PromptContent navigation={navigation} setLoading={setLoading} refreshList={refreshList} setPromptParams={setPromptParams} {...promptParams} />
            )}
        </>
    );
};

Screen.navigationOptions = ({navigation}) => { 
    const { auth } = useAuth(navigation);

    return { 
        header: () => (
            <Header 
                navigation={navigation} 
                title={`작업완료`}
                main={false}
                buttons={
                    <Fragment>
                        {auth.Update && auth.Action1 && <Form.ActionButton id="work-complete-form" navigation={navigation} type="success" action="approval" title="승인" />}
                    </Fragment>
                }
            /> 
        )
    } 
};

export default Screen;