import React, { Component } from 'react';
import SvgToolkit from 'amos-viz/lib/svg/SvgToolkit';
import loadScripts from 'dt2react/lib/utils/loadScripts';
import * as endConf from 'amos-processor/lib/config/endconf';
import { UUID } from 'amos-tool';
import { ScreenCard } from './../../common';
import { message, eventConsts } from './../../eventConsts';
import {
  getRegionAreaRpnAction
} from './../api';

const AmosConfig = endConf.AmosConfig;
const prefix = AmosConfig.httpURI.fileServerURI || '/';
const colorEnum = { '0': 'initial', '1': 'one',  '2': 'two', '3': 'three', '4': 'fourfive', '5': 'fourfive' };

class RiskSituationChart extends Component {
  constructor(props) {
    super(props);
    this.state = {
      rpnData: {},
      riskName: {},
      info: {},
      sitMap: {},
      text: {},
      imgWidth: '',
      imgHeight: '',
      imgTranslate: '',
      backgroundImage: '',
      riskSourceIdMap: {},
      code: (message.getStorageData(eventConsts.STATION_CODE) || {}).message
    };
    // 需要添加实时数据
    this.infoboxs = new Set();
  }

  componentDidMount() {
    message.storageSubscribe(eventConsts.STATION_CODE, (data) => {
      this.setState({
        code: data.message || '',
        rpnData: {},
        riskName: {},
        info: {},
        sitMap: {},
        text: {},
        imgWidth: '',
        imgHeight: '',
        imgTranslate: '',
        backgroundImage: '',
        riskSourceIdMap: {}
      },this.initRpnChart);
    });
    this.initRpnChart();
  }

  initRpnChart = () => {
    console.log('发起请求');
    const { code } = this.state;
    const uuid = UUID.uuid('16');
    let scripts = [
      {
        key: `station-config${uuid}`,
        url: `${prefix}extra/RiskSituation/${code}/station.config.js`
      },
      {
        key: `svginfo-min${uuid}`,
        url: `${prefix}extra/RiskSituation/${code}/svginfo.min.js`
      }
    ];
    loadScripts.asyncLoadScripts(scripts, () => {
      const { riskSourceIdMap, imgWidth, imgHeight, imgTranslate, backgroundImage }  = window.riskDynamicChart || {};
      const { Info: info, SiteMap: sitMap, Text: text } = window.ISvgConf || {};
      this.setState({
        riskSourceIdMap, imgWidth, imgHeight, imgTranslate, backgroundImage, info, sitMap, text
      });
      this.getRegionAreaRpn();
    });
  }

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

  onItemMouseOver = (event) => {
    const { riskName = {} } = this.state;
    this.setState({ pointedChildName: riskName[event.target.id] });
  }

  afterAddons = () => {
    const { info, text } = this.state;
    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 = () => {
    const { imgWidth, imgHeight, backgroundImage, imgTranslate } = this.state;
    return [
      <image key="bottom-bg" width={imgWidth} height={imgHeight} xlinkHref={backgroundImage} transform={imgTranslate}/>
    ];
  }

  /**
   * 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级</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 = () => {
    const riskName = this.state.riskName;
    const { riskSourceIdMap, code } = this.state;
    getRegionAreaRpnAction(code).then(
      data => {
        let changeValue = {};
        let changeColor = {};
        // eslint-disable-next-line guard-for-in
        for (let k in riskSourceIdMap) {
          changeValue[k] = 0;
          changeColor[k] = colorEnum[0];
          if (riskSourceIdMap[k] !== -1) {
            data.forEach(d => {
              if (String(riskSourceIdMap[k]) === d.mrid) {
                changeValue[k] = d.rpni;
                changeColor[k] = colorEnum[d.riskLevelMrid];
                riskName[k] = d.name;
              }
            });
          }
        }
        this.updateData(changeValue);
        this.updateLevel(changeColor);
        this.setState(riskName);
      },
      err => {
        console.log('get region area rpn error!');
      }
    );
  }

  render() {
    const { pointedChildName, sitMap } = this.state;
    return (
      <ScreenCard title="换流站风险态势图">
        {
          sitMap && sitMap.viewBox &&
          <div className="ccs-risk-situation-left-sitmap">
            <SvgToolkit
              ref={node => this.toolkitRef = node}
              className="situation-map"
              childClassName="situation-item"
              svgModule={sitMap}
              enableTooltip
              tooltip={pointedChildName || ''}
              beforeAddons={this.beforeAddons}
              afterAddons={this.afterAddons}
              onClick={this.onItemClick}
              onMouseOver={this.onItemMouseOver}
            />
            {this.getLegend()}
          </div>
        }
      </ScreenCard>
    );
  }
}

export default RiskSituationChart;
