import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Icon from 'amos-icon';
import { PubSub } from 'ray-eventpool';
import { stopEvent } from 'amos-jsplumb';
import TopoHeader from './../header/TopoHeader';
import TopoStagePlumb from './TopoStagePlumb';
import { transferDropData, commonAddNode } from './addNode';
import TriggerEditor from './../../../common/editor/TriggerEditor';
import ConfigPanel from './../toporight/demofile/ConfigPanel';
import { DB_CLICK_ELE } from './../modelConf/stageConst';
import './topocontent.scss';

const testFunc = e => {
  console.log(e);
};

// 拓扑图事件
const eventListeners = {
  click: testFunc,
  connection: testFunc,
  endpointClick: testFunc
};
const extraSize = {
  top: 90,
  left: 350
};

/**
 *
 * 拓扑图
 * @class TopoContent
 * @extends {Component}
 */
class TopoContent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      hiddenProperty: true,
      showEditor: false,
      connections: [], // 当前视图组件所有连线
      nodes: [], // 当前视图组件所有节点
      zoom: 1, // 默认缩放级别
      resetCanvas: false // 标志位，控制jsplumb组件的重新初始化
    };
  }

  componentDidMount() {
    this.pubsub = PubSub.subscribe(DB_CLICK_ELE, (topic, { id, preStatus, nextStatus, config, parentConfig }) => {
      // this.setState({
      //   showEditor: true
      // });
      this.showProperty(config.label);
    });
  }

  onChange = ({ nodes, connections }) => {
    this.setState({ nodes, connections });
  };

  onIstCreated = inst => {
    this.jsPlumbInstance = inst;
  };

  /**
   * 拖拽结束事件
   * @memberOf RuleStage
   */
  handleDrop = event => {
    stopEvent(event);
    const x = event.clientX - extraSize.left;
    const y = event.clientY - extraSize.top;
    const data = event.dataTransfer.getData('FlowChartNode');
    const { nodeType, label } = transferDropData(data);
    this.doDropAddNode({ nodeType, label, x, y });
  };

  doDropAddNode = ({ nodeType: eleType, label, x, y }) => {
    const { nodes } = this.state;
    const position = {
      left: x,
      top: y
    };
    const result = commonAddNode({ eleType, labelValue: label, position });

    this.setState({
      catalogVisible: false,
      nodes: [...nodes, result]
    });
  };

  /**
   *
   * 这保证 handleDrop可以被调用
   * @memberOf RuleScene
   */
  handleDragOver = event => {
    stopEvent(event);
  };

  renderTopoHeaderExtra = () => {
    const extra = [
      <div key="zoom-in" className="topo-header-extra-item" onClick={this.zoomIn} title="放大">
        <Icon icon="zoom-in" />
      </div>,
      <div key="zoom-out" className="topo-header-extra-item" onClick={this.zoomOut} title="缩小">
        <Icon icon="zoom-out" />
      </div>,
      <div key="save" className="topo-header-extra-item" onClick={this.save} title="保存">
        <Icon icon="save" />
      </div>
    ];
    return extra;
  };

  test = () => {};

  // 显示属性面板
  showProperty = label => {
    this.deviceLabel = label;
    this.setState({ hiddenProperty: false });
    if (this.configPanelRef !== undefined) {
      this.configPanelRef.closeDeviceCapacityPanel();
    }
  };

  render() {
    const { zoom, nodes, connections, resetCanvas, showEditor, hiddenProperty } = this.state;
    let deviceLabel = this.deviceLabel;
    let config = {
      label: 'IG541气体灭火设备',
      type: 'custom',
      data: {
        id: 1000019,
        isDelete: false,
        createTime: null,
        updateTime: null,
        name: 'IG541气体灭火设备',
        model: 'IG-541',
        type: 1,
        img: 'default.png',
        descr: null,
        visibility: 0,
        userId: null,
        attributes: null,
        capabilities: null
      },
      style: { left: '570px', top: '152px' }
    };
    let cfgParamJson = { equip_10000022: '', cpbl_10000019_10000022: '15.0', cpbl_intfc_10000019_10000019: '1026' };
    let devPropertyContent = hiddenProperty ? (
      <div />
    ) : (
      <ConfigPanel
        updateNodeConfig={this.test}
        updateNodeName={this.test}
        config={config}
        equipmentId={23}
        nodeId="df0f9d2f-8e5a-44f5-a6f9-8ded3e1185aa"
        getSubgraphData={this.getSubgraphData}
        subviewId={24}
        cfgParamJson={cfgParamJson}
        deviceLabel={deviceLabel}
        ref={node => (this.configPanelRef = node)}
      />
    );
    return (
      <div className="topo-content-wrapper">
        <TopoHeader title="子图" extra={this.renderTopoHeaderExtra()} />
        <div
          onDragOver={this.handleDragOver}
          onDrop={this.handleDrop}
          ref={node => (this.topoView = node)}
          onClick={this.hiddenDevicePanel}
          className="kunshan-topo-content"
        >
          {!resetCanvas ? (
            <TopoStagePlumb
              eventListeners={eventListeners}
              onPlumbClick={this.onPlumbClick}
              onSceneCreated={this.onSceneCreated}
              onPlumbChange={this.onPlumbChange}
              zoom={zoom}
              nodes={nodes}
              connections={connections}
            />
          ) : null}
        </div>
        {devPropertyContent}
      </div>
    );
  }
}

TopoContent.propTypes = {
  subviewId: PropTypes.string,
  subviewName: PropTypes.string,
  currentNode: PropTypes.object,
  selectedKeys: PropTypes.array,
  editTreeData: PropTypes.func
};

export default TopoContent;
