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

const Screen = ({navigation}) => {
    const refreshList = navigation.getParam('refreshList', ()=>{});
    const siteId = navigation.getParam('siteId', '');
    const { auth, userinfo, config } = useAuth(navigation);

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

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

        try {
            console.log('get - ', `api/app/Equipment/${siteId}/${equipmentId}`);
            const result = await fetchGet(`api/app/Equipment/${siteId}/${equipmentId}`);
            result.StoredCount = '0';
            setData(result);
            Form.setFormData(result);
        } catch(error) {
            showMessage(error.message);
        }

        setLoading(false);
    }

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

            try {
                const result = await fetchPut(`api/app/EquipmentHistory`, submit);
                showMessage('저장되었습니다.');
                refreshList();
                navigation.pop();
            } catch(error) {
                showMessage(error.message);
            }
            setLoading(false);
        });
    }

    return ( 
        <BottomTabBarLayout>
            <Form.Container onSave={handleSubmit(onSave)} loading={loading}>

                <Form.Field>
                    <Form.Require><Form.Label>추가입고</Form.Label></Form.Require>
                    <Form.Switch editable={true} initialValue={true} onChange={() => {
                        navigation.replace('Form', {
                            auth: auth,
                            userinfo: userinfo,
                            config: config,
                            refreshList: refreshList,
                            action: Form.CREATE, 
                            siteId: siteId, 
                        });
                    }} />
                </Form.Field>

                <Form.Field>
                    <Form.Require><Form.Label>공기구</Form.Label></Form.Require>
                    <Form.EntitySelect entity="FmsEquipment" siteId={siteId}
                        defaultLabel="공기구선택" editable={true}
                        onChange={(item) => {
                            setValue('EquipmentId', item.value, true);
                            fetch(item.value);
                        }}  />
                </Form.Field>
                <Form.Regist name="EquipmentId" rule={{required:'공기구를 선택하세요.'}} error={errors.EquipmentId} />

                <Form.Field>
                    <Form.TitleTop><Form.Label>이미지</Form.Label></Form.TitleTop>
                    <Form.UploadFile type={UploadFileType.Image} editable={false} defaultFile={data.ImageFile} />
                </Form.Field>

                <Form.Field>
                    <Form.Require><Form.Label>분류</Form.Label></Form.Require>
                    <Form.Input placeholder="분류" value={data.EquipmentTypeName} editable={false} />
                </Form.Field>

                <Form.Field>
                    <Form.Require><Form.Label>이름</Form.Label></Form.Require>
                    <Form.Input placeholder="이름" value={data.Name} editable={false} />
                </Form.Field>

                <Form.Field>
                    <Form.Title><Form.Label>규격</Form.Label></Form.Title>
                    <Form.Input placeholder="규격" value={data.Standard} editable={false} />
                </Form.Field>
                
                <Form.Field>
                    <Form.Title><Form.Label>단위</Form.Label></Form.Title>
                    <Form.Input placeholder="단위" value={data.Unit} editable={false} />
                </Form.Field>

                <Form.Field>
                    <Form.Require><Form.Label>창고명칭</Form.Label></Form.Require>
                    <Form.Input placeholder="창고명칭" value={data.WarehouseName} editable={false} />
                </Form.Field>

                <Form.Field>
                    <Form.Title><Form.Label>공급업체</Form.Label></Form.Title>
                    <Form.Input placeholder="공급업체" value={data.SupplierName} editable={false} />
                </Form.Field>

                <Form.Field>
                    <Form.Title><Form.Label>업체연락처</Form.Label></Form.Title>
                    <Form.Input placeholder="업체연락처" value={data.SupplierPhoneNo} editable={false} />
                </Form.Field>

                <Form.Field>
                    <Form.Require><Form.Label>입고수량</Form.Label></Form.Require>
                    <Controller
                        name="StoredCount"
                        control={control}
                        as={
                            <Form.Input placeholder="추가입고수량"  
                                filter={(text) => {
                                    return InputFilters.number(text);
                                }}
                                onChangeText={text => setValue('StoredCount', text, true)} 
                                editable={true} />
                        } />
                </Form.Field>
                <Form.Regist name="StoredCount" rule={{required:'추가입고수량을 입력하세요.'}} error={errors.StoredCount} />

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

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

Screen.navigationOptions = ({navigation}) => { 
    const { auth } = useAuth(navigation);

    return { 
        header: () => (
            <Header 
                navigation={navigation} 
                title={`공기구정보`}
                main={false}
                buttons={
                    <Fragment>
                    {auth.Update && (
                        <Fragment>
                            <Form.SaveButton type="primary" />
                        </Fragment>
                    )}
                    </Fragment>
                }
            /> 
        )
    } 
};

export default Screen;