import React, { Component,Fragment } from 'react';
import Echarts from '../../common/echarts/index'
import DrillDownBar from '../charts/drillDownBar'
import { hashcode } from '../../../utils/baseUtils'
import EmptyContent from '../../common/emptyContent'
import { connect } from 'dva'
import { Icon,message } from 'antd';
import moment from 'moment';
moment.locale('zh-cn');
moment.suppressDeprecationWarnings = true;
class EchartsView extends Component {
    render() { 
        const { chartOption, inDashBoard, item } = this.props;
        if(!chartOption || ((!chartOption.series || chartOption.series.length === 0) && (!chartOption.baseOption || !chartOption.baseOption.series || chartOption.baseOption.series.length === 0))) {
            return <EmptyContent />
        }else {
            const { baseOption } = chartOption;
            const { name } = baseOption;//主题
            //drillDown 钻取层级数组
            let { drillDown } = chartOption;
            const { originConfig } = baseOption;
            //drillable 是否开启钻取 boolean
            //drillList 钻取配置数组
            const { drillList, drillable } = originConfig;

            if(!drillDown && drillable && drillList && drillList.length>0 ){
                //初始化drillDown
                let baseDrill = drillList[0].column;
                let granularity = drillList[0].granularity;
                drillDown = chartOption.drillDown = [{
                    label : baseDrill.label,
                    field : baseDrill.value,
                    type : baseDrill.type,
                    filter : {},
                    showDataType : baseDrill.type==='time'?granularity.value:'',
                    value : null 
                }]
            }

            return (
                <Fragment>
                    {drillable?
                        (
                            <div style={{display:'flex'}}>
                                <Icon type="gold" style={{margin:'0 0 0 15px',fontSize:'20px'}} theme="twoTone" />
                                {
                                    /* 
                                     *  在钻取开启后 drillDown会生成钻取数组 默认为第一层
                                     *  DrillDownBar组件为钻取层级工具栏
                                     */
                                    <DrillDownBar className={`drilldownbar ${name}`} inDashBoard={inDashBoard} item={item} key={hashcode(drillDown)} drillDown={drillDown}></DrillDownBar>
                                }
                            </div>
                        )
                    :null}
                    <Echarts
                        key={hashcode({
                            baseOption: chartOption.baseOption,
                            media: chartOption.media
                        })}
                        option={chartOption}
                        events={drillable?this.getEvents:{}}
                    />
                </Fragment>
            ) 
        }
    }

    //加入事件
    getEvents = {
        'click': this.onEchartClick.bind(this)
    }

    onEchartClick(e,echart){
        let index = -1;
        //判断是否点击了图表
        if( echart ){
            const echartInstance = echart.getEchartsInstance();
            const pointInPixel = [e.offsetX, e.offsetY];
            if( echartInstance.containPixel('grid',pointInPixel) ){
                //获取点击的X轴的索引
                index = echartInstance.convertFromPixel({seriesIndex:0},pointInPixel)[0];
            }else{
                return false;
            }
        }
        
        // 钻取（下钻）
        const { chartOption, dispatch, inDashBoard, item } = this.props;
        let { drillDown } = chartOption;
        const { baseOption } = chartOption;
        const { originConfig } = baseOption;
        const { drillList } = originConfig;
        let xType = e.componentSubType || (baseOption.bar?'bar':null) || 
                    (baseOption.line?'line':null) ||  (baseOption.pie?'pie':null);
        let xValue = index>-1?baseOption.xAxis[0].data[index]:e.name;
        // 若下钻层级已到达钻取配置最后一层 提示信息
        if( drillList.length === drillDown.length ){
            message.warning('已经钻取到最后一层了！');
            return false;
        }
        //拿到上一层级的钻取配置
        let preDrill = drillList.slice(drillDown.length-1,drillDown.length)[0];
        //拿到当前层级的钻取配置
        let curDrill = drillList.slice(drillDown.length,drillDown.length+1)[0];
        //将本次钻取的数据加入drillDown中
        switch(xType){
            case 'bar':{
                drillDown.push({
                    label : curDrill.column.label,
                    field : curDrill.column.value,
                    type : curDrill.column.type,
                    filter : this.getFilter(preDrill,xValue),
                    value : xValue,
                    showDataType : curDrill.column.type==='time'?curDrill.granularity.value:''
                });
                break;
            }
            case 'line':{
                drillDown.push({
                    label : curDrill.column.label,
                    field : curDrill.column.value,
                    type : curDrill.column.type,
                    filter : this.getFilter(preDrill,xValue),
                    value : xValue,
                    showDataType : curDrill.column.type==='time'?curDrill.granularity.value:''
                });
                break;
            }
            case 'pie':{
                //饼图如果是其它 并且tooMany(后台判断有 其他 部分) 为 true 时 不能下钻
                if( xValue==='其它' && chartOption.baseOption.originConfig.tooMany ){
                    drillDown.push({
                        label : curDrill.column.label,
                        field : curDrill.column.value,
                        type : curDrill.column.type,
                        filter : {
                            name: preDrill.column.value,
                            label: preDrill.column.label,
                            type: preDrill.column.type,
                            operator: 'notIn',
                            operatorLabel: '不包括',
                            value1: originConfig.data.slice(0, -1).map(d => d.name).join(),
                            value2: originConfig.data.slice(0, -1).map(d => d.name).join(),
                            drillDownType: preDrill.granularity.value
                        },
                        value : xValue,
                        showDataType : curDrill.column.type==='time'?curDrill.granularity.value:''
                    });
                }else {
                    drillDown.push({
                        label : curDrill.column.label,
                        field : curDrill.column.value,
                        type : curDrill.column.type,
                        filter : this.getFilter(preDrill,xValue),
                        value : xValue,
                        showDataType : curDrill.column.type==='time'?curDrill.granularity.value:''
                    });
                }
                break;
            }
            default:{
                return false;
            }
        }
        
        let page = null;
        let pageSize = null;

        if(inDashBoard){
            //调用对应的图表类型的接口
            let { chartType } = item
            let type = `${chartType.charAt(0).toUpperCase()}${chartType.slice(1,chartType.length)}`
            dispatch({ 
                type: 'dashboardDesigner/setItemFetching', code: item.code, fetching: true 
            })
            dispatch({ 
                type: `chartDesigner/fetch${type}Data`, page, pageSize, drillDown, inDashBoard, item 
            }).then(option => {
                dispatch({ 
                    type: 'dashboardDesigner/setItemFetching', code: item.code, fetching: false 
                })
                dispatch({ type: 'dashboardDesigner/setItemFields', code: item.code, fields: [
                    { name: 'chartOption', value: option }
                ]})
            })
            
        }else{
            dispatch({ type: 'chartDesigner/fetchChartData', page, pageSize, drillDown });
        }
    }

