import React from 'react'
import 'antd-mobile/dist/antd-mobile.css';
import { CNavBar } from '../common/navbar.jsx';
import { Button, Flex, Card, List, WingBlank, WhiteSpace, Badge, DatePicker } from 'antd-mobile';
import { Http } from '../../Utils/help'
import Format from '../../Utils/NumericFormat';
import $ from 'jquery';


//import '../dashboard/less/list.less';

const F2 = require('@antv/f2');
const Item = List.Item;
const Brief = Item.Brief;

const colors = {
    '能耗': '#94e08a',  //能耗
    '能价': '#1890FF'  //能价
};
export default class EnergyAnalysis extends React.Component {
    constructor(props) {
        super(props);
        const { func } = this.props.location.state;
        this.StockageData = this.StockageData.bind(this);
        this.state = {
            func: func,
            data: [],
            electricitydetail: [],
        }
    }

    //取得json数据集
    componentWillMount() {
        //this.dataAjax = Http.getJSON2("ds/data/energyanalysis/energyanalysismerge");
        this.dataAjax = Http.getJSON2("ds/data/energyanalysis/energyanalysismergedetail", { "type": '0', "process": '' });
    }


    componentDidUpdate() {

    }

    componentDidMount() {
        console.log("componentDidMount--");

        this.dataAjax.done((result) => {
            //console.log(result);
            try {
                this.setState(
                    {
                        electricitydetail: this.packageing(result),
                    }, () => {
                        this.chartRender();
                    }
                )
            } catch (error) {
                console.error(error.message);
                console.error(error.stack);
            }
        })
    }

    packageing = (values) => {
        console.log("packageing--");
        //console.log(values);
        // console.log(JSON.stringify(values));
        var vdate = '';
        if (values) {
            var machine = "";
            var machine2 = "";
            for (let i = 0; i < values.length; i++) {
                if (values[i].machine != machine) {
                    console.log("values[i].machine==machine");
                    vdate = vdate.substring(0, vdate.length - 1) + ']},{"machine":"' + values[i].machine + '","machinename":"' + values[i].machinename + '","data":[' + JSON.stringify(values[i]) + ',';
                    machine = values[i].machine;
                } else {
                    //console.log("values[i].machine!=machine");
                    vdate = vdate + (JSON.stringify(values[i])) + ',';
                }

            }
            // console.log('[' + vdate1.substring(3, vdate1.length - 1) + ']},' + vdate.substring(3, vdate.length - 1) + ']}]');
            vdate = '[' + vdate.substring(3, vdate.length - 1) + ']}]';
            vdate = JSON.parse(vdate)

        }
        //console.log(vdate);
        return vdate;
    }

    chartRender = () => {
        console.log("chartrender...")
        //console.log(this.state.electricitydetail);
        //console.log(JSON.stringify(this.state.electricitydetail));

        this.StockageData(this.state.electricitydetail)
    }

