import React, { Component } from "react";
import style from "../index.less";
import { Radio} from '@commonComp';
import echarts from 'echarts';
import config from "@config";
import 'zrender/lib/svg/svg';
/**
 * 来源于后台数据
 * 图表类型
 *
 *
 * **/
class ChartItem extends Component {
  constructor(props) {
    super(props);
    this.getContainers = this.getContainers.bind(this);
    this.rangChange = this.rangChange.bind(this);
    this.getXAxisArr = this.getXAxisArr.bind(this);
  }
  getXAxisArr(type){
    const endDate = this.props.endDate;
    let now = endDate?new Date(endDate).getTime():new Date().getTime();
    let arr = [],temp=0;
    //近一周
    switch(type){
      case 'week':
        arr.push(...this.getDayHours(now,true,1));
        for(let i=1;i<6;i++){
          temp=i*1000*60*60*24;
          arr.unshift(...this.getDayHours(now-temp,true));
        };
        arr.unshift(...this.getDayHours(now-6*1000*60*60*24,true,2));
        break;
      case 'month':
        for(let i=0;i<30;i++){
          temp=i*1000*60*60*24;
          arr.unshift(this.getDayHours(now-temp));
        }
        break;
      case 'sixMonth':
        for(let i=0;i<180;i++){
          temp=i*1000*60*60*24;
          arr.unshift(this.getDayHours(now-temp));
        }
        break;
      case 'year':
        for(let i=0;i<365;i++){
          temp=i*1000*60*60*24;
          arr.unshift(this.getDayHours(now-temp));
        }
        break;
      default:
    }

    return arr;
  }
  getDayHours(time,isHour,isLimit){
    const year = new Date(time).getFullYear();
    const month = new Date(time).getMonth()+1;
    const date = new Date(time).getDate();
    const hour = new Date(time).getHours();
    let arr=[],temp='';
    const str= year+'-'+(month<10?'0'+month:month)+'-'+(date<10?'0'+date:date);
    if(isHour){
      const num = isLimit===1?hour+1:24;
      for(let i=(isLimit===2?hour:0);i<num;i++){
        //temp = hour-i>-1?hour-i:hour-i+24;
        arr.push(str+" "+(i<10?'0'+i:i)+":00:00");
      }
      return arr;
    }else{
      return str;
    }
  }
  rangChange(type,i){
    const {initFn,disName,handleChange,data,pindex} = this.props;
    const times = this.getXAxisArr(type);
    const startTime=times[0];
    const endTime=times[times.length-1];
    const range = [startTime,endTime];
    const temp=this.props.timeTypes;
    if(!data[startTime+endTime]){
      initFn&&initFn({range,disName,rangeType:type,index:i,pindex,getNew:false});
    }
    handleChange&&handleChange(Object.assign(temp,{[i]:type}));
  }
  getContainers(obj){
    const timeTypes = this.props.timeTypes;
    const {endDate} = this.props;
    let len = 1,idx=0;    //单个图表第一条线的在所有线中的index,用于显示不同的形状，打印使用
    let arr = [],keys = Object.keys(obj||{});
    for(let i in obj){
      idx = keys.findIndex((t)=>{return t==i});
      len = idx==0?0:len+obj[keys[idx-1]].length;
      arr.push(<Chart data={obj[i]} len={len} endDate={endDate} type={timeTypes&&timeTypes[i]} index={i} getXAxisArr={this.getXAxisArr} handleRangeChange={this.rangChange}/>)
    }
    return arr.length>0?arr:<p style={{color:'#acacac'}}>该模块暂无数据</p>;
  }
  getLegends(obj){
    let arr = [],temp='',doms=[];
    for(let i in obj){
      arr = [...arr,...obj[i]];
    }
    arr.map((it,ix)=>{
      doms.push(<div><img src={require('@common/images/'+(ix+1)+'.png')} /><span>{it}</span></div>);
    });
    return doms;
  }
  componentDidMount(){
    const {initFn,pindex,disName} = this.props;
    const type = config.chartDismen;
    const times = this.getXAxisArr(config.chartDismen);
    const startTime=times[0];
    const endTime=times[times.length-1];
    const range = [startTime,endTime];
    initFn&&initFn({range,disName,rangeType:type,pindex,getNew:true});
  }
  render() {
    const {title,data,names} = this.props;
    const range = this.getXAxisArr(config.chartDismen);
    const obj = data[range[0]+range[range.length-1]];
    const nameObj = names&&names[range[0]+range[range.length-1]];
    return <div className={style['assess-item']}>
      <h2>{title}</h2>
      <div className={style['legend']}>
        {this.getLegends(nameObj)}
      </div>
      <div className={style['item-content']}>
        {this.getContainers(obj)}
      </div>
    </div>;
  }
}

