import React, { Fragment, useState, useEffect, useLayoutEffect, useContext } from 'react';
import { ActivityIndicator, TextInput } from 'react-native';
import session from '~/Utils/session';
import fetchGet, { fetchPost, fetchPut, fetchDelete } from '~/Utils/fetch';
import { useToast, confirm } from '~/Components/UIControls/Message';
import Form from '~/Components/Form';
import Button from '~/Components/UIControls/Button';
import { useForm, Controller } from 'react-hook-form';
import BottomTabBarLayout from '~/Components/Layouts/BottomTabBarLayout';
import { UploadFileType } from '~/Components/UIControls/UploadFile';
import { usePopup } from '~/Components/UIControls/Popup';
import { useAuth } from '~/Components/Hooks';
import { Util } from '~/Utils/utils';
import { NavigationActions } from 'react-navigation';
import { InputFilters } from '~/Components/UIControls/Input';
import PopupSelect from '~/Components/UIControls/PopupSelect';
import PopupRentList from './PopupRentList';

const Screen = ({navigation}) => {
    const action = navigation.getParam('action', Form.CREATE);
    const [editable, setEditable] = useState(action == Form.CREATE ? true : false);
    const refreshList = navigation.getParam('refreshList', ()=>{});
    const siteId = navigation.getParam('siteId', '');
    const historyId = navigation.getParam('historyId', '');
    const { auth, userinfo, config } = useAuth(navigation);

    const [loading, setLoading] = useState(false);
    const [data, setData] = useState({
        ReturnCount: '0',
    });
    const { showMessage } = useToast();

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

    const onProcess = () => {
        console.log('onProcess');
        if (loading) {
            showMessage('저장중입니다. 잠시만기다려 주세요.');
            return;
        }

        confirm('저장', '정말 승인처리 하시겠습니까?', async () => {
            setLoading(true);
            try {
                const result = await fetchGet(
                    `/api/EquipmentHistory/ReturnApproval?siteId=${siteId}&id=${historyId}&userId=${userinfo.UserId}`
                    , {});
                showMessage('승인되었습니다.');
                refreshList();
                navigation.pop();
            } catch (error) {
                showMessage(error.message);
            }
            setLoading(false);
        });
    };

    useEffect(() => {
        if(!editable) {
            fetch(historyId);
        }
        navigation.setParams({
            onProcess: onProcess,
        });
    }, []);
    
    // search
    const fetch = async (equipmentHistoryId) => {
        setLoading(true);

        try {
            console.log('get - ', `api/app/EquipmentHistory/${siteId}/${equipmentHistoryId}`);
            let result = await fetchGet(`api/app/EquipmentHistory/${siteId}/${equipmentHistoryId}`);
            if(editable) {
                result.ReturnCount = '0';
                result.LossCount = '0';
                result.ReturnReason = '';
                result.CmFile = null;
            }

            setData(result);
            Form.setFormData(result);
            if (!result.IsReturnApproval) {
                navigation.setParams({notApproval:true});
            }

        } catch(error) {
            showMessage(error.message);
        }

        setLoading(false);
    }

    // delete
    const onDelete = async () => {
        if (loading) {
            showMessage('처리중입니다. 잠시만기다려 주세요.');
            return;
        }
        confirm('삭제', '삭제하시겠습니까?', async () => {
            setLoading(true);
            try {
                await fetchDelete(`api/EquipmentHistory/${siteId}/${historyId}`);

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

    return ( 
        <BottomTabBarLayout>
            <Form.Container onDelete={onDelete} loading={loading}>
                {editable && (
                    <Fragment>
                        <Form.Field>
                            <Form.Require><Form.Label>공기구</Form.Label></Form.Require>
                            <PopupSelect navigation={navigation} path={PopupRentList} editable={true}
                                onSelect={(item) => {
                                    fetch(item.EquipmentHistoryId);
                                }} />
                        </Form.Field>
                        <Form.Regist name="EquipmentHistoryId" rule={{required:'공기구를 선택하세요.'}} error={errors.EquipmentHistoryId} />
                        <Form.Regist name="EquipmentRentId" />
                    </Fragment>
                )}

                {config.UseEquipmentRent && (
                    <Fragment>
                        <Form.Field>
                            <Form.Require><Form.Label>대여명</Form.Label></Form.Require>
                            <Form.Input placeholder="대여명" value={Util.get(data, 'RentInfo.Title')} editable={false} />
                        </Form.Field>

                        <Form.Field>
                            <Form.Require><Form.Label>대여자</Form.Label></Form.Require>
                            <Form.Input placeholder="대여자" value={Util.get(data, 'RentInfo.RentUserName')} editable={false} />
                        </Form.Field>

                        <Form.Field>
                            <Form.Require><Form.Label>대여일</Form.Label></Form.Require>
                            <Form.Input placeholder="대여일" value={Util.getDateString(data, 'RentInfo.RentDate', '.')} editable={false} />
                        </Form.Field>

                        <Form.Field>
                            <Form.Require><Form.Label>반납예정일</Form.Label></Form.Require>
                            <Form.Input placeholder="반납예정일" value={Util.get(data, 'RentInfo.ReturnDueDate')} editable={false} />
                        </Form.Field>
                    </Fragment>
                )}

                <Form.Field>
                    <Form.Title><Form.Label>공기구명</Form.Label></Form.Title>
                    <Form.Input placeholder="공기구명" value={data.EquipmentName} editable={false} />
                </Form.Field>

                {editable ? (
                    <Fragment>
                        <Form.Field>
                            <Form.Title><Form.Label>{config.UseEquipmentRent ? '대여' : '재고'}수량</Form.Label></Form.Title>
                            <Form.Input placeholder={`${config.UseEquipmentRent ? '대여' : '재고'}수량`} value={data.CurrentRentCount} editable={false} />
                        </Form.Field>
                        <Form.Regist name="CurrentRentCount" />
                    </Fragment>
                ) : (
                    <Fragment>
                        <Form.Field>
                            <Form.Title><Form.Label>규격</Form.Label></Form.Title>
                            <Form.Input placeholder="규격" value={Util.get(data, 'EquipmentInfo.Standard')} editable={false} />
                        </Form.Field>
                        <Form.Field>
                            <Form.Title><Form.Label>상태</Form.Label></Form.Title>
                            <Form.Input placeholder="상태" value={Util.get(data, 'EquipmentStateType.Name')} editable={false} />
                        </Form.Field>
                    </Fragment>
                )}

                {config.UseEquipmentRent ? (
                    <Fragment>
                        <Form.Field>
                            <Form.Require><Form.Label>반납수량</Form.Label></Form.Require>
                            <Controller
                                name='ReturnCount'
                                control={control}
                                as={
                                    <Form.Input placeholder="반납수량" defaultValue={data.ReturnCount} editable={editable} 
                                        filter={(text) => {
                                            return InputFilters.numberRange(text, 0, data.CurrentRentCount);
                                        }}
                                        onChangeText={(text) => {
                                            setValue('ReturnCount', text);
                                        }}
                                    />
                                }
                            />
                        </Form.Field>
                        <Form.Regist name="ReturnCount" rule={{required:'반납수량을 입력하세요.'}} error={errors.ReturnCount} />
                    </Fragment>
                ) : (
                    <Fragment>
                        <Form.Regist name="ReturnCount" value={0} />
                    </Fragment>
                )}

                <Form.Field>
                    <Form.Require><Form.Label>손실수량</Form.Label></Form.Require>
                    <Controller
                        name='LossCount'
                        control={control}
                        as={
                            <Form.Input placeholder="손실수량" defaultValue={data.LossCount} editable={editable} 
                                filter={(text) => {
                                    return InputFilters.numberRange(text, 0, data.CurrentRentCount);
                                }}
                                onChangeText={(text) => {
                                    setValue('LossCount', text);
                                }}
                            />
                        }
                    />
                </Form.Field>
                <Form.Regist name="LossCount" rule={{required:'손실수량을 입력하세요.'}} error={errors.LossCount} />


                <Form.Field>
                    <Form.Require><Form.Label>{config.UseEquipmentRent ? '반납/손실' : '손실'}사유</Form.Label></Form.Require>
                    <Controller
                        name='ReturnReason'
                        control={control}
                        as={
                            <Form.Input placeholder={`${config.UseEquipmentRent ? '반납/손실' : '손실'}사유`} defaultValue={data.ReturnReason} editable={editable} 
                                onChangeText={(text) => {
                                    setValue('ReturnReason', text);
                                }}
                            />
                        }
                    />
                </Form.Field>
                <Form.Regist 
                    name="ReturnReason" 
                    rule={{required:`${config.UseEquipmentRent ? '반납/손실' : '손실'}수량을 입력하세요.`}} 
                    error={errors.ReturnReason} 
                />

                <Form.Field>
                    <Form.TitleTop><Form.Label>첨부파일</Form.Label></Form.TitleTop>
                    <Form.UploadFile 
                        type={UploadFileType.Image} 
                        editable={editable} 
                        defaultFile={data.CmFile} 
                        onUpload={(isUpload, result) => {
                            Form.uploadFile('CmFile', isUpload, result);
                        }} onDelete={() => {
                            Form.deleteFile('CmFile');
                        }}
                    />
                </Form.Field>
                <Form.RegistFile editable={editable} name="CmFile" value={Util.get(data, "CmFile")} />

                {data.IsReturnApproval && (
                    <>
                        <Form.Field>
                            <Form.Title><Form.Label>승인자</Form.Label></Form.Title>
                            <Form.Input placeholder="승인자" value={data.ReturnApprovalUser} editable={false} />
                        </Form.Field>
                        <Form.Field>
                            <Form.Title><Form.Label>승인일자</Form.Label></Form.Title>
                            <Form.Input placeholder="승인일자" value={data.ReturnApprovalDate} editable={false} />
                        </Form.Field>
                    </>
                )}

                <Form.Field style={{ height:30 }}>
                </Form.Field>

            </Form.Container>
        </BottomTabBarLayout>
    );
};

Screen.navigationOptions = ({navigation}) => { 
    const action = navigation.getParam('action', Form.CREATE);
    const editable = action == Form.CREATE ? true : false;
    const { auth } = useAuth(navigation);
    const handler = navigation.getParam('onProcess');
    const notApproval = navigation.getParam('deleteView', false);

    return { 
        header: () => (
            <Header 
                navigation={navigation} 
                title={`공기구손실`}
                main={false}
                buttons={
                    <Fragment>
                    {auth.Delete && notApproval && (
                        <Fragment>
                            <Form.DeleteButton />
                        </Fragment>
                    )}
                    {auth.Action1 && notApproval && (
                        <Form.PrimaryButton onPress={handler}>
                            승인
                        </Form.PrimaryButton>
                    )}
                    </Fragment>
                }
            /> 
        )
    } 
};

export default Screen;