import React, { Fragment, useState, useEffect, useLayoutEffect, useContext } from 'react';
import Styled from 'styled-components/native';
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 { useAuth } from '~/Components/Hooks';
import Accidents from '../Common/Accidents';
import Complaints from '../Common/Complaints';
import { View, Text } from 'react-native';
import { UploadFileType } from '~/Components/UIControls/UploadFile';
import IconButton from '~/Components/UIControls/IconButton';
import { CreateButton } from '~/Components/Listing/Search';
import Theme from '~/Themes';
import { isTrue } from '~/Components/UIControls/Common';

const titleWidth = 100;

const Human = Styled.View`
    flex-direction: row;
    justify-content: center;
    align-items: center;
    height: 32px;
    border: 0px;
    margin-right:3px;
    margin-top:1px;
    margin-bottom:1px;
    padding-left:8px;
    padding-right:8px;
    background-color: #0b83e6;
    border-radius:5px;
    overflow:hidden;
`;
const HumanName = Styled.Text`
    font-size: 16;
    font-family: ${Theme.Fonts.Regular};
    include-font-padding: false;
    line-height: 24;
    letter-spacing: -1.6;
    color: white;
`;
const HumanRemove = ({ onPress = () => {} }) => {
    return (
        <IconButton iconFamily="AntDesign" iconName="minuscircle" color="white" size={20} onPress={onPress} style={{ marginLeft: 10 }} />
    );
};

const HumanManager = ({ editable, initialHumans, setValue, humansDataPath }) => {
    const [humans, setHumans] = useState(Array.isArray(initialHumans) ? initialHumans : []);

    const { prompt } = usePrompt();

    useEffect(() => {
        if (Array.isArray(initialHumans)) {
            setValue(humansDataPath, initialHumans.join(','));
            setHumans([...initialHumans]);
        } else {
            setValue(humansDataPath, '');
            setHumans([]);
        }
    }, [editable]);

    const addHuman = () => {
        prompt({
            title: '인원명',
            message: '추가할 인원의 이름을 입력하세요.',
            defaultValue: '',
            confirm: (text) => {
                let newHumans = [...humans];
                newHumans.push(text);
                setValue(humansDataPath, newHumans.join(','), true);
                setHumans(newHumans);
            },
        });
    };

    const removeHuman = (index) => {
        let newHumans = [];
        for (let i = 0; i < humans.length; i++) {
            if (index == i) continue;
            newHumans.push(humans[i]);
        }
        setValue(humansDataPath, newHumans.join(','), true);
        setHumans(newHumans);
    };

    return (
        <Fragment>
            <Form.FieldSet
                style={{
                    flexDirection: 'row',
                    flexWrap: 'wrap',
                    alignItems: 'flex-start',
                    borderWidth: 1,
                    borderColor: Theme.COLORS.EDITABLE_BORDER,
                    borderRadius: 4,
                }}
            >
                {humans && Array.isArray(humans) && humans.length > 0 ? (
                    humans.map((name, index) => {
                        return (
                            <Fragment key={`human-${index}`}>
                                <Human style={!isTrue(editable) && { backgroundColor: '#9aa3ac' }}>
                                    <HumanName>{name}</HumanName>
                                    {isTrue(editable) && (
                                        <HumanRemove
                                            onPress={() => {
                                                removeHuman(index);
                                            }}
                                        />
                                    )}
                                </Human>
                            </Fragment>
                        );
                    })
                ) : (
                    <View style={{ flex: 1, height: 35, justifyContent: 'center', alignItems: 'flex-start' }}>
                        <Form.Label
                            style={{
                                fontFamily: Theme.Fonts.Regular,
                                color: Theme.COLORS.EDITABLE_BORDER,
                                letterSpacing: -1.6,
                                fontSize: 16,
                                lineHeight: 30,
                            }}
                        >
                            작업자를 추가해 주세요.
                        </Form.Label>
                    </View>
                )}
                <CreateButton
                    onPress={() => {
                        addHuman();
                    }}
                    style={{
                        right: 3,
                        top: 3,
                        bottom: 'auto',
                        width: 38,
                        height: 38,
                    }}
                />
            </Form.FieldSet>
            <Form.Regist name={humansDataPath} />
        </Fragment>
    );
};

