import React from 'react';
import PropTypes from 'prop-types';
import { placement, plumbNodeConnect } from 'amos-jsplumb';
import { Popover, Row, Tooltip } from 'amos-antd';
import { browserHistory } from 'amos-react-router';
import Icon from 'amos-icon';
import { OltSerUrl } from '../../../../consts/urlConsts';
import { AmosFetch } from '../../../../utils/processor';
import { PubSub } from 'ray-eventpool';
import dt2react from 'dt2react';
import { TOPO_ELE_DEL_TOPIC,TOPO_SHOW_PROPERTY_TOPIC,TOPO_ENABLE_CLICK_TOPIC } from './../modelConf/stageConst';
import { sourceEndPoint, targetEndpoint } from './../modelConf/nodeConf';
import DeviceProNode from './DeviceProNode';
import { deviceCategoryEnum } from  './../../../deviceManage/common/DeviceEnum';
import { stringUtil } from './../../../deviceManage/common/DeviceLang';
import ActionItem from './../../../ruleDesign/ruleStatge/extra/ActionItem';

const keyDelete = 46;
const { Anchors } = placement;

/**
 * 自定义节点样式
 *
 * @class NingHuaNode
 */
@plumbNodeConnect({
  className: 'custom-ele',
  targetParams: {
    allowLoopback: false,
    anchor: Anchors.TopCenter,
    dropOptions: { hoverClass: 'drag-hover' },
    isTarget: true
  },
  // sourceParams: {
  //   allowLoopback: false,
  //   anchor: Anchors.BottomCenter,
  //   isTarget: false,
  //   dropOptions: { hoverClass: 'drag-hover' }
  // },
  endPointParams: [
    {
      params: sourceEndPoint,
      referenceParams: {
        anchor: Anchors.TopCenter
      }
    }
  ]
})
class NingHuaNode extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dataList: [],
      isWarning: false
    };
  }
  componentWillMount(){
    let { config } = this.props;
    let url = `${OltSerUrl.getRealDataByDeviceId}/${config.equipmentId}`;
    //获取接口通讯方式
    AmosFetch.get(url).then(res => {
      if (res.ok) {
        return res.json();
      }
      else
      {
        throw new Error('从服务端获取数据失败！');
      }
    }).then((data)=>{
      if (data.result === 'SUCCESS'){
        let isALarm = data.dataList.isWarning;
        if (isALarm) {
          this.alarmLevel = data.dataList.maxLevel;
        }
        this.setState({ dataList: data.dataList.realTimeMetricDataVoList,isWarning: data.dataList.isWarning });
      }
    });
  }

  /*
  componentDidMount() {
    const { config, initNode } = this.props;

    const initConfig = {
      endPointParams: [
        {
          element: this.container,
          params: sourceEndPoint,
          referenceParams: {
            anchor: Anchors.Continuous,
            uuid: `${config.id}`
          }
        }
      ],
      makeTargetParams: {
        allowLoopback: false,
        anchor: Anchors.TopCenter,
        dropOptions: { hoverClass: 'drag-hover' },
        isTarget: true
      },
      makeSourceParams: {
        filter: '.test',
        allowLoopback: false,
        anchor: Anchors.BottomCenter,
        isTarget: false,
        // connectorStyle: { stroke: 'red', strokeWidth: 2, outlineStroke: 'red', outlineWidth: 20 },
        // connectionType: 'basic',
        // anchor: allAroundAnchor,
        dropOptions: { hoverClass: 'drag-hover' }
      },
      nodeId: config.id
    };
    initNode(initConfig);
  }
*/
  componentWillReceiveProps(nextProps){
    if (nextProps.config && nextProps.config.realTimeData){
      let realTimeData = nextProps.config.realTimeData;
      let dataList = this.state.dataList;
      if (dataList.length === 0 ){
        dataList.push(realTimeData);
      } else {
        let flag = false;
        dataList.map((data)=>{
          if (data.cpblId === realTimeData.cpblId){
            data.metricDataMap = realTimeData.metricDataMap;
            flag = true;
          }
        });
        if (!flag){
          dataList.push(realTimeData);
        }
      }
      this.setState({
        dataList
      });
    }
  }

  clickNode = (e,id) => {
    //this.container.focus();
    this.singleClickTrigger({ e,id });
  }

  showNodeProperty = (e,id) => {
    //this.container.focus();
    this.dbClickTrigger({ e,id });
  }

  // hoverAction = (e) => {
  //   console.log('1234');
  //   let currentNode = this.bottomEndpointRef;
  //   dt2react.addStyle(currentNode,'visibility','visible');
  // }

  // leaveAction = (e) => {
  //   console.log('1234');
  //   let currentNode = this.bottomEndpointRef;
  //   dt2react.addStyle(currentNode,'visibility','hidden');
  // }

  gotoAlarm = () =>{
    let { isWarning } = this.state;
    if (isWarning === true){
      browserHistory.push(`/main/monitor/alarmManage/recentAlarm?param=${this.props.config.equipmentId}`);
    }
  }

  dbClickTrigger = ({ id }) => {
    PubSub.publish(TOPO_SHOW_PROPERTY_TOPIC.trigger, {
      id
    });
  }

  singleClickTrigger = ({ id }) => {
    PubSub.publish(TOPO_ENABLE_CLICK_TOPIC.trigger, {
      id
    });
  }

  keyboardTrigger = ({ id , e }) => {
    if (e && e.keyCode === keyDelete) { // 按 delete
      PubSub.publish(TOPO_ELE_DEL_TOPIC.trigger, {
        id
      });
    }
  }

  remove = (e, { id }) => {
    PubSub.publish(TOPO_ELE_DEL_TOPIC.trigger, {
      id
    });
  }

  getAlarmImg = () => {
    let { isWarning } = this.state;
    let alarmContent = [];
    if (isWarning === true) {
      this.lampStyle = 'twinkle-img-style';
      let alarmLevel = this.alarmLevel;
      if (alarmLevel === 1) {
        alarmContent.push(<img src={require('./../../../../assets/iot/topo/dot/red.png')} onClick={this.gotoAlarm} alt='' />);
      } else if (alarmLevel === 2) {
        alarmContent.push(<img src={require('./../../../../assets/iot/topo/dot/orange.png')} onClick={this.gotoAlarm} alt='' />);
      } else if (alarmLevel === 3) {
        alarmContent.push(<img src={require('./../../../../assets/iot/topo/dot/yellow.png')} onClick={this.gotoAlarm} alt='' />);
      }
    } else {
      this.lampStyle = 'img-style';
      // this.lampStyle = 'twinkle-img-style';
      alarmContent.push(<img src={require('./../../../../assets/iot/topo/dot/green.png')} onClick={this.gotoAlarm} alt='' />);
    }
    return alarmContent;
  }

  getView = () =>{
    let view = [];
    let dataList = this.state.dataList;
    if (dataList === undefined) {
      return;
    }
    dataList.map((data, i)=>{
      const key = `dpn-${i}`;
      // view.push(<Row key={key}><h3 className="node-popover-ability">{data.cpblName}</h3></Row>);
      if (data.metricDataMap && JSON.stringify(data.metricDataMap) !== '{}'){
        let obj = data.metricDataMap;
        for (let i in obj){
          console.log(i);
          let title = `${i}：${obj[i]}`;
          view.push(<div title={title} className={`quota-${key}`} >{title}</div>);
        }
      } else {
        view.push(<div className={`quota-${key}`} >无数据</div>);
      }
    });
    return view;
  }

  render() {
    let { config } = this.props;
    let dataList = this.state.dataList;
    let alrmColor;
    let name;
    let srcImgUrl;
    let id;
    let alrmContent = this.getAlarmImg();
    if (config !== undefined && config.data !== undefined)
    {
      let data = config.data;
      let displayImgUrl = data.viewPath;
      let { isWarning } = this.state;
      alrmColor = { color: 'green' };
      if (isWarning === true) {
        alrmColor = { color: 'red' };
      }
      name = config.label === undefined ? data.name : config.label;
      srcImgUrl = displayImgUrl === '' || displayImgUrl === null ? `${OltSerUrl.fetchDeviceImg}/default.png` : `${OltSerUrl.fetchDeviceImg}/${displayImgUrl}`;
      id = config.id;
    }
    let lampStyle = this.lampStyle;
    return (

      <div
        className="node-content-wrapper"
        onClick={(e)=>this.clickNode(e,id)}
        // onDoubleClick={(e)=>this.showNodeProperty(e,id)}
        onKeyDown={(e)=>this.keyboardTrigger({ e, id })}
        title={name}
        //onMouseOver={this.hoverAction}
        //onMouseOut={this.leaveAction}
      >

        <div className='custom-node-img'>
          <img src={srcImgUrl} alt='device' />
        </div>
        <div className='text-info'>
          <div className={lampStyle}>
            {alrmContent}
          </div>
          <p className='text-style'>{name}</p>
          <div className='quota-data'>
            {
              this.getView()
            }
          </div>
        </div>
        <div className='ele-node-action'>
          <div className="action-extra-item">
            <ActionItem
              icon="delete"
              onClick={(e) => this.remove(e, { id })}
              tip="点击删除元素节点"
            />
          </div>
        </div>
      </div>

    );
  }
}

NingHuaNode.propTypes = {
  config: PropTypes.object
};

export default NingHuaNode;
