import React, { Component } from 'react';
import PropTypes from 'prop-types';
import AmosWebSocket from 'amos-websocket';
import { Connect } from 'amos-framework';
import SvgToolkit from 'amos-viz/lib/svg/SvgToolkit';
import * as endConf from 'amos-processor/lib/config/endconf';
import sitMap from './datas/sit-map';
import info from './datas/info';
import text from './datas/text';
import SysWsURL, { completeToken } from './../../../../consts/wsUrlConsts';
import imgStatic from './../../../../consts/imgStatic';
import { eventTopics, rulesDataFactory } from './../../../3dview/consts';
import { getRegionAreaRpnAction } from './../../../../services/situationService';

const eventConnect = Connect.eventConnect;
const genVal = (val) =>  Math.round((Math.random() * 10 + val));
const colorEnum = { '0': 'initial', '1': 'one',  '2': 'two', '3': 'three', '4': 'fourfive', '5': 'fourfive' };
const AmosConfig = endConf.AmosConfig;
const riskSourceIdMap = AmosConfig.riskSourceIdMap;

/**
 * 态势图
 * @desciption created by af sinppets
 * @date create date 2019-06-03 14:16
 * @class SituationMap
 * @extends {Component}
 */
@eventConnect
export default class SituationMap extends Component {
  constructor(props) {
    super(props);
    this.state = {
      rpnData: {}
    };
    // 需要添加实时数据
    this.infoboxs = new Set();
  }

  componentDidMount() {
    // this.updateData();
    // 获取初始风险区域rpn值
    this.getRegionAreaRpn();
  }

  onItemClick = (event) => {
    console.log(event.target);
  }

  afterAddons = () => {
    const infos = (info.children || []).map((ifo, index) => {
      const { key, ...rest } = ifo;
      const newKey = rest.id || key || `ifo-${index}`;
      rest.d = rest.path;
      delete rest.path;
      return <path key={newKey} {...rest} />;
    });

    const texts = (text.texts || []).map((txt, index) => {
      const { innerText, key, ...rest } = txt;
      const newKey = rest.id || key || `text-${index}`;
      return <text key={newKey} {...rest}>{innerText}</text>;
    });

    return [
      ...infos,
      ...texts
    ];
  }

  beforeAddons = () => {
    return [
      <image key="bottom-bg" width="988" height="519" xlinkHref={imgStatic.biz.map} />
    ];
  }

  /**
   * datas 格式说明： { 'mapItem-1': 10, 'mapItem-2': 15, ... }
   */
  updateData = (datas) => {
    const infoValue = this.toolkitRef.getAllChild('.info-value');
    infoValue.forEach((iv, index) => {
      // const value = genVal(index);
      // // 直接修改值
      // iv.innerHTML = value;

      // 实时数据替换
      const memberOf = iv.dataset.member;
      if (datas[memberOf] !== undefined)
      {
        iv.innerHTML = datas[memberOf];
      }
    });
    // console.log(lineNode);
  }

  updateLevel = (levels) => {
    // { 'mapItem-1': 'initial|fourfive|three|two|one' }
    // 通过 id 找到一些列需要修改等级的节点 (data-member) 属性进行匹配
    // sitmap tip line dot
    (Object.keys(levels) || []).forEach(key => {
      // 区域，直接通过 id 进行修改
      levels[key] && this.toolkitRef.updateChild(key, { class: `situation-item face-${levels[key]}` });
    });
    // 线条、圆点
    const lineNode = this.toolkitRef.getAllChild('.line');
    lineNode.forEach((ln) => {
      const memberOf = ln.dataset.member;
      // ln.className = `line-${levels[memberOf]} line`;
      levels[memberOf] && ln.setAttribute('class', `line-${levels[memberOf]} line`);
    });
    const dotNode = this.toolkitRef.getAllChild('.dot');
    dotNode.forEach((dot) => {
      const memberOf = dot.dataset.member;
      // dot.className = `dot-${levels[memberOf]} line`;
      levels[memberOf] && dot.setAttribute('class', `dot-${levels[memberOf]} dot`);
    });

    // 顶部数据框
    const msgNode = this.toolkitRef.getAllChild('.msgblock');
    msgNode.forEach((msg) => {
      const memberOf = msg.dataset.member;
      // msg.className = `face-${levels[memberOf]} msgblock`;
      levels[memberOf] && msg.setAttribute('class', `face-${levels[memberOf]} msgblock`);
    });
    const edgeNode = this.toolkitRef.getAllChild('.edge');
    edgeNode.forEach((edge) => {
      const memberOf = edge.dataset.member;
      // edge.className = `edge-${levels[memberOf]} edge`;
      levels[memberOf] && edge.setAttribute('class', `edge-${levels[memberOf]} edge`);
    });
  }