    getFilter(curDrill,xValue){
        const { column } = curDrill;
        if( xValue === '空'){
            return {
                name: column.value,
                label: column.label,
                type: column.type,
                operator: 'isNull',
                operatorLabel: '为空',
                value1: xValue,
                value2: xValue,
            }
        }
        switch(column.type){
            case 'categorical':{
                return {
                    name: column.value,
                    label: column.label,
                    type: column.type,
                    operator: '=',
                    operatorLabel: '等于',
                    value1: xValue,
                    value2: xValue,
                }
            }
            case 'time':{
                //解析时间
                const { granularity } = curDrill;
                let values = this.getTimeByType(granularity,xValue);
                return {
                    name: column.value,
                    label: column.label,
                    type: column.type,
                    operator: values.operator,
                    operatorLabel: values.operatorLabel,
                    value1: values.value1,
                    value2: values.value2,
                    drillDownType: granularity.value
                }
            }
            default:{
                return {};
            }
        }
    }

    getTimeByType(granularity,value){
        //解析时间
        switch(granularity.value){
            case 'year':{
                return {
                    value1: `${value}`,
                    value2: '',
                    operator: '=',
                    operatorLabel: '等于'
                }
            }
            case 'halfYear':{
                //解析value
                //可能有 (- 上半年) 的情况
                let year = value.split(' ')[0];
                let value1,value2;
                if(value.indexOf('上半年')>-1){
                    value1 = `${year}-H1`;
                    value2 = `${year}-H1`;
                }else{
                    value1 = `${year}-H2`;
                    value2 = `${year}-H2`;
                }
                return {
                    value1: value1,
                    value2: value2,
                    operator: 'in',
                    operatorLabel: '介于'
                }
            }
            case 'quarter':{
                //解析value
                let to_number = {
                    '一':1,
                    '二':2,
                    '三':3,
                    '四':4
                }
                let quarter = to_number[value.split(' ')[1].charAt(0)];
                let year = value.split(' ')[0];

                return {
                    value1: `${year}-${quarter}`,
                    value2: '',
                    operator: '=',
                    operatorLabel: '等于'
                }
            }
            case 'month':{
                //解析value
                let month = value.split('/')[1];
                let year = value.split('/')[0];

                /* 对月数进行格式化 */
                if(month < 10){
                    month = '0' + month
                } 

                return {
                    value1: moment(`${year}-${month}-01`).format('YYYY-MM'),
                    value2: '',
                    operator: '=',
                    operatorLabel: '等于'
                }
            }
            case 'week':{
                //解析value
                let week = value.replace(' ','-').split('周')[0];

                return {
                    value1: week,
                    value2: '',
                    operator: '=',
                    operatorLabel: '等于'
                }
            }
            case 'day':{
                return {
                    value1: moment(`${value}`).format('YYYY-MM-DD'),
                    value2: '',
                    operator: '=',
                    operatorLabel: '等于'
                }
            }
            default:{
                return {};
            }
        }
    }
}
 
export default connect()(EchartsView);