import React from 'react';
import PropTypes from 'prop-types';
import { plumbNodeConnect, placement } from 'amos-jsplumb';
import { Popover } 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 classNames from 'classnames';
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 CustomNode
 * @extends {DefaultNode}
 */
@plumbNodeConnect({
  className: 'custom-ele',
  targetParams: {
    allowLoopback: false,
    anchor: Anchors.TopCenter,
    dropOptions: { hoverClass: 'drag-hover' },
    isTarget: true
  },
  sourceParams: {
    allowLoopback: false,
    anchor: Anchors.Continuous,
    isTarget: false,
    dropOptions: { hoverClass: 'drag-hover' }
  },
  endPointParams: [
    {
      params: sourceEndPoint,
      referenceParams: {
        anchor: Anchors.TopCenter
      }
    }
  ]
})
class CustomNode 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: isALarm });
      }
    });
  }

  componentWillReceiveProps(nextProps) {
    // console.log('nextProps:');
    // console.log(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;
            data.time = realTimeData.time;
            flag = true;
          }
        });
        if (!flag) {
          dataList.push(realTimeData);
        }
      }
      this.setState({
        dataList
      });
    }
  }

  clickNode = (e, id) => {
    window.topoNodefocus = true;
    //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;
  }

  render() {
    let { config } = this.props;
    let dataList = this.state.dataList;
    let name;
    let srcImgUrl;
    let id;
    let alrmContent = this.getAlarmImg();
    if (config !== undefined && config.data !== undefined) {
      let data = config.data;
      let displayImgUrl = data.viewPath;
      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 (

      <Popover overlayClassName="custom-node-popover" placement="right" title={'实时监测数据'} content={<DeviceProNode dataList={dataList} />}>

        <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>
            {/*<p>{data ? stringUtil(deviceCategoryEnum, parseInt(data.type)) : ''}</p>*/}
          </div>
          <div className='ele-node-action'>
            <div className="action-extra-item">
              <ActionItem
                icon="delete"
                onClick={(e) => this.remove(e, { id })}
                tip="点击删除元素节点"
              />
            </div>
          </div>
        </div>
      </Popover>

    );
  }
}

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

export default CustomNode;
