import React, { Fragment, useState, useEffect, useLayoutEffect, useContext } from 'react';
import Styled from 'styled-components/native';
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 Theme from '~/Themes';
import moment from 'moment';
import _ from 'lodash';

const getYearItems = (start = null) => {
    if(!start) start = parseInt(moment().format('YYYY'));

    let years = [];
    for(let year = start; year >= start - 10; year--) {
        years.push({ label: year+'', value: year+''});
    }

    return years;
}

const ChartItem = Styled.View`
    flex:1;
    margin-top:3px;
    margin-bottom:3px;
    height:90px;
    background-color: #efefef;
    padding:8px;
    border-radius:5px;
`;
const ChartMonth = Styled.View`
    padding-left:10px;
`;
const ChartMonthTitle = Styled.Text`
    font-family: ${Theme.Fonts.Bold};
    font-size: 15px;
`;


{/*
<ChartBar>
    <Bar>
        <BarGraph style={{width:'70%'}}></BarGraph>
    </Bar>
    <ChartValue>70</ChartValue>
</ChartBar>
*/}

const ChartBars = Styled.View`
    flex-direction: column;
`;
const ChartBar = Styled.View`
    margin-top:2px;
    margin-bottom:2px;
    width:100%;
    height:20px;
    flex-direction: row;
    overflow: hidden;
`;
const Bar = Styled.View`
    flex:1;
`;
const BarGraph = Styled.View`
    background-color:green;
    height:20px;
`;

const ChartBaseText = Styled.Text`
    position: absolute;
    font-family: ${Theme.Fonts.Regular};
    font-size: 15px;
    line-height: 20px;
    margin-left:10px;
`;
const ChartValue = Styled.Text`
    font-family: ${Theme.Fonts.Regular};
    font-size: 15px;
    line-height: 20px;
    width: 100px;
    text-align: right;
`;

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

    const [years] = useState(getYearItems());
    const [loading, setLoading] = useState(false);
    const [searchParam, setSearchParam] = useState({
        FuelTypeId: 0,
        PriceTypeId: 0,
        BaseYear: moment().format('YYYY'),
        CompareYear: moment().add(-1, 'years').format('YYYY'),
        PriceCode: '',
    });
    const [priceTypeItems, setPriceTypeItems] = useState([]);
    const [data, setData] = useState({
        maxValue: 0,
        list: []
    });
    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 fetchPriceType = async (fuelTypeId) => {
        setLoading(true);
        try {
            const result = await fetchGet(`api/SitePrice/GetPriceType?siteId=${userinfo.SiteId}&fuelTypeId=${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 (params) => {
        console.log('searchParam - ', params);

        if(!params.FuelTypeId) return;
        if(!params.PriceTypeId) return;
        if(!params.PriceCode) return;
        if(!params.BaseYear) return;
        if(!params.CompareYear) return;

        setLoading(true);
        try {
            const result = await fetchGet(`/api/SitePriceHistory/GetChartData`, {
                siteId : userinfo.SiteId,
                fuelTypeId : params.FuelTypeId,
                priceTypeId : params.PriceTypeId,
                priceCode : params.PriceCode,
                baseYear : params.BaseYear,
                compareYear : params.CompareYear,
            });

            const maxBaseVal = _.maxBy(result, (o) => { return o.baseVal }).baseVal;
            const maxCompareVal = _.maxBy(result, (o) => { return o.compareVal }).compareVal;
            const maxValue = maxBaseVal > maxCompareVal ? maxBaseVal : maxCompareVal;

            for(let obj of result) {
                obj.baseValPercent = maxValue == 0 ? 0 : Math.round(obj.baseVal / maxValue * 100.0);
                obj.compareValPercent = maxValue == 0 ? 0 : Math.round(obj.compareVal / maxValue * 100.0);
            }

            setData({maxValue:maxValue, list:result});
            console.log({maxValue:maxValue, list:result});
        } catch(error) {
            showMessage(error.message);
        }
        setLoading(false);
    }

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

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

                <Form.Field>
                    <Form.Require><Form.Label>요금구분</Form.Label></Form.Require>
                    <Form.Select 
                        items={priceTypeItems} 
                        initialValue={searchParam.PriceTypeId} 
                        defaultLabel="요금구분" 
                        onChange={item => {
                            const params = {...searchParam, PriceTypeId: item.value};
                            setSearchParam(params);
                            fetch(params);
                        }}
                    />
                </Form.Field>

                <Form.Field>
                    <Form.Require><Form.Label>기준년도</Form.Label></Form.Require>
                    <Form.Select
                        items={years}
                        initialValue={searchParam.BaseYear}
                        defaultLabel="기준년도"
                        onChange={(item) => {
                            const params = {...searchParam, BaseYear: item.value};
                            setSearchParam(params);
                            fetch(params);
                        }}
                    />
                </Form.Field>

                <Form.Field>
                    <Form.Require><Form.Label>비교년도</Form.Label></Form.Require>
                    <Form.Select
                        items={years}
                        initialValue={searchParam.CompareYear}
                        defaultLabel="비교년도"
                        onChange={(item) => {
                            const params = {...searchParam, CompareYear: item.value};
                            setSearchParam(params);
                            fetch(params);
                        }}
                    />
                </Form.Field>

                <Form.Field>
                    <Form.Require><Form.Label>비교요소</Form.Label></Form.Require>
                    <Form.EntitySelect 
                        entity="BemsPriceCode"
                        id="PriceCode"
                        name="PriceCodeDesc"
                        where={`fuelTypeId = 1 and PriceCode in ('P038','P022','P003')`}
                        defaultLabel="비교요소" editable={true}
                        onChange={(item) => { 
                            const params = {...searchParam, PriceCode: item.value};
                            setSearchParam(params);
                            fetch(params);
                        }}
                    />
                </Form.Field>

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

                {!!data.list && Array.isArray(data.list) && data.list.map((item, index) => {
                    return (
                        <Fragment key={`item-${index}`}>
                            <ChartItem>
                                <ChartMonth>
                                    <ChartMonthTitle>{item.mon}</ChartMonthTitle>
                                </ChartMonth>
                                <ChartBars>
                                    <ChartBar>
                                        <Bar>
                                            <BarGraph style={{backgroundColor:'#11b31a', width:`${item.baseValPercent}%`}} />
                                            <ChartBaseText>{searchParam.BaseYear}</ChartBaseText>
                                        </Bar>
                                        <ChartValue>{item.baseVal}</ChartValue>
                                    </ChartBar>
                                    <ChartBar>
                                        <Bar>
                                            <BarGraph style={{backgroundColor:'#ffb600', width:`${item.compareValPercent}%`}} />
                                            <ChartBaseText>{searchParam.CompareYear}</ChartBaseText>
                                        </Bar>
                                        <ChartValue>{item.compareVal}</ChartValue>
                                    </ChartBar>
                                </ChartBars>
                            </ChartItem>
                        </Fragment>
                    )
                })}


                {/*
                <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.Container>
        </BottomTabBarLayout>
    );
};

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

    return { 
        header: () => (
            <Header 
                navigation={navigation} 
                title={`에너지비용`}
            /> 
        )
    } 
};

export default Screen;