    StockageData = (electricitydetail) => {
        electricitydetail.map((i, index) => {
            //console.log(i);
            for (let x = 0; x < 2; x++) {

                //F2 绘制图表
                F2.Global.pixelRatio = window.devicePixelRatio;
                const chart = new F2.Chart({
                    id: "energy" + (i.machine) + x,
                    padding: ['auto', 30, 40, 30]
                });
                if (i.data == null) {
                    console.log("i.data is null---");
                }
                //console.log(i.data);
                try {

                    if (x == 0) {
                        chart.source(i.data, {
                            date: {
                                type: 'timeCat',
                                tickCount: 6,
                                range: [0, 1],
                                mask: 'MM-DD',
                                size: 3
                            },
                            ydl: {
                                min: 0,
                                //30递增显示
                                tickInterval: 30
                            },
                            classify: {
                                type: 'cat',
                                values: ['峰值', '平值', '谷值', '总和']
                            }
                        });
                    } else {
                        chart.source(i.data, {
                            date: {
                                type: 'timeCat',
                                tickCount: 6,
                                range: [0, 1],
                                mask: 'MM-DD',
                                size: 3
                            },
                            outputi: {
                                type:'linear',
                                min: 0,
                                tickCount:5,
                                // tickInterval: 0.15,
                                alias: '能耗',
                                values: ['能耗']
                            },
                            price: {
                                type:'linear',
                                min: 0,
                                tickCount:5,
                                // tickInterval: 0.15,
                                alias: '能价',
                                values: ['能价']
                            }
                            , classify: {
                                type: 'cat',
                                values: ['能耗', '能价'],
                                alias: ['能耗', '能价']
                            }

                        }
                        );

                        //自定义tooltip
                        chart.tooltip(
                            {
                                showItemMarker: true,
                                custom: true, // 自定义 tooltip 内容框
                                showCrosshairs: true,//显示对应X轴的辅助线
                                showTitle:true,
                                //clickable : false,
                                onChange: function (obj) {
                                    const legend = chart.get('legendController').legends.top[0]; // 获取 legend
                                    const tooltipItems = obj.items;
                                    const legendItems = legend.items;

                                    const map = {};
                                    legendItems.map(item => {
                                        map[item.name] = F2.Util.mix({}, item);
                                    });
                                    tooltipItems.map(item => {
                                        const { name, value } = item;
                                        // console.log(item);
                                        if(item['name']=="总和"){
                                            // console.log(item['origin']['outputi'])
                                            // console.log(item['origin']['price'])
                                            map['能耗'].value = item['origin']['outputi'];
                                            map['能价'].value = item['origin']['price'];
                                        }
                                    });
                                    legend.setItems(Object.values(map));
                                    
                                }
                            }
                        );
                        //classify 的legend不能点击
                        chart.legend('classify',{
                            clickable:false
                        })
                    }
                    chart.axis('date', {
                        line: null,
                        label: {
                            fontSize: 13
                        }
                    });
                    chart.axis('ydl', {
                        grid(text) {
                            if (text === '0') {
                                return {
                                    stroke: '#efefef'
                                };
                            }
                            return {
                                stroke: '#f7f7f7'
                            };
                        },
                        label: {
                            fontSize: 14
                        }
                    });

                } catch (error) {
                    console.error(error.message)
                }

                //将数据值映射到图形
                if (x == 0) {
                    chart.line().position('date*ydl').color('classify').size(2).shape('smooth');
                    chart.point().position('date*ydl').color('classify').size(2).shape('smooth');
                } else if (x == 1) {
                    //color必须使用回调函数来指定classify为“总和”时的颜色，否则会有不能设定颜色的情况
                    chart.line().position('date*outputi').color('classify', classify => {
                        if (classify == '总和') {
                            return '#54FF9F';
                        }
                        return '#FFFFFF';
                    }).size(2).shape('smooth');
                    chart.point().position('date*outputi').color('classify', classify => {
                        if (classify == '总和') {
                            return '#54FF9F';
                        }
                        return '#FFFFFF';
                    }).size(2).shape('smooth');

                    chart.line().position('date*price').color('classify', classify => {
                        if (classify == '总和') {
                            return '#6495ED';
                        }
                        return '#FFFFFF';
                    }).size(2).shape('smooth');

                    chart.point().position('date*price').color('classify', classify => {
                        if (classify == '总和') {
                            return '#6495ED';
                        }
                        return '#FFFFFF';
                    }).size(2).shape('smooth');
                }
                //渲染图表
                chart.render();
            }
        }, this);
    }



    render() {
        return (
            <div style={{ height: '100%' }}>
                {this.state.electricitydetail.map((i, index) => (

                    <WingBlank size="lg">
                        <WhiteSpace size="lg" />
                        <Card>
                            <Card.Header
                                title={i.machinename + "能耗"}
                                extra={
                                    <Button disabled={!(i.data instanceof Array)} type="ghost" size="small" inline onClick={() => {
                                        if (null != i.machine && '' != i.machine) {
                                            console.log("Click 明细");
                                            const { history } = this.props;
                                            history.push({
                                                pathname: '/energyanalysisdetail',
                                                state: {

                                                    func: this.state.func,
                                                    code: i.machine,
                                                    name: i.machinename,
                                                    data: i.data
                                                }
                                            });
                                        }
                                    }}>明细</Button>
                                }
                            />
                            <Card.Body>
                                <div style={{ width: "100%", fontSize: '14px', padding: '0 5px' }}>
                                    <span style={{ background: "#98F5FF" }}>电量(kw)</span>
                                </div>
                                <hr style={{ height: "1px", border: "none", borderTop: "1px dashed #98F5FF" }} />
                                <div style={{ width: "100%", height: "200px", margin: "0 auto" }}>
                                    <canvas id={"energy" + (i.machine) + "0"} style={{ width: "100%", height: "100%" }}></canvas>
                                </div>
                                <div style={{ width: "100%", fontSize: '14px', padding: '0 5px' }}>
                                    <span style={{ background: "#00EE76" }}>能耗/能价</span>
                                </div>
                                <hr style={{ height: "1px", border: "none", borderTop: "1px dashed #00EE76" }} />
                                <div style={{ width: "100%", height: "200px", margin: "0 auto" }}>
                                    <canvas id={"energy" + (i.machine) + "1"} style={{ width: "100%", height: "100%" }}></canvas>
                                </div>
                            </Card.Body>
                        </Card>
                    </WingBlank>
                ))}

                <WhiteSpace size="lg" />
            </div>
        )
    }
}