const PromptContentComplete = ({
    nextWork = false,
    title = '',
    message = '',
    form = {},
    siteId = 0,
    workRequestId = 0,
    userId = '',
    defaultValue = {},
    initialDate = new Date(),
    minimumDate = new Date(),
    navigation = null,
    setLoading = () => {},
    refreshList = () => {},
    setPromptParams = () => {},
}) => {
    const { register, setValue, handleSubmit, errors, getValues, control } = useForm();
    useLayoutEffect(() => {}, [register]);

    const confirmProcess = async (confirmForm) => {
        console.log('confirmForm - ', confirmForm);
        const submit = {
            FmsWorkRequest: {
                WorkUsers: Util.get(confirmForm, 'FmsWorkRequest.WorkUsers'),
                WorkPartnerId: Util.get(confirmForm, 'FmsWorkRequest.WorkPartnerId'),
            },
            SiteId: siteId,
            WorkRequestId: workRequestId,
            StartDate: confirmForm.StartDate,
            EndDate: confirmForm.EndDate,
        };
        console.log('submit - ', submit);

        confirm('승인요청', '승인요청처리 하시겠습니까?', async () => {
            setLoading(true);

            try {
                const result = await fetchPost(`api/app/WorkResult/Complete`, submit);
                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>

                    <Controller
                        name="FmsWorkRequest.WorkUsers"
                        defaultValue=""
                        control={control} /* rules={{required:'작업자를 추가하세요.'}} */
                        as={
                            <HumanManager
                                editable={true}
                                initialHumans={[]}
                                setValue={setValue}
                                humansDataPath="FmsWorkRequest.WorkUsers"
                            />
                        }
                    />
                    <Form.Error message={Util.get(errors, 'FmsWorkRequest.WorkUsers')} />

                    <Form.Field>
                        <Controller
                            name="FmsWorkRequest.WorkPartnerId"
                            defaultValue={defaultValue.workPartnerId}
                            control={control}
                            as={
                                <Form.PopupSelect
                                    path="/Popup/Partner/Index"
                                    popupProps={{ navigation, siteId }}
                                    emptyLabel="업체"
                                    editable={true}
                                    defaultLabel={defaultValue.workPartnerName}
                                    onSelect={(result) => {
                                        setValue('FmsWorkRequest.WorkPartnerId', result.PartnerId, true);
                                    }}
                                />
                            }
                        />
                    </Form.Field>
                    <Form.Error message={Util.get(errors, 'FmsWorkRequest.WorkPartnerId')} />

                    <Form.Field>
                        <Controller
                            name="StartDate"
                            defaultValue={defaultValue.workStartDateTime}
                            control={control} /* rules={{required:'작업시작일시를 선택하세요.'}} */
                            as={
                                <Form.DatePicker
                                    placeholder="작업시작일시"
                                    mode="datetime"
                                    date={defaultValue.workStartDateTime}
                                    editable={true}
                                    onChange={(newDate) => setValue('StartDate', newDate, true)}
                                />
                            }
                        />
                    </Form.Field>
                    <Form.Error message={Util.get(errors, 'StartDate')} />

                    <Form.Field>
                        <Controller
                            name="EndDate"
                            defaultValue={defaultValue.workEndDateTime}
                            control={control} /* rules={{required:'작업종료일시를 선택하세요.'}} */
                            as={
                                <Form.DatePicker
                                    placeholder="작업종료일시"
                                    mode="datetime"
                                    date={defaultValue.workEndDateTime}
                                    editable={true}
                                    onChange={(newDate) => setValue('EndDate', newDate, true)}
                                />
                            }
                        />
                    </Form.Field>
                    <Form.Error message={Util.get(errors, 'EndDate')} />

                    <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>
        </>
    );
};

// 작업진행 관리 (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 hasCheckItem = navigation.getParam('hasCheckItem', true);
    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 [complaints, setComplaints] = useState([]);
    const { openPopup } = usePopup();
    const { prompt } = usePrompt();
    const { showMessage } = useToast();

    const [promptParams, setPromptParams] = useState({
        show: false,
        nextWork: false,
        title: '',
        message: '',
        form: {},
        siteId: 0,
        workRequestId: 0,
        userId: '',
        defaultValue: {},
        initialDate: new Date(),
        minimumDate: new Date(),
    });

    // 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);
                setComplaints(result.FmsWorkRequestToComplaint);
                console.log(complaints);
                navigation.setParams({
                    workProgressId: result.WorkProgressId,
                    hasCheckItem: result.HasCheckItem,
                });
            } 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();
        } else if (action == 'edit-work-request') {
            showEditWorkRequest();
        } else if (action == 'complete') {
            complete();
        } else if (action == 'hold') {
            hold();
        }
    };

    // 작업 진행
    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 complete = async () => {
        if (loading) {
            showMessage('처리중입니다. 잠시만기다려주세요.');
            return;
        }

        setPromptParams({
            show: true,
            nextWork: false,
            title: '추가정보 입력',
            message: '작업 추가정보를 입력하세요.',
            siteId: siteId,
            workRequestId: workRequestId,
            userId: userinfo.UserId,
            defaultValue: {
                workUsers: '',
                workPartnerId: data.WorkPartnerId,
                workPartnerName: data.WorkPartnerName,
                workStartDateTime: data.StartDate,
                workEndDateTime: data.EndDate,
            },
            initialDate: null,
            minimumDate: null,
        });
    };

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

        confirm('보류', '보류처리 하시겠습니까?', async () => {
            setLoading(true);

            try {
                const result = await fetchPost(`api/app/WorkResult/Hold`, {
                    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;
        }

        prompt({
            title: '반려사유입력',
            message: '반려사유를 입력하세요.',
            confirm: (text, event) => {
                event.autoClose = false;
                rejectProcess(text, false, null, event);
            },
        });
    };

    // 반려 처리(스케쥴사용시)
    const rejectWorkSchedule = 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: PromptContentReject,
                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 showEditWorkRequest = () => {
        navigation.navigate('EditWorkRequest', {
            refreshList: refresh,
            action: Form.EDIT,
            siteId: userinfo.SiteId,
            workRequestId: data.WorkRequestId,
            workTypeId: data.WorkTypeId,
            auth: auth,
            userinfo: userinfo,
        });
    };

    const updateAccidents = async (list) => {
        setLoading(true);
        try {
            const result = await fetchPost(`api/app/WorkRequest/SaveAccidents`, {
                SiteId: siteId,
                WorkRequestId: workRequestId,
                FmsWorkRequestToAccident: list,
            });
            setAccidents(list);
            refreshList();
        } catch (error) {
            showMessage(error.message);
        }
        setLoading(false);
    };

    const updateComplaints = async (list) => {
        setLoading(true);
        try {
            const result = await fetchPost(`api/app/WorkRequest/SaveComplaints`, {
                SiteId: siteId,
                WorkRequestId: workRequestId,
                FmsWorkRequestToComplaint: list,
            });
            setComplaints(list);
            refreshList();
        } catch (error) {
            showMessage(error.message);
        }
        setLoading(false);
    };

    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="작업이력"
                                />
                                {Util.get(data, 'WorkDetailType.Code') == 'ACCIDENT' && (
                                    <TabTitle
                                        onPress={() => {
                                            navigation.setParams({ tab: 'accidents' });
                                        }}
                                        active={tab == 'accidents' ? true : false}
                                        title="사고목록"
                                    />
                                )}
                                {Util.get(data, 'WorkDetailType.Code') == 'COMPLAINT' && (
                                    <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="work-process-form" onAction={onAction}>
                                    <Form.Field>
                                        <Form.Title style={{ width: titleWidth }}>
                                            <Form.Label>지시제목</Form.Label>
                                        </Form.Title>
                                        <Form.Input defaultValue={Util.get(data, 'Title')} editable={false} />
                                    </Form.Field>

                                    <Form.Field>
                                        <Form.Title style={{ width: titleWidth }}>
                                            <Form.Label>작업상태</Form.Label>
                                        </Form.Title>
                                        <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>
                                        <Form.Input defaultValue={Util.getDateString(data, "WorkDueDate")} editable={false} />
                                    </Form.Field>

                                    <Form.Field>
                                        <Form.Title style={{width:titleWidth}}><Form.Label>종료예정일</Form.Label></Form.Title>
                                        <Form.DatePicker date={data.WorkEndDate} editable={false} />
                                    </Form.Field>
                                    */}

                                    <Form.Field>
                                        <Form.Title style={{ width: titleWidth }}>
                                            <Form.Label>작업시작일</Form.Label>
                                        </Form.Title>
                                        <Form.Input defaultValue={Util.getDateString(data, 'StartDate')} editable={false} />
                                    </Form.Field>

                                    <Form.Field>
                                        <Form.Title style={{ width: titleWidth }}>
                                            <Form.Label>작업종료일</Form.Label>
                                        </Form.Title>
                                        <Form.Input defaultValue={Util.getDateString(data, 'EndDate')} editable={false} />
                                    </Form.Field>

                                    <Form.Field>
                                        <Form.Title style={{ width: titleWidth }}>
                                            <Form.Label>작업자</Form.Label>
                                        </Form.Title>
                                        <Form.Input defaultValue={Util.get(data, 'WorkerUser.Name')} editable={false} />
                                    </Form.Field>

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

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

                                    <Form.Field>
                                        <Form.TitleTop style={{ width: titleWidth }}>
                                            <Form.Label>첨부파일</Form.Label>
                                        </Form.TitleTop>
                                        <Form.UploadFile type={UploadFileType.Image} editable={false} defaultFile={data.CmFile} />
                                    </Form.Field>

                                    <Form.Field>
                                        <Form.TitleTop style={{ width: titleWidth }}>
                                            <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>
                            <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>
                            {Util.get(data, 'WorkDetailType.Code') == 'ACCIDENT' && (
                                <TabItem active={tab == 'accidents' ? true : false}>
                                    <Accidents
                                        navigation={navigation}
                                        keys={{ SiteId: siteId, WorkRequestId: workRequestId }}
                                        accidents={accidents}
                                        setAccidents={updateAccidents}
                                        editable={true}
                                    />
                                </TabItem>
                            )}
                            {Util.get(data, 'WorkDetailType.Code') == 'COMPLAINT' && (
                                <TabItem active={tab == 'complaints' ? true : false}>
                                    <Complaints
                                        navigation={navigation}
                                        keys={{ SiteId: siteId, WorkRequestId: workRequestId }}
                                        complaints={complaints}
                                        setComplaints={updateComplaints}
                                        editable={true}
                                    />
                                </TabItem>
                            )}
                            <TabItem active={tab == 'material' ? true : false} alwaysReload={true}>
                                <Materials siteId={siteId} workRequestId={workRequestId} />
                            </TabItem>
                        </TabContent>
                    </Tab>
                    {loading && <Form.Loading />}
                </Fragment>
            </BottomTabBarLayout>
            {promptParams.show && (
                <PromptContentComplete
                    navigation={navigation}
                    setLoading={setLoading}
                    refreshList={refreshList}
                    setPromptParams={setPromptParams}
                    {...promptParams}
                />
            )}
        </>
    );
};

const PromptContentReject = ({ 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 hasCheckItem = navigation.getParam('hasCheckItem', true);
    const { auth } = useAuth(navigation);

    console.log('workTypeId:', workTypeId);
    console.log('hasCheckItem : ', hasCheckItem);

    return {
        header: () => (
            <Header
                navigation={navigation}
                title={`작업진행`}
                main={false}
                buttons={
                    auth.Update && (
                        <Fragment>
                            {workProgressId == 7 /* 보류 */ ? (
                                <Form.ActionButton
                                    id="work-process-form"
                                    navigation={navigation}
                                    buttonStyle={{ width: 65 }}
                                    type="success"
                                    action="continue"
                                    title="작업진행"
                                />
                            ) : (
                                <Fragment>
                                    {!hasCheckItem ? (
                                        <Form.ActionButton
                                            id="work-process-form"
                                            navigation={navigation}
                                            buttonStyle={{ width: 65 }}
                                            type="success"
                                            action="edit-work-request"
                                            title="수정"
                                        />
                                    ) : (
                                        <Fragment />
                                    )}
                                    {/*<Form.ActionButton id="work-process-form" navigation={navigation} buttonStyle={{width:45}} type="primary" action="hold" title="보류" />*/}
                                    <Form.ActionButton
                                        id="work-process-form"
                                        navigation={navigation}
                                        buttonStyle={{ width: 65 }}
                                        type="primary"
                                        action="complete"
                                        title="승인요청"
                                    />
                                    {auth.Action1 ? (
                                        <Form.ActionButton
                                            id="work-process-form"
                                            navigation={navigation}
                                            buttonStyle={{ width: 45 }}
                                            type="error"
                                            action="reject"
                                            title="반려"
                                        />
                                    ) : (
                                        <Fragment />
                                    )}
                                </Fragment>
                            )}
                        </Fragment>
                    )
                }
            />
        ),
    };
};

export default Screen;