class Chart extends Component{
  constructor(props) {
    super(props);
    this.state={
      chartObj:null,
      //timeRange:'year',
      week:props.getXAxisArr('week'),
      month:props.getXAxisArr('month'),
      sixMonth:props.getXAxisArr('sixMonth'),
      year:props.getXAxisArr('year')
    };
    this.drawChart = this.drawChart.bind(this);
    this.timeSwitch = this.timeSwitch.bind(this);
  }
  drawChart(){
    const {index,data,getXAxisArr,type,endDate,len} = this.props;
    const xAxis = getXAxisArr(type);
    const id = endDate?'chart'+endDate+index:'chart'+index;
    let series = [],names=[],inx=-1;
    let myChart = echarts.init(document.getElementById(id) ,null, {renderer: 'svg'});
    let xAxisArr = [...xAxis];
    const strNum = type=='week'?13:10;
    const interval = {
      week:23,
      month:4,
      sixMonth:9,
      year:60
    };
    data&&data.map((it,j)=>{
      let values=new Array();
      let name='';
      it&&it.creatTime.map((x,i)=>{
        inx=xAxis.findIndex((a)=>{
          name=x.substr(0,strNum);
          return a.substr(0,strNum)==name;
        });     //日期对应横坐标的位置
        if(inx!=-1){
          if(type=='week'){
            xAxisArr[inx] = x;
          }
          values[inx] = it.indexValue[i];       //值对应横坐标的位置
        }
      });
      names.push(it.itemName);
      series.push({
        name: it.itemName,
        type: 'line',
        data: values,
        showAllSymbol:true,
        symbol:'image://'+require('@common/images/'+((len+j)%8+1)+'.png'),//config.chartSymbols[(len+j)%8],
        symbolSize:10,
        itemStyle:{
          color:config.chartColors[(len+j)%8]
        }
      });
    });
    // 指定图表的配置项和数据
    var option = {
      tooltip: {
        trigger: 'axis',
        textStyle:{
          fontSize:12
        }
      },
      legend: {
        show:false
        /*data:names,
        padding:0,
        itemHeight:16,*/
      },
      grid:{
        top:40
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: xAxisArr,
        splitLine:{
          show:true
        },
        axisPointer:{
          //show:false
        },
        axisTick:{
          show:false,
          interval:interval[type]
        },
        axisLabel:{
          show:true,
          showMaxLabel:true,
          interval:interval[type],
          rotate:65,
          fontSize:10,
          formatter: function(value,index){
            return value.substr(0,13);
          }
        }
      },
      yAxis: {
        type: 'value',
        axisTick:{
          show:false
        },
        axisLabel:{
          show:true,
          showMaxLabel:true
        }
      },
      series: series
    };

    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option);
  }
  timeSwitch(type){
    const {handleRangeChange,index} = this.props;

    handleRangeChange&&handleRangeChange(type,index);

    const that=this;
    setTimeout(()=>{
      that.drawChart();
    },300);

  }
  componentDidMount(){
    this.drawChart();
  }
  render(){
    const {type,index,endDate} = this.props;
    return <div className={style['cont']}>
              <div className={style['time-range']}>
                <span className={type=='year'?style['range']+" "+style['on']:style['range']} onClick={()=>this.timeSwitch("year")}>近一年</span>
                <span className={type=='sixMonth'?style['range']+" "+style['on']:style['range']} onClick={()=>this.timeSwitch("sixMonth")}>近六个月</span>
                <span className={type=='month'?style['range']+" "+style['on']:style['range']} onClick={()=>this.timeSwitch("month")}>近一个月</span>
                <span className={type=='week'?style['range']+" "+style['on']:style['range']} onClick={()=>this.timeSwitch("week")}>近一周</span>
              </div>
              <div className={style["chart-box"]} id={endDate?'chart'+endDate+index:'chart'+index}></div>
            </div>;
  }
}

export default ChartItem;