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';
import moment from 'moment';

const Screen = ({navigation}) => {
    const { auth, userinfo, config } = useAuth(navigation);

    const [loading, setLoading] = useState(false);
    const [priceTypeParam, setPriceTypeParam] = useState({
        PayDate: moment().format('YYYYMM'),
        StartDate: moment().startOf('month').format('YYYY-MM-DD'),
        EndDate: moment().endOf('month').format('YYYY-MM-DD'),
        FuelTypeId: 0,
        PriceTypeId: 0,
    });
    const [priceTypeItems, setPriceTypeItems] = useState([]);
    const [data, setData] = useState({});
    const { showMessage } = useToast();

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

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

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

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

    const searchPriceType = async (param) => {
        setPriceTypeParam(param);
        if(!param.FuelTypeId) return;

        setLoading(true);
        try {
            const result = await fetchGet(`api/SitePrice/GetPriceType?siteId=${userinfo.SiteId}&fuelTypeId=${param.FuelTypeId}`);
            const items = result.map(x => { return { label:x.PriceTypeIdDesc, value:x.PriceTypeId } });
            setPriceTypeItems(items);
        } catch(error) {
            showMessage(error.message);
        }
        setLoading(false);
    }
    
    // search
    const fetch = async (param) => {
        setPriceTypeParam(param);

        setLoading(true);
        try {
            const result = await fetchGet(`api/SitePriceHistory/GetPriceData?siteId=${userinfo.SiteId}&payDate=${param.PayDate}&fuelTypeId=${param.FuelTypeId}&priceTypeId=${param.PriceTypeId}`);
            setData(result);
        } catch(error) {
            showMessage(error.message);
        }
        setLoading(false);
    }

    // save
    const onSave = async form => {
        if(!form.items || !Array.isArray(form.items) || form.items.length <= 0) {
            showMessage('연료 및 요금구분을 선택하여 요금정보를 조회해 주세요.');
            return;
        }

        if(loading) {
            showMessage('저장중입니다. 잠시만기다려 주세요.');
            return;
        }
        console.log('form', form.items);
        confirm('저장', '저장하시겠습니까?', async () => {
            setLoading(true);

            try {
                const result = await fetchPost(`api/SitePriceHistory/Save`, form.items);
                showMessage('저장되었습니다.');
            } 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.MonthPicker 
                        placeholder="고지서년월" 
                        monthFormat="YYYY년 MM월" 
                        onChange={(momentValue, stringValue) => {
                            fetch({
                                ...priceTypeParam,
                                PayDate: momentValue.startOf('month').format('YYYYMM'),
                                StartDate: momentValue.startOf('month').format('YYYY-MM-DD'),
                                EndDate: momentValue.endOf('month').format('YYYY-MM-DD'),
                            });
                        }}
                    />
                </Form.Field>

                <Form.Field>
                    <Form.Require><Form.Label>연료</Form.Label></Form.Require>
                    <Form.EntitySelect 
                        entity="BemsFuelType"
                        where={`FuelTypeId != 0`}
                        defaultLabel="연료" editable={true}
                        onChange={(item) => { 
                            if(priceTypeParam.FuelTypeId != item.value) {
                                searchPriceType({
                                    ...priceTypeParam,
                                    FuelTypeId: item.value,
                                    PriceTypeId: 0,
                                });
                                reset();
                                setData([]);
                            }
                        }}
                    />
                </Form.Field>

                <Form.Field>
                    <Form.Require><Form.Label>요금구분</Form.Label></Form.Require>
                    <Form.Select 
                        items={priceTypeItems} 
                        initialValue={searchPriceType.PriceTypeId} 
                        defaultLabel="요금구분" 
                        onChange={item => {
                            if(item.value != priceTypeParam.PriceTypeId) {
                                fetch({
                                    ...priceTypeParam,
                                    PriceTypeId: item.value,
                                });
                            }
                        }}
                    />
                </Form.Field>

                <Form.FieldSetHead>
                    <Form.Legend><Form.LegendLabel>요금정보</Form.LegendLabel></Form.Legend>
                </Form.FieldSetHead>
                <Form.FieldSet>
                    {!!data && Array.isArray(data) && data.map((item, index) => {
                        return (
                            <Fragment key={`item-${item.FuelTypeId}-${item.PriceTypeId}-${item.PayDate}-${item.PriceCode}`}>
                                <Form.Field>
                                    <Form.Title style={{width:200}}><Form.Label>{item.PriceCodeDesc}</Form.Label></Form.Title>
                                    <Form.Input 
                                        defaultValue={item.PriceValue}
                                        filter={(text) => {
                                            return InputFilters.decimal(text);
                                        }}
                                        onChangeText={(text) => {
                                            setValue(`items[${index}].PriceValue`, text);
                                        }} 
                                    />
                                </Form.Field>
                                <Form.Regist name={`items[${index}].SiteId`} value={item.SiteId} />
                                <Form.Regist name={`items[${index}].FuelTypeId`} value={item.FuelTypeId} />
                                <Form.Regist name={`items[${index}].PriceTypeId`} value={item.PriceTypeId} />
                                <Form.Regist name={`items[${index}].PriceCode`} value={item.PriceCode} />
                                <Form.Regist name={`items[${index}].PayDate`} value={item.PayDate} />
                                <Form.Regist name={`items[${index}].StartDate`} value={priceTypeParam.StartDate} />
                                <Form.Regist name={`items[${index}].EndDate`} value={priceTypeParam.EndDate} />
                                <Form.Regist name={`items[${index}].PriceValue`} value={item.PriceValue} />
                            </Fragment>
                        )
                    })}
                </Form.FieldSet>

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

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

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

    return { 
        header: () => (
            <Header 
                navigation={navigation} 
                title={`고지서관리`}
                buttons={
                    <Fragment>
                    {auth.Update && (
                        <Form.SaveButton type="primary" />
                    )}
                    </Fragment>
                }
            /> 
        )
    } 
};

export default Screen;