import React, { Fragment, useState, useEffect, useLayoutEffect, useContext } from 'react';
import { ActivityIndicator, Text } from 'react-native';
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 Button from '~/Components/UIControls/Button';
import { useForm } 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';

const titleWidth = 100;

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

    const [loading, setLoading] = useState(false);
    const [data, setData] = useState({ IsUse: true });
    const { showMessage } = useToast();

    // 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/Partner/Get?siteId=${siteId}&partnerId=${partnerId}`);
                const result = await fetchGet(`api/app/Partner/Get?siteId=${siteId}&partnerId=${partnerId}`);
                setData(result);
                Form.setFormData(result);
            } catch(error) {
                showMessage(error.message);
            }
        } else {
            const initialData = {IsUse:true};
            setData(initialData);
            Form.setFormData(initialData);
        }

        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,
                PartnerId: partnerId,
            };
            console.log('submit data', submit);

            try {
                const result = await fetchPost('api/app/Partner/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/Partner/${siteId}/${partnerId}`);

                showMessage('삭제되었습니다.');
                refreshList();
                navigation.pop();
            } catch(error) {
                showMessage(error.message);
            }
            setLoading(false);
        });
    }
    console.log('UseServicePartner : ' +config.UseServicePartner);
    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.RegistrationNo} 
                                onChangeText={text => setValue('RegistrationNo', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="RegistrationNo" rule={{required:'사업자번호를 입력하세요.'}} error={errors.RegistrationNo} />

                <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.Require style={{width:titleWidth}}><Form.Label>회사대표</Form.Label></Form.Require>
                    <Form.Input placeholder="회사대표" defaultValue={data.RepresentativeName} 
                                onChangeText={text => setValue('RepresentativeName', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="RepresentativeName" rule={{required:'대표자명을 입력하세요.'}} error={errors.RepresentativeName} />
                
                <Form.Field>
                    <Form.Require style={{width:titleWidth}}><Form.Label>대표번호</Form.Label></Form.Require>
                    <Form.Input placeholder="대표번호" defaultValue={data.PhoneNo} 
                                onChangeText={text => setValue('PhoneNo', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="PhoneNo" rule={{required:'대표번호를 입력하세요.'}} error={errors.PhoneNo} />

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

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

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

                <Form.Field>
                    <Form.Require style={{width:titleWidth}}><Form.Label>업무분야</Form.Label></Form.Require>
                    <Form.EntitySelect entity="CmBusinessField" defaultLabel="업무분야" useCheck={true}
                                selectedValue={data.BusinessFieldId} selectedText={data.BusinessFieldName} editable={editable} auth={auth}
                                onChange={(item) => { 
                                    setValue('BusinessFieldId', item.value, true);
                                }}  />
                </Form.Field>
                <Form.Regist editable={editable} name="BusinessFieldId" rule={{required:'업무분야를 선택 하세요.'}} />

                <Form.Field>
                    <Form.Require style={{width:titleWidth}}><Form.Label>업체유형</Form.Label></Form.Require>
                    <Form.EntitySelect entity="CmPartnerType" defaultLabel="업체유형" where={config.UseServicePartner ? `Name != '용역업체'` :`1 = 1` } 
                        selectedValue={data.PartnerTypeId} selectedText={data.PartnerTypeName} useCheck={true} editable={editable}
                        onChange={(item) => {     
                            console.log(item.value);                        
                            setValue('PartnerTypeId', item.value, true) }}  />
                </Form.Field>
                <Form.Regist editable={editable} name="PartnerTypeId" rule={{required:'업체유형을 선택 하세요.'}} error={errors.PartnerTypeId} />
                
                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>우편번호</Form.Label></Form.Title>
                    <Form.Input placeholder="우편번호" defaultValue={data.AddressZip1}  maxLangth={3}
                                onChangeText={text => setValue('AddressZip1', text, true)} 
                                editable={editable} returnKeyType="next" keyboardType="number-pad" /><Text> - </Text> 
                    <Form.Regist editable={editable} name="AddressZip1" />
                    <Form.Input placeholder="우편번호" defaultValue={data.AddressZip2} maxLangth={3}
                                onChangeText={text => setValue('AddressZip2', text, true)} 
                                editable={editable} returnKeyType="next" keyboardType="number-pad" />
                    <Form.Regist editable={editable} name="AddressZip2" />
                </Form.Field>

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>회사주소1</Form.Label></Form.Title>
                    <Form.Input placeholder="회사주소1" defaultValue={data.Address1} 
                                onChangeText={text => setValue('Address1', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="Address1" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>회사주소2</Form.Label></Form.Title>
                    <Form.Input placeholder="회사주소2" defaultValue={data.Adderss2} 
                                onChangeText={text => setValue('Adderss2', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="Adderss2" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>홈페이지</Form.Label></Form.Title>
                    <Form.Input placeholder="홈페이지" defaultValue={data.HomepageUri} 
                                onChangeText={text => setValue('HomepageUri', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="HomepageUri" />
                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>비고</Form.Label></Form.Title>
                    <Form.Input placeholder="비고" defaultValue={data.Note} 
                                onChangeText={text => setValue('Note', text, true)} 
                                editable={editable} returnKeyType="next" />
                </Form.Field>
                <Form.Regist editable={editable} name="Note" />
                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>사용여부</Form.Label></Form.Title>
                    <Form.Switch initialValue={data.IsUse} onValueChange={(newValue) => { setValue('IsUse', newValue) }} editable={editable} />
                </Form.Field>
                <Form.Regist editable={editable} name="IsUse" />

                <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;