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

const Screen = ({navigation}) => {
    const action = navigation.getParam('action', Form.VIEW);
    const refreshList = navigation.getParam('refreshList', ()=>{});
    const siteId = navigation.getParam('siteId', '');
    const fuelTypeId = navigation.getParam('fuelTypeId', '');
    const fuelPriceId = navigation.getParam('fuelPriceId', '1');
    const priceTypeId = navigation.getParam('priceTypeId', '');
    const yearMonth = navigation.getParam('yearMonth', '');
    const [content, setContent] = useState('');
    const { auth } = useAuth(navigation);
    const { showMessage } = useToast();
    const [priceTypes, setPriceTypes] = useState([]);

    const [loading, setLoading] = useState(false);

    // mount
    useEffect(() => {
        (async () => {
            await session.load();
            await fetchPriceTypes(fuelTypeId);
            await fetch();
        })();
    }, []);

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

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

    const fetchPriceTypes = async (fuelTypeId) => {
        try {
            const result = await fetchGet('/api/EnergyDayAnalysis/GetPriceType', {
                siteId, fuelTypeId
            });
            if(result && Array.isArray(result)) {
                setPriceTypes(result.map((item) => { return { label: item.PriceTypeIdDesc, value: item.PriceTypeId } }));
            }
        } catch(error) {
            showMessage(error.message);
        }
    }
    
    // search
    const fetch = async (fetchParam={}) => {
        setLoading(true);

        try {
            const year = moment(yearMonth).format('YYYY');
            const month = moment(yearMonth).format('M');
            const postParam = {
                siteId, fuelTypeId, fuelPriceId:1, year, month, priceTypeId
            };
            console.log(postParam);
        
            let result = await fetchGet(`api/EnergyDayAnalysis/GetAnalysisData`, {
                ...postParam,
                ...fetchParam
            });

            if(result.length > 0) {
                setContent(result[0].Content);
            } else {
                setContent('');
            }
        } catch(error) {
            showMessage(error.message);
        }

        setLoading(false);
    }

    // save
    const onSave = async () => {
        if(!priceTypeId) {
            showMessage('요금제를 선택하세요.');
            return;
        }

        if(loading) {
            showMessage('저장중입니다. 잠시만기다려 주세요.');
            return;
        }

        const year = moment(yearMonth).format('YYYY');
        const month = moment(yearMonth).format('M');
        var info = [];
        info.push({
          SiteId: siteId,
          FuelTypeId: fuelTypeId,
          FuelPriceId: 1,
          PriceTypeId: priceTypeId,
          Year: year,
          Month: month,
          Content: content,
        });
        const submit = info[0];
    
        confirm('저장', '저장하시겠습니까?', async () => {
            setLoading(true);

            try {
                const result = await fetchPost(`api/EnergyDayAnalysis/${siteId}/${fuelTypeId}/1/${year}/${month}/${priceTypeId}`, submit);

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

    return ( 
        <BottomTabBarLayout>
            <Form.Container onSave={onSave} loading={loading}>
                <Form.Field>
                    <Form.Title><Form.Label>에너지종류</Form.Label></Form.Title>
                    <Form.EntitySelect entity="BemsFuelType" defaultLabel="에너지종류" 
                        id="FuelTypeId" name="Name"
                        selectedValue={fuelTypeId} editable={false}
                        onChange={(item) => { 
                            navigation.setParams({fuelTypeId: item.value});
                            fetchPriceTypes(item.value);
                            fetch({fuelTypeId: item.value});
                        }} />
                </Form.Field>

                <Form.Field>
                    <Form.Title><Form.Label>요금제</Form.Label></Form.Title>
                    <Form.Select 
                        items={priceTypes} 
                        initialValue={priceTypeId} 
                        defaultLabel="요금제" 
                        onChange={item => {
                            navigation.setParams({priceTypeId: item.value});
                            fetch({priceTypeId: item.value});
                        }}
                    />
                </Form.Field>

                <Form.Field>
                    <Form.Title><Form.Label>년월</Form.Label></Form.Title>
                    <Form.MonthPicker 
                        month={yearMonth} 
                        placeholder="년월" 
                        monthFormat="YYYY년 MM월" 
                        maximumDate="9999-12" 
                        editable={false} 
                        onChange={(momentValue, stringValue) => {
                            navigation.setParams({yearMonth: momentValue.startOf('month').format('YYYY.MM')});
                            fetch({yearMonth:momentValue.startOf('month').format('YYYY.MM')});
                        }} 
                    />
                </Form.Field>

                <Form.Field>
                    <Form.TitleTop><Form.Label>증감이유</Form.Label></Form.TitleTop>
                    <Form.Input value={content} defaultValue={content} editable={true} multiline={true} onChangeText={(text) => {
                        setContent(text);
                    }} />
                </Form.Field>

                <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 && (<Form.SaveButton type="primary" />)}
                    </Fragment>
                }
            /> 
        )
    } 
};

export default Screen;