import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Connect, Modal } from 'amos-framework';
// import AmosWebSocket from 'amos-websocket';
import * as endConf from 'amos-processor/lib/config/endconf';

import { MapChart } from 'amos-viz/lib/echarts';
import {fetchJsonAction} from './../../../services/3dService';
import { getTopoAisleListAction } from 'SERVICES/pamsServices';
import SysWsURL, { completeToken } from 'CONSTS/wsUrlConsts';
import AmosWebSocket from 'amos-websocket';
import { utils } from 'amos-tool';
// import mapChartData from './../../../_mock/indexMap';

const eventConnect = Connect.eventConnect;
const AmosConfig = endConf.AmosConfig;
const enableScreenSaver = AmosConfig.screenSaverConf.enable;
const delayTime = AmosConfig.screenSaverConf.delayTime;
const chartColor = ['#00A2FF','#19FF00','#959595','#FF8800','#FF0000','#02E3FC','#FFF948','#FFAA00'];

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

    this.state = {
      mapChartData: []
    };
    this.eventpool = {
      click: (...args) => {
        let pointData = args[0].data;
        let seriesType = args[0].seriesType;
        if (seriesType === 'lines') {
          this.props.mapLineClick(pointData);
          // window.localStorage.setItem('cityLine',JSON.stringify(pointData))

        }
      }
    };
  }

  componentDidMount() {
    this.getTopoAisleList();
		// fetchJsonAction('/src/_mock/chart/indexMap.json',(data) => {
		// 	this.state.mapChartData = data;
		// 	this.setState({
		// 		mapChartData: data || []
		// 	})
		// })
	}

  componentWillUnmount() {

  }

  /**
   * 处理后台返回的告警通道数据
   *
   * @memberof IndexChart
   */
  getTopoAisleList = () => {
    getTopoAisleListAction().then((result) => {
      fetchJsonAction('/src/_mock/chart/indexMap.json',(data) => {
        let temp;
        console.log(result);
        if (!utils.isEmpty(result) && utils.isArray(result)) {
          result.map(item =>{
            if (item.city === '西安'){
              const flag = item.data.some(e => {
                if (e.name === '异常') {
                  return true;
                }
              });
              if (!flag){
                temp = data;
              } else {
                item.data.map( itemA => {
                  if (itemA.name === '异常'){
                    if (itemA.data.length > 0) {
                      itemA.data.map( itemB => {
                        temp = this.isExist(data, '西安',itemA.data);
                      });
                    }
                  }
                });
              }
            }
          });
          this.setState({
            mapChartData: temp || []
          });
        }
      });
    });
  }

  /**
   * 重构数据
   */
  isExist = (data, city, itemData) => {
    let temp = [];
    data.map( item => {
      item.data.map( itemA => {
        if (item.city === city){
          if (itemA.name === '正常'){
            itemA.data.map( itemB => {
              const flag = itemData.some(e => {
                if (itemB[1].name === e[1].name) {
                  return true;
                }
              });
              !flag && temp.push(itemB);
            });
            itemA.data = temp;
          } else if (itemA.name === '故障'){
            itemA.data = itemData;
          }
        }
      });
    });
    return data;
  }


  convertData = data => {
    let res = [];
    for (let i = 0; i < data.length; i++) {
			let dataItem = data[i];
			let fromCoord = dataItem[0].position;
			let toCoord = dataItem[1].position;
			if (fromCoord && toCoord) {
				res.push({
					coords:[
						fromCoord,toCoord
					],
					citys: [dataItem[0].name,dataItem[1].name]
				})
			}
    }
    return res;
  };
  getSeries = data => {
    let series = [];
    for (let i = 0; i < data.length; i++){
      let cityData = data[i].data;
      for (let j = 0; j < cityData.length; j ++) {
        // console.log(cityData[j].name)
        let seriesItem = {
          name: cityData[j].name,
          // name: cityData[j].data.length>0?cityData[j].data[1].name:'',
          type: 'lines',
          zlevel: 2,
          lineStyle: {
						normal: {
							// color:  '#1AFF00',
							color:  chartColor[j],
							width: i === 0?3:1,
							opacity: 0.8,
							curveness: 0.2
						}
          },
          data: this.convertData(cityData[j].data||[])
        };
        let cityPoint = {
					// 目的地标记
					// name: cityData[j].name,
					type: 'effectScatter',
					coordinateSystem: 'geo',
					zlevel: 2,
					rippleEffect: {
							brushType: 'stroke',
							period: 6
					},
					label: {
							normal: {
									show: true,
									position: 'right',
                  formatter: '{b}',
                  color: '#000'
							}
					},
					// symbolSize: function(val) {
					//     return val[2] / 8;
					// },
					symbolSize: 10,
					itemStyle: {
							normal: {
									color: '#1AFF00'
							}
					},
					data: (cityData[j].data||[]).map(function(dataItem) {
						return {
								name: dataItem[1].name,
								value: dataItem[1].position.concat([dataItem[1].value])
						};
          })

        }
        series.push(seriesItem);
        series.push(cityPoint);
      }

    }
    return series;
  }

    /**
   * webSocket接收通道状态数据
   */
  aislePamsHandleData = (data) => {
    let result = data.pams;
    fetchJsonAction('/src/_mock/chart/indexMap.json',(data) => {
      let temp;
      if (!utils.isEmpty(result) && utils.isArray(result)) {
        result.map(item =>{
          if (item.city === '西安'){
            const flag = item.data.some(e => {
              if (e.name === '异常') {
                return true;
              }
            });
            if (!flag){
              temp = data;
            } else {
              item.data.map( itemA => {
                if (itemA.name === '异常'){
                  if (itemA.data.length > 0) {
                    itemA.data.map( itemB => {
                      temp = this.isExist(data, '西安',itemA.data);
                    });
                  }
                }
              });
            }
          }
        });
        this.setState({
          mapChartData: temp || []
        });
      }
    });
  }

  render() {
    // console.log(mapChartData)
    let { mapChartData } = this.state
		let cityData = mapChartData
    let mapOption = {
      // backgroundColor: '#fff',
      title : {
          show: false,
          text: '迁徙图',
          subtext: '--',
          left: 'center',
          textStyle : {
              color: '#fff'
          }
      },
      tooltip : {
          trigger: 'item'
      },
      legend: {
          orient: 'vertical',
          top: 'top',
          left: 'left',
          data:['其他', '正常', '未运行', '告警', '故障', 'MBFE正常', 'MBFE告警', 'MBFE故障'],
          textStyle: {
              color: '#000'
          },
          // selectedMode: 'single'
      },
      geo: {
          map: '陕西',
          label: {
              emphasis: {
                  show: false
              }
          },
          center: [110.15, 36.07],
          roam: true,
          itemStyle: {
              normal: {
                  areaColor: '#E0F9FF',
                  borderColor: '#1C9AD2',
                  borderWidth: 2,
                  // shadowColor: '#151515',
                  // shadowBlur: 5
              },
              emphasis: {
                  areaColor: '#c7e9f1'
              }
          }
      },
      series: this.getSeries(cityData)

    };

    const aisleURL = completeToken(SysWsURL.aisleURI);

    return (
      <div className="chart-content" >
          <AmosWebSocket ref={node => this.aws = node} url={aisleURL} onMessage={this.aislePamsHandleData} reconnect debug />
          <MapChart option={mapOption} eventpool={this.eventpool} />
      </div>
    );
  }
}

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

export default IndexChart;
