import React, { Fragment, useState, useEffect, useLayoutEffect, useContext } from 'react';
import session from '~/Utils/session';
import fetchGet, { fetchPost, fetchDelete } from '~/Utils/fetch';
import { useToast, confirm } from '~/Components/UIControls/Message';
import Form from '~/Components/Form';
import { useForm } from 'react-hook-form';
import BottomTabBarLayout from '~/Components/Layouts/BottomTabBarLayout';
import { usePopup } from '~/Components/UIControls/Popup';
import { useAuth } from '~/Components/Hooks';
import { InputFilters } from '~/Components/UIControls/Input';
import { UploadFileType } from '~/Components/UIControls/UploadFile';

const Screen = ({navigation}) => {
    const action = navigation.getParam('action', Form.VIEW);
    const editable = navigation.getParam('editable', action == Form.VIEW ? false : true);
    const setEditable = (value) => { navigation.setParams({editable: value}) };
    const refreshList = navigation.getParam('refreshList', ()=>{});
    const siteId = navigation.getParam('siteId', '');
    const contractId = navigation.getParam('contractId', '');
    const { auth } = useAuth(navigation);
    const { showMessage } = useToast();

    const [loading, setLoading] = useState(false);
    const [data, setData] = useState({});
    const [partnerTypeId , setPartnerTypeId] = useState('');
    // mount
    useEffect(() => {
        fetch();
    }, [editable]);

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

    // popup
    const { openPopup } = usePopup();

    // react hook form initialize
    const { register, setValue, handleSubmit, errors, getValues } = useForm();
    useLayoutEffect(() => {
        Form.setUseFormFunctions(register, setValue);
    }, [register]);
    
    // search
    const fetch = async () => {
        setLoading(true);
        await session.load();

        if(action != Form.CREATE) {
            try {
                console.log('get - ', `api/app/ContractManagement/Get?siteId=${siteId}&contractId=${contractId}`);
                const result = await fetchGet(`api/app/ContractManagement/Get?siteId=${siteId}&contractId=${contractId}`);
                setData(result);
                Form.setFormData(result);
            } catch(error) {
                showMessage(error.message);
            }
        }

        setLoading(false);
    }

    // edit
    const onEdit = async () => {
        await fetch();
        setEditable(true);
    }

    // cancel edit
    const onCancelEdit = async () => {
        await fetch();
        setEditable(false);
    }

    // save
    const onSave = async form => {
        if(loading) {
            showMessage('저장중입니다. 잠시만기다려 주세요.');
            return;
        }
        confirm('저장', '저장하시겠습니까?', async () => {
            setLoading(true);
            const submit = {...form,
                SiteId: siteId,
                ContractId: contractId,
            };
            console.log('submit data', submit);

            try {
                const result = await fetchPost('api/app/ContractManagement/Save', submit);

                showMessage('저장되었습니다.');
                refreshList();
                if(action == Form.CREATE) {
                    navigation.pop();
                } else {
                    setEditable(false);
                }
            } catch(error) {
                showMessage(error.message);
            }
            setLoading(false);
        });
    }

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

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

    const titleWidth = 110;
    
    return ( 
        <BottomTabBarLayout>
            <Form.Container onSave={handleSubmit(onSave)} onDelete={onDelete} onEdit={onEdit} onCancelEdit={onCancelEdit} loading={loading}>
                <Form.Field>
                    <Form.Require style={{width:titleWidth}}><Form.Label >계약명</Form.Label></Form.Require>
                    <Form.Input placeholder="계약명" defaultValue={data.Name} 
                                onChangeText={text => setValue('Name', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="Name" rule={{required:'계약명을 입력하세요.'}} error={errors.Name} />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>계약날짜</Form.Label></Form.Title>
                    <Form.DatePicker date={data.ContractDate} onChange={(newDate) => setValue('ContractDate', newDate, true)} editable={editable} />
                </Form.Field>
                <Form.Regist editable={editable} name="ContractDate" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>시작일</Form.Label></Form.Title>
                    <Form.DatePicker date={data.StartDate} onChange={(newDate) => setValue('StartDate', newDate, true)} editable={editable} />
                </Form.Field>
                <Form.Regist editable={editable} name="StartDate" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>종료일</Form.Label></Form.Title>
                    <Form.DatePicker date={data.EndDate} onChange={(newDate) => setValue('EndDate', newDate, true)} editable={editable} />
                </Form.Field>
                <Form.Regist editable={editable} name="EndDate" />

                <Form.Field>
                    <Form.Require style={{width:titleWidth}}><Form.Label>업체유형</Form.Label></Form.Require>
                    <Form.EntitySelect entity="CmPartnerType" defaultLabel="업체유형"
                        selectedValue={data.PartnerTypeId} selectedText={data.PartnerTypeName} editable={editable} useCheck={true}
                        onChange={(item) => {                             
                            setValue('PartnerTypeId', item.value, true);
                            setPartnerTypeId(item.value) }}  />
                </Form.Field>
                <Form.Regist editable={editable} name='PartnerTypeId' rule={{required:'업체유형을 선택하세요.'}} error={errors.PartnerTypeId} />

                <Form.Field>
                    <Form.Require style={{width:titleWidth}}><Form.Label>업체명</Form.Label></Form.Require>
                    <Form.EntitySelect entity="CmPartner" defaultLabel="업체명" siteId={session.getSiteId()} 
                        where={partnerTypeId != '' ? `PartnerTypeId=${partnerTypeId}`:``}
                        selectedValue={data.PartnerId} selectedText={data.PartnerName} editable={editable} useCheck={true}
                        onChange={(item) => {                             
                            setValue('PartnerId', item.value, true) }}  />
                </Form.Field>
                <Form.Regist editable={editable} name='PartnerId' rule={{required:'업체를 선택하세요.'}} error={errors.PartnerId} />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>담당자</Form.Label></Form.Title>
                    <Form.Input placeholder="담당자" defaultValue={data.OwnerShipName} 
                                onChangeText={text => setValue('OwnerShipName', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="OwnerShipName"/>

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>담당자연락처</Form.Label></Form.Title>
                    <Form.Input placeholder="담당자연락처" defaultValue={data.OwnerShipPhoneNo} 
                                onChangeText={text => setValue('OwnerShipPhoneNo', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="OwnerShipPhoneNo" />

                <Form.Field>
                    <Form.Require style={{width:titleWidth}}><Form.Label>지급유형</Form.Label></Form.Require>
                    <Form.EntitySelect entity="FmsPaymentType" defaultLabel="지급유형"
                        selectedValue={data.PaymentTypeId} selectedText={data.PaymentTypeName} editable={editable} useCheck={true}
                        onChange={(item) => {
                            setValue('PaymentTypeId', item.value, true);
                        }}  />
                </Form.Field>
                <Form.Regist editable={editable} name='PaymentTypeId' rule={{ required:'지급유형을 선택하세요.' }} error={errors.PaymentTypeId}/>

                <Form.Field>
                    <Form.Require style={{width:titleWidth}}><Form.Label>계약구분</Form.Label></Form.Require>
                    <Form.EntitySelect entity="FmsContractType" defaultLabel="계약구분" 
                        selectedValue={data.ContractTypeId} selectedText={data.ContractTypeName} editable={editable} useCheck={true}
                        onChange={(item) => {
                            setValue('ContractTypeId', item.value, true);
                        }}  />
                </Form.Field>
                <Form.Regist editable={editable} name='ContractTypeId' rule={{ required:'계약구분을 선택하세요.' }} error={errors.ContractTypeId}/>

                <Form.Field>
                    <Form.Require style={{width:titleWidth}}><Form.Label>계약방법</Form.Label></Form.Require>
                    <Form.EntitySelect entity="FmsContractMethod" defaultLabel="계약방법"
                        selectedValue={data.ContractMethodId} selectedText={data.ContractMethodName} editable={editable} useCheck={true}
                        onChange={(item) => {
                            setValue('ContractMethodId', item.value, true);
                        }}  />
                </Form.Field>
                <Form.Regist editable={editable} name='ContractMethodId' rule={{ required:'계약방법을 선택하세요.' }} error={errors.ContractMethodId} />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>계약금액</Form.Label></Form.Title>
                    <Form.Input placeholder="계약금액" defaultValue={data.ContractAmountText} 
                                onChangeText={text => setValue('ContractAmountText', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="ContractAmountText" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>계약이행보증률</Form.Label></Form.Title>
                    <Form.Input placeholder="계약이행보증률" defaultValue={data.ContractExeGuaranteeRate} 
                                filter={text => {
                                    return InputFilters.decimal(text);
                                }}
                                onChangeText={text => setValue('ContractExeGuaranteeRate', text, true)} 
                                editable={editable} returnKeyType="next" keyboardType="decimal-pad" />
                </Form.Field>
                <Form.Regist editable={editable} name="ContractExeGuaranteeRate" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>하자보증률</Form.Label></Form.Title>
                    <Form.Input placeholder="하자보증률" defaultValue={data.DefectGuaranteeRate} 
                                filter={text => {
                                    return InputFilters.decimal(text);
                                }}
                                onChangeText={text => setValue('DefectGuaranteeRate', text, true)} 
                                editable={editable} returnKeyType="next" keyboardType="decimal-pad" />
                </Form.Field>
                <Form.Regist editable={editable} name="DefectGuaranteeRate" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>하자보증기간</Form.Label></Form.Title>
                    <Form.Input placeholder="하자보증기간" defaultValue={data.DefectGuaranteePeriodText} 
                                onChangeText={text => setValue('DefectGuaranteePeriodText', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="DefectGuaranteePeriodText" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>비고</Form.Label></Form.Title>
                    <Form.Input placeholder="비고" defaultValue={data.Comment} 
                                onChangeText={text => setValue('Comment', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="Comment" />

                <Form.Field>
                    <Form.TitleTop style={{width:titleWidth}}><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={data.CmFile} />

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

            </Form.Container>
            {loading && <Form.Loading />}
        </BottomTabBarLayout>
    );
};

Screen.navigationOptions = ({navigation}) => { 
    const action = navigation.getParam('action', Form.VIEW);    // create, edit, view
    const editable = navigation.getParam('editable', action == Form.VIEW ? false : true);
    const { auth } = useAuth(navigation);
    return { 
        header: () => (
            <Header 
                navigation={navigation} 
                title={`계약관리`}
                main={false}
                buttons={
                    <Fragment>
                    {!editable && (
                        <Fragment>
                            {auth.Update && <Form.EditButton navigation={navigation} type="primary" />}
                            {auth.Delete && <Form.DeleteButton />}
                        </Fragment>
                    )}
                    {editable && (
                        <Fragment>
                            {auth.Update && <Form.SaveButton type="primary" />}
                            {action != Form.CREATE && <Form.CancelEditButton navigation={navigation} />}
                        </Fragment>
                    )}
                    </Fragment>
                }
            /> 
        )
    } 
};

export default Screen;