import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Connect, Modal } from 'amos-framework';
import * as endConf from 'amos-processor/lib/config/endconf';
import ReactEcharts from 'amos-viz/lib/echarts';
import { rightTopChartAction ,getxuncountAction} from '../../../../../services/3dService';
import SysWsURL, { completeToken } from './../../../../../consts/wsUrlConsts';
import AmosWebSocket from 'amos-websocket';
import moment from 'moment';
import { isArray } from 'amos-pluggable/lib/_utils';
import message from 'amos-framework/lib/message';
const eventConnect = Connect.eventConnect;
const AmosConfig = endConf.AmosConfig;
const chartStyle = {
  width: '100%', height: '100%'
};

@eventConnect
class TopCharts extends Component {
  constructor(props) {
    super(props);

    this.state = {
      data:{},
      currentCode: '',
      technologyDataname: '',
      serviceDataname: '',
      technologyData: {},
      serviceData: {},
      dataList: [],
      xun:{}
    };
  }

  componentDidMount() {
    this.freshDataList(this.props.curCompanyId);
    this.getxuncount();
  }

  componentWillReceiveProps = nextProps => {
    if (this.props.currentCode !== nextProps.currentCode) {
      console.log(nextProps.currentCode,'nextProps.currentCode')
      const { currentCode, curCompanyId } = nextProps || {};
      this.state.currentCode = currentCode;
      this.freshDataList(nextProps.curCompanyId);
      this.setState({ currentCode });
      this.getxuncount();
    }
  };


  //巡检点统计
  getxuncount(){
    getxuncountAction().then(data => {
      this.setState({
        xun: data
      });
    });
  }



  freshDataList(companyId){
    rightTopChartAction(companyId).then(data => {
      this.setState({
        dataList: data
      });
    });
  }

  getOptions = (data,title) => {
    let seriesData = [

      { value: data.normal || 0, name:'正常' },
      { value: data.abnormal || 0, name:'异常'},
      { value: data.missedDetection || 0, name:'漏点' },
      { value: data.notIncluded || 0, name:'未计划' },
    ];
    return {

      tooltip: {
          trigger: 'item',
          formatter: "{b}: {c} ({d}%)"
      },
      legend: {
          orient: 'vertical',
          x: 'left',
          top:'35%',
          left:'10%',
          itemWidth: 15,
          itemHeight: 10,
          itemGap: 10,
          data:['正常','异常','漏点','未计划'],
          formatter: function(name) {
            let curItem = seriesData.find( e => {
              return e.name === name;
            })
            var content = name +'：' + curItem.value;
            return content;
          },
          textStyle: {
            color: '#ffffff',//字体颜色
            fontSize: 10
          }
      },
      color:['#88FF00','#FF9100','#FF0000','#D8D8D8'],
      series: [
          {
              name:'检查点',
              type:'pie',
              center:['70%','60%'],//饼图位置
              radius: ['50%', '70%'],//外半径，内半径
              avoidLabelOverlap: false,
              label: {
                  normal: {
                      show: true,
                      position: 'center',
                      formatter: function(param) {
                          let total = 0;
                          seriesData.forEach(e => {
                            total += e.value;
                          })
                          var view =  total + '\r\n总数';
                          return view;
                        },
                      textStyle: {
                        fontSize: 14,
                        color: '#D8D8D8'
                      },
                  },
              },
              labelLine: {
                  normal: {
                      show: false
                  }
              },
              data:seriesData
          }
      ]
    };
  }


