import React, { Fragment, useState, useEffect, useLayoutEffect, useContext } from 'react';
import { ActivityIndicator } 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 } 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';

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

    const [loading, setLoading] = useState(false);
    const [data, setData] = useState({});
    const { showMessage } = useToast();
    const [businessFieldId, setBusinessFieldId] = useState(0);

    // mount
    useEffect(() => {
        fetch(false);
    }, []);

    // change editable
    useEffect(() => {
    }, [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 (editable=false) => {
        setLoading(true);
        await session.load();

        if(action != Form.CREATE) {
            try {
                console.log('get - ', `api/app/Equipment/${siteId}/${equipmentId}/${historyId}`);
                const result = await fetchGet(`api/app/Equipment/${siteId}/${equipmentId}/${historyId}`);
                setData(result);
                setBusinessFieldId(result.BusinessFieldId);
                Form.setFormData(result);
                setEditable(editable);
            } catch(error) {
                showMessage(error.message);
            }
        }

        setLoading(false);
    }

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

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

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

            try {
                if(action == Form.CREATE) {
                    const result = await fetchPut('api/app/Equipment', submit);
                    showMessage('등록되었습니다.');
                } else {
                    const result = await fetchPost(`api/app/Equipment/${siteId}/${equipmentId}`, submit);
                    showMessage('저장되었습니다.');
                }
                refreshList();
                if(action == Form.CREATE) {
                    navigation.pop();
                } else {
                    fetch(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/Equipment/${siteId}/${equipmentId}`);

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

    return ( 
        <BottomTabBarLayout>
            <Form.Container onSave={handleSubmit(onSave)} onDelete={onDelete} onEdit={onEdit} onCancelEdit={onCancelEdit} loading={loading}>
                {action == Form.CREATE && (
                    <Form.Field>
                        <Form.Require style={{width:titleWidth}}><Form.Label>추가입고</Form.Label></Form.Require>
                        <Form.Switch editable={true} initialValue={false} onChange={() => {
                            navigation.replace('FormAddStock', {
                                auth: auth,
                                userinfo: userinfo,
                                config: config,
                                refreshList: refreshList,
                                action: Form.CREATE, 
                                siteId: session.getSiteId(), 
                            });
                        }} />
                    </Form.Field>
                )}

                <Form.Field>
                    <Form.TitleTop style={{width:titleWidth}}><Form.Label>이미지</Form.Label></Form.TitleTop>
                    <Form.UploadFile type={UploadFileType.Image} editable={editable} defaultFile={data.ImageFile}
                    onUpload={(isUpload, result) => {
                        Form.uploadFile("ImageFile", isUpload, result);
                    }} onDelete={() => {
                        Form.deleteFile("ImageFile");
                    }} />
                </Form.Field>
                <Form.RegistFile editable={editable} name="ImageFile" value={data.ImageFile} />

                <Form.Field>
                    <Form.Require style={{width:titleWidth}}><Form.Label>분류</Form.Label></Form.Require>
                    <Form.EntitySelect entity="FmsEquipmentCodeType" id="EquipmentTypeId" 
                        defaultLabel="분류" selectedValue={data.EquipmentTypeId} selectedText={data.EquipmentTypeName} editable={editable} useCheck={true}
                        onChange={(item) => { setValue('EquipmentTypeId', item.value, true) }}  />
                </Form.Field>
                <Form.Regist editable={editable} name="EquipmentTypeId" rule={{required:'분류를 선택하세요.'}} error={errors.EquipmentTypeId} />

                <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} />
                </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.Input placeholder="단위" defaultValue={data.Unit} onChangeText={text => setValue('Unit', text, true)} editable={editable} />
                </Form.Field>
                <Form.Regist editable={editable} name="Unit" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>규격</Form.Label></Form.Title>
                    <Form.Input placeholder="규격" defaultValue={data.Standard} onChangeText={text => setValue('Standard', text, true)} editable={editable} />
                </Form.Field>
                <Form.Regist editable={editable} name="Standard" />

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

                <Form.Field>
                    <Form.Require style={{width:titleWidth}}><Form.Label></Form.Label></Form.Require>
                    <Form.EntitySelect entity="FmsMaterialWarehouse" id="WarehouseId" siteId={session.getSiteId()}
                        defaultLabel="창고" 
                        selectedValue={data.WarehouseId} 
                        where={`BusinessFieldId=${businessFieldId}`} 
                        selectedText={data.WarehouseName} 
                        editable={editable} useCheck={true}
                        onChange={(item) => { setValue('WarehouseId', item.value, true) }}  />
                </Form.Field>
                <Form.Regist editable={editable} name="WarehouseId" rule={{required:'분류를 선택하세요.'}} error={errors.WarehouseId} />

                {action != Form.CREATE && auth.Update && (
                    <Fragment>
                        <Form.Field>
                            <Form.Title style={{width:titleWidth}}><Form.Label>전체수량</Form.Label></Form.Title>
                            <Form.Input placeholder="전체수량" value={data.TotalStockCount} editable={false} />
                        </Form.Field>
                        <Form.Field>
                            <Form.Title style={{width:titleWidth}}><Form.Label>현재재고</Form.Label></Form.Title>
                            <Form.Input placeholder="현재재고" value={data.CurrentStockCount} editable={false} />
                        </Form.Field>
                    </Fragment>
                )}

                {action == Form.CREATE && auth.Update && (
                    <Fragment>
                        <Form.Field>
                            <Form.Title style={{width:titleWidth}}><Form.Label>최초입고수량</Form.Label></Form.Title>
                            <Form.Input placeholder="최초입고수량"  
                                filter={(text) => {
                                    return InputFilters.number(text);
                                }}
                                onChangeText={text => setValue('StoredCount', text, true)} 
                                editable={editable} />
                        </Form.Field>
                        <Form.Regist editable={editable} name="StoredCount" />
                    </Fragment>
                )}

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>공급업체</Form.Label></Form.Title>
                    <Form.Input placeholder="공급업체" defaultValue={data.SupplierName} onChangeText={text => setValue('SupplierName', text, true)} editable={editable} />
                </Form.Field>
                <Form.Regist editable={editable} name="SupplierName" />

                <Form.Field>
                    <Form.Title style={{width:titleWidth}}><Form.Label>업체연락처</Form.Label></Form.Title>
                    <Form.Input placeholder="업체연락처" defaultValue={data.SupplierPhoneNo} onChangeText={text => setValue('SupplierPhoneNo', text, true)} editable={editable} />
                </Form.Field>
                <Form.Regist editable={editable} name="SupplierPhoneNo" />

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

            </Form.Container>
        </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 && auth.Delete && (
                        <Fragment>
                            <Form.EditButton navigation={navigation} type="primary" />
                            <Form.DeleteButton />
                        </Fragment>
                    )}
                    {editable && auth.Update && (
                        <Fragment>
                            <Form.SaveButton type="primary" />
                            {action != Form.CREATE && <Form.CancelEditButton navigation={navigation} />}
                        </Fragment>
                    )}
                    </Fragment>
                }
            /> 
        )
    } 
};

export default Screen;