import React from 'react'
import 'antd-mobile/dist/antd-mobile.css';
import { CNavBar } from '../common/navbar.jsx';
import { Button, Flex, NavBar, 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;

export default class EnergyAnalysisDetail extends React.Component {
    constructor(props) {
        super(props);
        const { func, code, name, data } = this.props.location.state;
        //this.StockageData = this.StockageData.bind(this);
        this.state = {
            func: func,
            data: data,
            code: code,
            name: name,
            electricitydetail: []
        }
    }
    //取得json数据集
    componentWillMount() {
        console.log(this.state.code);
        console.log(this.state.name);
        //console.log(JSON.stringify(this.state.data));
        this.dataAjax = Http.getJSON2("ds/data/energyanalysis/energyanalysismergedetail", { "type": '1', "process": this.state.code });
    }

    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 machno = "";
            for (let i = 0; i < values.length; i++) {
                //console.log(values[i]);
                if (values[i].machno != machno) {
                    console.log("values[i].machno!=machno");
                    vdate = vdate.substring(0, vdate.length - 1) + ']},{"machno":"' + values[i].machno + '","name":"' + values[i].name + '","data":[' + JSON.stringify(values[i]) + ',';
                    machno = values[i].machno;
                } else {
                    vdate = vdate + (JSON.stringify(values[i])) + ',';
                }
            }
            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);

        try {
            this.electricityData(this.state.electricitydetail);
        } catch (error) {
            console.error(error.message);
        }
    }

    electricityData = (electricitydetail) => {
        electricitydetail.map((i, index) => {
            for (let x = 0; x < 2; x++) {
                //F2 绘制图表
                F2.Global.pixelRatio = window.devicePixelRatio;
                const chart = new F2.Chart({
                    id: "energyanalysisinfo" + (i.machno) + x,
                    padding: ['auto', 30, 40, 30]
                });
                // console.log(i['data']);
                // [0]['classify']
                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.02,
                                alias: '能耗',
                                values: ['能耗']
                            },
                            price: {
                                type:'linear',
                                min: 0,
                                tickCount:5,
                                // tickInterval: 0.02,
                                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) {
                    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%' }}>
                <NavBar mode="light">
                    <span style={{ color: '#000' }}>{this.state.name + '能耗'}</span>
                </NavBar>
                {this.state.electricitydetail.map((i, index) => (
                    <WingBlank size="lg">
                        <WhiteSpace size="lg" />
                        <Card>
                            <Card.Header title={i.machno + ' ' + i.name + "能耗"} />
                            <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={"energyanalysisinfo" + (i.machno) + "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={"energyanalysisinfo" + (i.machno) + "1"} style={{ width: "100%", height: "100%" }}></canvas>
                                </div>
                                {/* <div style={{ width: "100%", fontSize: '14px', padding: '0 5px' }}>
                                    <span style={{ background: "#EEB4B4" }}>能价</span>
                                </div>
                                <hr style={{ height: "1px", border: "none", borderTop: "1px dashed #EEB4B4" }} />
                                <div style={{ width: "100%", height: "200px", margin: "0 auto" }}>
                                    <canvas id={"energyanalysisinfo" + (i.machno) + "2"} style={{ width: "100%", height: "100%" }}></canvas>
                                </div> */}
                            </Card.Body>
                        </Card>
                    </WingBlank>
                ))}

                <WhiteSpace size="lg" />
            </div>
        )
    }
}