  getOptionsx = (data,title) => {


    return {
      backgroundColor:'rgba(23,90,201,0.9)',
      tooltip: {
        trigger: 'axis',
        axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
        }
    },
         grid: {
           left: '2%',
           right: '4%',
           bottom: '14%',
           top:'16%',
           containLabel: true
         },
          legend: {
         data: ['未开始', '进行中', '已结束','已超时'],
         right: 10,
         top:12,
         textStyle: {
             color: "#fff"
         },
         itemWidth: 12,
         itemHeight: 10,
         // itemGap: 35
     },
         xAxis: {
           type: 'category',
           triggerEvent :true,
           data: data.x,
           axisLine: {
             lineStyle: {
               color: 'white'

             }
           },
           axisLabel: {
             // interval: 0,
             // rotate: 40,
             textStyle: {
               fontFamily: 'Microsoft YaHei'
             }
           },
         },

         yAxis: {
           type: 'value',
           axisLine: {
             show: false,
             lineStyle: {
               color: 'white'
             }
           },
           splitLine: {
             show: true,
             lineStyle: {
               color: 'rgba(255,255,255,0.3)'
             }
           },
           axisLabel: {}
         },

         series: [{
           name: '未开始',
           type: 'bar',
           barWidth: '15%',
           itemStyle: {
            normal: {
                color:'#02E3FC',
                barBorderRadius: 11,
            },
        },
           data:data.wks
         },
         {
           name: '进行中',
           type: 'bar',
           barWidth: '15%',
           itemStyle: {
            normal: {
                color:'#00FF55',
                barBorderRadius: 11,
            },
        },
        data:data.yxz
         },
         {
           name: '已结束',
           type: 'bar',
           barWidth: '15%',
           itemStyle: {
            normal: {
                color:'#FF8000',
                barBorderRadius: 11,

            },
        },
        data:data.yjs
         },
         {
           name: '已超时',
           type: 'bar',
           barWidth: '15%',
           itemStyle: {
            normal: {
                color:'#FF0000',
                barBorderRadius: 11,

            },
        },
        data:data.ycs
         }]
       };
  }

  onclick = {
    'click': this.clickEchartsPie.bind(this)
}
clickEchartsPie(e) {
  const {  dataList } = this.state;
  let ff={}
  isArray(dataList) && dataList.forEach(e => {

    ff = e;
  });
  if(e.hasOwnProperty("name")){
    if(ff[ff[e.name]]>0){

      this.props.patrolDetailView(e.name,ff[e.name]);
    }else{
      message.danger('当前没有巡检计划');
    }


  }else{
    if(ff[ff[e.value]]>0){

      this.props.patrolDetailView(e.value,ff[e.value]);
    }else{
      message.danger('当前没有巡检计划');
    }

  }





}






  handleData = (data = {}) => {
    //console.log('topChart ws data:', data);
    if (data === 'planTaskRefresh'){
      this.getxuncount();
      this.freshDataList(this.props.curCompanyId);
    } else {
      this.setState({ data });
    }
  };

  render() {
    let now = moment().locale('zh-cn').format('YYYY-MM-DD');
    const { data, dataList } = this.state;
    const wsURL = completeToken(SysWsURL.topChartws);
    const planTaskWsURL = completeToken(SysWsURL.planTaskURI);
    let { technologyData,xun, serviceData ,technologyDataname,serviceDataname} = this.state;
    //console.log(dataList,'topchartDataList');
    isArray(dataList) && dataList.forEach(e => {
        technologyData = e;
    });



    return (
        <div className='left-chart-top'>


           <div className='left-chart-child'>
             <ReactEcharts option = { this.getOptionsx(technologyData, null) }  eventpool={this.onclick}/>

          </div>
          <div className='left-chart-child'>
          <div className='title'>
                <span className='titleLeft'>
                <span className='titleIcon' style={{ background: 'url("/src/assets/indexChart/point.png") no-repeat center center/100% 100%' }}></span>
                  巡检点状态统计</span>
              </div>
            <ReactEcharts option = { this.getOptions(xun,"") } className='child-pie'/>

          </div>
          <AmosWebSocket ref={node => this.aws = node} url={wsURL} onMessage={this.handleData} reconnect debug />
          <AmosWebSocket ref={node => this.aws = node} url={planTaskWsURL} onMessage={this.handleData} reconnect debug />
        </div>
    );

  }
}

TopCharts.propTypes = {
  subscribe: PropTypes.func,
  trigger: PropTypes.func
};

export default TopCharts;