  getLegend() {
    return (
      <div className='situation-map-legend' >
        <div className='situation-map-legend-item'>
          <div className='situation-map-legend-block' style={{ background: '#15653d' }} />
          <div>初始</div>
        </div>
        <div className='situation-map-legend-item'>
          <div className='situation-map-legend-block' style={{ background: '#0078ef' }} />
          <div>4/5级</div>
        </div>
        <div className='situation-map-legend-item'>
          <div className='situation-map-legend-block' style={{ background: '#ffcc2a' }} />
          <div>3级</div>
        </div>
        <div className='situation-map-legend-item'>
          <div className='situation-map-legend-block' style={{ background: '#ff5a20' }} />
          <div>2级</div>
        </div>
        <div className='situation-map-legend-item'>
          <div className='situation-map-legend-block' style={{ background: '#f42828' }} />
          <div>1级</div>
        </div>
      </div>
    );
  }

  getRegionAreaRpn() {
    getRegionAreaRpnAction().then(
      data => {
        let changeValue = {};
        let changeColor = {};
        for (let k in riskSourceIdMap) {
          changeValue[k] = 0;
          changeColor[k] = colorEnum[0];
          if (riskSourceIdMap[k] !== -1) {
            data.forEach(d => {
              if (riskSourceIdMap[k] === d.id) {
                changeValue[k] = d.rpni;
                changeColor[k] = colorEnum[d.level];
              }
            });
          }
        }
        this.updateData(changeValue);
        this.updateLevel(changeColor);
      },
      err => {
        console.log('get region area rpn error!');
      }
    );
  }

  handleData = data => {
    const { topic, content } = rulesDataFactory(data);
    if (topic === eventTopics.riskSituation_colour) {
      console.log('rule ws data of riskSituation_colour:', content);
      let changeColor = {};
      let bizObj = content.data.bizobj;
      // 获取风险点和态势图对应关系
      Object.keys(riskSourceIdMap).forEach(key => {
        if (riskSourceIdMap[key] === parseInt(bizObj.id)) {
          let mapId = key;
          changeColor[mapId] = colorEnum[content.data.colour];
          // return;
        }
      });
      this.updateLevel(changeColor);
    }
    if (topic === eventTopics.riskSituation_bubble) {
      console.log('rule ws data of riskSituation_bubble:', content);
      let changeValue = {};
      let bizObj = content.data.bizobj;
      // 获取风险点和态势图对应关系
      Object.keys(riskSourceIdMap).forEach(key => {
        if (riskSourceIdMap[key] === parseInt(bizObj.id)) {
          let mapId = key;
          changeValue[mapId] = parseInt(content.data.title);
          // return;
        }
      });
      this.updateData(changeValue);
    }
  };

  render() {
    const wsURL = completeToken(SysWsURL.rulews);
    return (
      <div style={{ position: 'relative' }}>
        <AmosWebSocket ref={node => this.aws = node} url={wsURL} onMessage={this.handleData} reconnect debug />
        <SvgToolkit
          ref={node => this.toolkitRef = node}
          className="situation-map"
          childClassName="situation-item"
          svgModule={sitMap}
          beforeAddons={this.beforeAddons}
          afterAddons={this.afterAddons}
          onClick={this.onItemClick}
        />
        {this.getLegend()}
      </div>
    );
  }
}

SituationMap.propTypes = {
  subscribe: PropTypes.func
};
