import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { AmosFetch } from 'UTILS/processor';
import { getToken } from 'UTILS/request';
import { OltSerUrl, realTimeMetricWsURL } from 'CONSTS/urlConsts';
import AmosWebSocket from 'amos-websocket';
import { Row, Col, Modal } from 'amos-antd';
import { Switch, message } from 'amos-framework';
import { tools, handlers, domTools } from 'amos-jsplumb';
import { PubSub } from 'ray-eventpool';
import dt2react from 'dt2react';
import Icon from 'amos-icon';
import TopoStagePlumb from './TopoStagePlumb';
import ConfigPanel from './ConfigPanel';
import DragableCard from './DragableCard';
import ChooseEquipmentPanel from './equipmentChoose/ChooseEquipmentPanel';
import ChooseBackgroundPanel from './uploadPicture/ChooseBackgroundPanel';
import { TOPO_ELE_DEL_TOPIC, TOPO_SHOW_PROPERTY_TOPIC, TOPO_ENABLE_CLICK_TOPIC } from './modelConf/stageConst';
import './topo.scss';
import { fetchTopoEquipmentAction, fetchTopoDeviceAction } from './../../../services/deviceService';
import UploadSinglePicModal from './uploadPicture/UploadSinglePicModal';
import TopoConfigPanel from './topoconfig/TopoConfigPanel';

//拓扑图事件
const eventListeners = {
  // click: handlers.onConnectoinClick,
  connection: handlers.onConnectionEventHandler,
  endpointClick: handlers.onEndPointClick
};

const keyDelete = 46;

/**
 *
 * 拓扑图
 * @class TopoContent
 * @extends {Component}
 */
class TopoContent extends Component {



  constructor(props) {
    super(props);
    this.addConnections = [];
    this.currentImgUrl = this.props.imgName;
    this.currentPercent = this.props.currentNode.imgOpacity;
    this.currentImgLayout = this.props.currentNode.imgLayout;
    this.state = {
      communityOptions: [], //下拉框内容
      equiptemplateIndustryOptions: [], //设备所属行业数据
      daviceList: [], //设备集合
      useList: [],
      dragType: 'custom', //当前视图组件的默认类型(只有自定义一种)
      connections: [], //当前视图组件所有连线
      nodes: [], //当前视图组件所有节点
      zoom: 1, //默认缩放级别
      viewLocation: {}, //前端视图组件中设备的位置，用以保存时传到后台
      finalCriterias: [], //过滤条件
      dragData: {}, //从设备池拖出的对象
      checked: this.props.currentNode.enableMonitor,
      hiddenProperty: true, //标识为，控制右侧属性面板的数据显示/隐藏
      visibility: '0', //标识为，显示公共设备还是私有设备 '0'：公共 ，'1': 私有
      destroy: false, //是否刷新
      isNodeSelected: false, //是否选中了设备
      currentDeviceConfig: {}, //选中的设备（包括所有配置信息）
      configPanelWith: 'calc(100% - 300px)', //视图区宽度
      devicePanelStyle: 'topo-content-stage', //main panel style
      expandIconRight: '0' //配置界面耳朵样式
    };
    const token = getToken();
    this.websocketUrl = `${realTimeMetricWsURL}equipment-metric.ws?token=${token}`;
  }

  componentWillMount() {
    //获取接口通讯方式
    AmosFetch.get(OltSerUrl.communityProtocol)
      .then(res => {
        if (res.ok) {
          return res.json();
        } else {
          throw new Error('从服务端获取数据失败！');
        }
      })
      .then(data => {
        if (data.result === 'SUCCESS') {
          let communityDataList = [];
          data
            ? data.dataList.map(e => {
              communityDataList.push({ value: e.id, label: e.name, selected: false, style: 'all-filter-btn' });
            })
            : [];
          this.setState({ communityOptions: communityDataList });
        }
      });

    //获取行业
    AmosFetch.get(OltSerUrl.equiptemplateIndustry)
      .then(res => {
        if (res.ok) {
          return res.json();
        } else {
          throw new Error('从服务端获取数据失败！');
        }
      })
      .then(data => {
        if (data.result === 'SUCCESS') {
          let equiptemplateIndustryDataList = [];
          data
            ? data.dataList.map(e => {
              equiptemplateIndustryDataList.push({ value: e.id, label: e.name, selected: false, style: 'all-filter-btn' });
            })
            : [];
          this.setState({ equiptemplateIndustryOptions: equiptemplateIndustryDataList });
        }
      });
  }

  componentDidMount() {
    let { subviewId } = this.props;
    this.handleCriterias();
    this.getOffset();
    window.addEventListener('resize', this.onWindowResize);
    this.getSubgraphData(subviewId);
    this.chooseBackground({});

    // 删除元素
    this.pubsub_eledel = PubSub.subscribe(TOPO_ELE_DEL_TOPIC.eleDel, (topic, { id }) => {
      if (this.nodeId === id) {
        this.questdeleteNode(id);
      }
    });

    // 显示右侧面板
    this.pubsub_eleshow = PubSub.subscribe(TOPO_SHOW_PROPERTY_TOPIC.eleShow, (topic, { id }) => {
      this.showProperty(id);
    });

    // 显示右侧面板
    this.pubsub_eleSelect = PubSub.subscribe(TOPO_ENABLE_CLICK_TOPIC.eleShow, (topic, { id }) => {
      this.nodeId = id;
      this.showProperty(id);
    });
  }

  componentWillReceiveProps(nextProps) {
    let { subviewId, imgName } = nextProps;
    //切换后
    this.jsPlumbInstance.reset();
    this.setState({ destroy: true, hiddenProperty: true });
    this.getSubgraphData(subviewId);
    // this.send(subviewId);
    if (imgName !== this.props.imgName) {
      this.chooseBackground({ imgName });
    }
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.onWindowResize);
    PubSub.unsubscribe(this.pubsub_eleshow);
    PubSub.unsubscribe(this.pubsub_eledel);
    PubSub.unsubscribe(this.pubsub_eleSelect);
  }

  onWindowResize = e => {
    this.getOffset();
  };

  onSceneCreated = inst => {
    this.jsPlumbInstance = inst;
    this.jsPlumbInstance.bind('connection', p => {
      this.addConnections.push(p.connection);
      p.connection.bind('click', j => {
        this.selectedConnection = j;
        j.toggleType('selected');
      });
    });
  };

  onAddConnection = (connId, sourceId, targetId) => {
    const { connections } = this.state;

    const newConn = {
      id: connId,
      sourceId: parseInt(sourceId),
      targetId: parseInt(targetId)
    };

    let isExist = false;
    connections.map(conn => {
      if (conn.sourceId === parseInt(sourceId) && conn.targetId === parseInt(targetId)) {
        isExist = true;
      }
    });

    if (!isExist) {
      this.setState({
        connections: [...this.state.connections, newConn]
      });
    }
  };

  onRemoveConnection = (connectionId, sourceId) => {
    if (window.confirm(`Remove connection '${connectionId}'?`)) {
      if (typeof connectionId === 'number') {
        let url = `${OltSerUrl.deleteLinkById}/${connectionId}`;
        AmosFetch.del(url)
          .then(res => {
            if (res.ok) {
              return res.text();
            } else {
              throw new Error('从服务端获取数据失败！');
            }
          })
          .then(data => {
            //重新刷新数据
            this.setState({
              connections: this.state.connections.filter(connection => connection.id !== connectionId)
            });
          });
      }
    }
  }

  onRemoveNode = (nodeId) => {
    const { nodes } = this.state;
    const newNodes = nodes.filter(n => n.id !== nodeId);
    this.setState({
      nodes: newNodes
    });
  }

  deleteLink = e => {
    if (e && e.keyCode === keyDelete) {
      // 按 delete
      let selectedConn = this.selectedConnection;
      if (selectedConn === undefined) {
        return;
      }
      let { connections } = this.state;
      let newConnections = [];
      let selectedId;
      connections &&
        connections.map(c => {
          if (selectedConn.targetId === c.targetId && selectedConn.sourceId === c.sourceId) {
            selectedId = c.id;
          } else {
            newConnections.push(c);
          }
        });

      let url = `${OltSerUrl.deleteLinkById}/${selectedId}`;
      this.jsPlumbInstance.deleteConnection(selectedConn);
      if (selectedId !== undefined) {
        AmosFetch.del(url)
          .then(res => {
            if (res.ok) {
              return res.text();
            } else {
              throw new Error('从服务端获取数据失败！');
            }
          })
          .then(data => {
            //重新刷新数据
            this.setState({ connections: newConnections });
          });
      }
      this.selectedConnection = undefined;
    }
  };

  onPlumbClick = e => {
    // let conns = this.addConnections;ist.getConnections()
    // conns && conns.map(c => {
    //   console.log(c);
    //   c.toggleType('dotted');
    // });
  };

  //获取子图的节点和连线信息
  getSubgraphData = (subviewId, nodeId) => {
    let url = `${OltSerUrl.fetchSubgraphInfoById}/${subviewId}`;
    AmosFetch.get(url)
      .then(res => {
        if (res.ok) {
          return res.json();
        } else {
          throw new Error('从服务端获取数据失败！');
        }
      })
      .then(data => {
        if (data.result === 'SUCCESS') {
          let subgraphInfo = data.dataList;
          if (subgraphInfo === null) {
            this.setState({ connections: [], nodes: [] });
          } else {
            let connections = subgraphInfo.connections;
            let nodes = subgraphInfo.nodes;
            nodes.map(item => {
              item.config = JSON.parse(item.config);
              if (item.equipmentId !== undefined) {
                item.config.equipmentId = item.equipmentId;
              }
              // item.id = item.nodeId;
              if (item.config.id !== undefined) {
                [item.config.id, item.nodeId] = [item.nodeId, item.config.id];
              } else {
                item.config.id = item.nodeId;
              }
              // [item.id, item.nodeId] = [item.nodeId, item.id];
              // item.config.id = item.nodeId;
              //宁化特殊处理
              if (item.config.data && item.config.data.model === 'VFE') {
                item.config.nodeType = 'ninghua';
              }
            });
            //后台数据改回前端数据
            connections.map(conn => {
              let sourceNode = nodes.filter(i => i.nodeId === conn.sourceId)[0];
              let targetNode = nodes.filter(i => i.nodeId === conn.targetId)[0];

              conn.sourceId = sourceNode === undefined ? conn.sourceId : sourceNode.id;
              conn.targetId = targetNode === undefined ? conn.targetId : targetNode.id;
            });
            //清空connections
            // ist.getConnections().map((item)=>{
            //   ist.deleteConnection(item);
            // });
            //清空Endpoint
            // this.state.nodes.map((item) => {
            //   ist.deleteEndpoint(ist.getEndpoint(`${item.id}-custom-top`));
            //   ist.deleteEndpoint(ist.getEndpoint(`${item.id}-custom-bottom`));
            //   ist.deleteEndpoint(ist.getEndpoint(`${item.id}-giot-bottom`));
            // });
            this.setState({ connections, nodes, destroy: false });
            this.chooseBackground({});
          }
        }
      });
  };

  //设置绘图区位置
  getOffset = () => {
    let topoViewNode = this.topoView;
    let viewLocation = dt2react.getOffset(topoViewNode) || {};
    this.setState({ viewLocation });
  };

  // getPrivateDevice = () => {
  //   let { finalCriterias } = this.state;
  //   this.setState({
  //     visibility: '1'
  //   });
  //   this.handleCriterias(finalCriterias,'1');
  // }

  // getPublicDevice = () => {
  //   let { finalCriterias } = this.state;
  //   this.setState({
  //     visibility: '0'
  //   });
  //   this.handleCriterias(finalCriterias,'0');
  // }

  getNeeddata = param => {
    let nodes = this.state.nodes;
    console.log('nodes:');
    console.log(nodes);
    let flag = false;
    if (nodes.length !== 0) {
      nodes.map(data => {
        if (data.config.equipmentId === param.eqpId) {
          data.config.realTimeData = param;
          flag = true;
        }
      });
      if (flag) {
        this.setState({
          nodes
        });
      }
    }
    console.log(nodes);
  };
  //webSocket 接收消息
  handleData = param => {
    console.log('我应该是实时数据：');
    console.log(param);
    this.getNeeddata(param);
  };

  questdeleteNode = nodeId => {
    if (nodeId !== undefined) {
      let delfunc = this.confirmDeleteAction;
      Modal.confirm({
        title: '确认删除',
        content: '是否删除所选信息？',
        okText: '确定',
        cancelText: '取消',
        onOk() {
          delfunc(nodeId);
        },
        onCancel() {}
      });
    }
  };

  //确认删除
  confirmDeleteAction = nodeId => {
    //初始化组件
    this.setState({ hiddenProperty: true });
    //删除node
    let { connections, nodes } = this.state;
    let newNodes = [];
    nodes.map(item => {
      // if (item.config.id === nodeId) {
      if (item.nodeId === nodeId) {
        this.deleteNodeById(item.id, item.equipmentId);
      } else {
        newNodes.push(item);
      }
    });
    let newConnections = [];
    let connectionIds = [];
    connections.map(item => {
      if (item.sourceId !== nodeId && item.targetId !== nodeId) {
        newConnections.push(item);
      } else {
        if (item.id !== undefined) {
          connectionIds.push(item.id);
        } else {
          //不删后台
        }
      }
    });
    this.deleteConnectionById(connectionIds);
    this.setState({ connections: newConnections, nodes: newNodes });
  };

  //根据ID删除节点
  deleteNodeById = (id, eqpId) => {
    this.setState({ destroy: true });
    let url = `${OltSerUrl.deleteNodeById}/${id}`;
    AmosFetch.del(url)
      .then(res => {
        if (res.ok) {
          return res.text();
        } else {
          throw new Error('从服务端获取数据失败！');
        }
      })
      .then(data => {
        let { daviceList, useList } = this.state;
        let newUseList = [];
        useList.map(data => {
          if (data.id === eqpId) {
            daviceList.push(data);
          } else {
            newUseList.push(data);
          }
        });

        //重新刷新数据
        this.setState({ destroy: false, daviceList, useList: newUseList });
        let ist = this.jsPlumbInstance;
        this.state.nodes.map(item => {
          if (item.id === id) {
            ist.deleteEndpoint(ist.getEndpoint(`${item.id}`));
          }
        });
      });
  };

  //根据ID删除连线
  deleteConnectionById = ids => {
    if (ids.length === 0) {
      return;
    }
    let url = `${OltSerUrl.deleteConnectionById}/${ids}`;
    AmosFetch.del(url)
      .then(res => {
        if (res.ok) {
          return res.text();
        } else {
          throw new Error('从服务端获取数据失败！');
        }
      })
      .then(data => {
        //重新刷新数据
      });
  };

  handleCriterias = (searchParam = {}, visibility) => {
    searchParam.orgCode = this.props.orgCode;
    fetchTopoEquipmentAction(searchParam).then(data => {
      if (data !== null) {
        this.setState({ daviceList: data.noUseList, useList: data.useList });
      } else {
        this.setState({ daviceList: [], useList: [] });
      }
    });
  };

  startDrag = (e, dragType, dragData) => {
    this.setState({ dragType, dragData });
  };

  /**
   * 允许拖拽
   *
   * @memberof TopoContent
   */
  enableDrag = e => {
    e.preventDefault();
  };

  stopDrag = e => {
    let { viewLocation, dragType, dragData } = this.state;
    if (Object.keys(dragData).length === 0) {
      return;
    }
    let id = tools.uuid();
    const style = domTools.getNodeOffset(e);
    const generateNodeConfig = t => ({
      config: {
        id,
        label: dragData.name,
        type: t === 'giot' ? 'source' : 'both',
        nodeType: t,
        data: dragData,
        style
      }
    });

    let newNode = generateNodeConfig(dragType);
    this.nodeId = id;
    newNode.nodeId = id;
    let { daviceList, useList } = this.state;
    let eqbId = newNode.config.data.id;
    let newDaviceList = [];
    daviceList.map(data => {
      if (data.id === eqbId) {
        useList.push(data);
      } else {
        newDaviceList.push(data);
      }
    });
    this.setState({
      nodes: [...this.state.nodes, newNode],
      dragData: {},
      destroy: true,
      daviceList: newDaviceList,
      useList
    });

    //拖拽后立刻保存
    this.saveSubgraphData([...this.state.nodes, newNode]);
  };

  //显示属性面板
  showProperty = nodeId => {
    let { nodes } = this.state;
    this.nodeId = nodeId;
    nodes.map(item => {
      // if (item.config.id === nodeId || item.nodeId === nodeId) {
      if (item.nodeId === nodeId) {
        let equipmentId = item.equipmentId;
        fetchTopoDeviceAction(equipmentId).then(data => {
          this.changePanelWidth(true);
          this.setState({ currentDeviceConfig: data, isNodeSelected: true, expandIconRight: '300px' });
        });
      }
    });
  };

  /**
   * 根据设备生成界面
   *
   * @memberof TopoContent
   */
  generatePanelByDevice = choosePanel => {
    if (choosePanel !== undefined) {
      let style = dt2react.getOffset(choosePanel);
      let allStyle = dt2react.getOffset(this.topoView);
      if (style !== undefined && allStyle !== undefined) {
        let contentHeight = allStyle.height - 155;
        dt2react.addStyle(choosePanel, 'height', `${contentHeight}px`);
      }
    }

    let { daviceList } = this.state;
    let res = [];
    if (daviceList !== undefined) {
      daviceList.map(data => {
        res.push(<DragableCard cardData={data} key={data.id} startDrag={this.startDrag} />);
      });
    }
    return res;
  };

  //保存子图信息
  saveSubgraphData = newNodes => {
    let ist = this.jsPlumbInstance;
    let elementObj = ist.getManagedElements();
    let { nodes, connections } = this.state;
    nodes = newNodes === undefined || newNodes.length === undefined ? nodes : newNodes;
    let { subviewId, currentNode } = this.props;

    //更新node位置信息，一个node对应一个equipment
    // nodes.map(item => {
    //   if (elementObj[item.nodeId] !== undefined) {
    //     let location = { left: `${elementObj[item.config.id].el.offsetLeft}px`, top: `${elementObj[item.config.id].el.offsetTop}px` };
    //     item.config.style = location;
    //   }
    // });
    //前端数据改成后台数据
    nodes.map(item => {
      if (item.config.id !== undefined) {
        [item.config.id, item.nodeId] = [item.nodeId, item.config.id];
        // [item.id, item.nodeId] = [item.nodeId, item.id];
        //不保存性能数据
        item.config.realTimeData = undefined;
        // item.config = JSON.stringify(item.config);
      }
      item.config = JSON.stringify(item.config);
    });

    //前端数据改成后台数据
    connections.map(conn => {
      let sourceNode = nodes.filter(i => i.id === parseInt(conn.sourceId))[0];
      let targetNode = nodes.filter(i => i.id === parseInt(conn.targetId))[0];

      conn.sourceId = sourceNode === undefined ? conn.sourceId : sourceNode.nodeId;
      conn.targetId = targetNode === undefined ? conn.targetId : targetNode.nodeId;
      conn.id = 0;
    });

    let data = { id: subviewId, nodes, connections, orgCode: currentNode.orgId };
    AmosFetch.post(OltSerUrl.addSubgraphData, { data })
      .then(res => {
        if (res.ok) {
          return res.text();
        } else {
          throw new Error('从服务端获取数据失败！');
        }
      })
      .then(data => {
        let result = JSON.parse(data);
        let resultStatus = result.result;
        if (resultStatus === 'SUCCESS') {
          //隐性保存不提示
          if (newNodes === undefined || newNodes.length === undefined) {
            message.success('保存成功！');
          }
          //界面刷新
          // this.getTreeData();
          //后台数据改回前端数据
          this.getSubgraphData(subviewId);
        } else {
          message.danger('保存失败！');
        }
      });
  };

  //更新node对应的equipment配置信息
  updateNodeConfig = (nodeId, configJson) => {
    let { nodes } = this.state;
    nodes.map(item => {
      // if (item.config.id === nodeId) {
      if (item.nodeId === nodeId) {
        item.equipmentParam = JSON.stringify(configJson);
      }
    });
    this.saveSubgraphData();
  };

  //webSocket 发送消息
  send = () => {
    let subviewId = this.props.subviewId;
    const ws = this.aws.getWebSocket();
    let param = {
      subviewId
    };
    ws.send(JSON.stringify(param));
  };

  //隐藏属性页
  doHiddenProperty = e => {
    this.setState({ hiddenProperty: true });
  };

  exit = () => {
    this.props.updateView('1', this.props.currentNode);
  };

  //选择背景
  chooseBackground = ({ imgName, percent, layout }) => {
    let view = this.topoView;
    if (imgName === undefined || imgName === null || view === undefined || view === null) {
    } else {
      this.currentImgUrl = imgName;
    }
    let currentImgUrl = this.currentImgUrl;
    if (currentImgUrl.includes('.')) {
      //判断是图片还是颜色
      if (layout !== undefined) {
        this.currentImgLayout = layout;
      }
      let currentImgLayout = this.currentImgLayout;
      if (currentImgLayout === 1) {
        let bkStyle = `url("${OltSerUrl.fetchDeviceImg}/graph/${currentImgUrl}") no-repeat`;
        dt2react.addStyle(view, 'background', bkStyle);
        dt2react.addStyle(view, 'background-size', '100% 100%');
      } else if (currentImgLayout === 2) {
        let bkStyle = `url("${OltSerUrl.fetchDeviceImg}/graph/${currentImgUrl}")`;
        dt2react.addStyle(view, 'background', bkStyle);
      }
    } else {
      dt2react.addStyle(view, 'background', currentImgUrl);
    }
    //透明度
    if (percent !== undefined) {
      dt2react.addStyle(view, 'opacity', percent);
      this.currentPercent = percent;
    } else {
      dt2react.addStyle(view, 'opacity', this.currentPercent);
    }
  };

  oneOpenOrClose = checked => {
    let subviewId = this.props.subviewId;
    let url = `${OltSerUrl.oneOpenOrClose}/${subviewId}/${checked}`;
    AmosFetch.get(url)
      .then(res => {
        if (res.ok) {
          return res.json();
        } else {
          throw new Error('从服务端获取数据失败！');
        }
      })
      .then(data => {
        if (data.result === 'SUCCESS') {
          this.setState({ checked });
        }
      });
  };

  changePanelWidth = isShowDevice => {
    if (isShowDevice) {
      this.setState({ configPanelWith: 'calc(100% - 300px)', expandIconRight: '300px' });
    } else {
      this.setState({ configPanelWith: '100%', expandIconRight: '0' });
    }
  };

  changeLeftPanelWidth = isShowDevice => {
    if (isShowDevice) {
      this.setState({ devicePanelStyle: 'topo-content-stage' });
    } else {
      this.setState({ devicePanelStyle: 'topo-no-left-content-stage' });
    }
  };

  mapFocus = () => {
    let topoNodefocus = window.topoNodefocus;
    if (!topoNodefocus) {
      this.setState({ isNodeSelected: false });
    } else {
      window.topoNodefocus = false;
    }
  };

  onZoom = (zoom) => {
    this.setState({
      zoom
    });
  }

  onDropHandler = (id, left, top) => {
    const { nodes } = this.state;
    nodes.forEach(node => {
      if (node.id === id) {
        let location = { left, top };
        node.config.style = location;
      }
    });
    this.setState({
      nodes
    });
  }

  beforeDrop = (info) => {
    let ist = this.jsPlumbInstance;
    info.targetId = info.dropEndpoint.elementId;
    let connections = ist.getConnections({ source: info.sourceId, target: info.targetId });
    if (info.targetId === info.sourceId) {
      message.danger('不可以自己连接自己');
    } else {
      if (connections.length === 0) {  // 检察是否已经建立过连接
        this.setState({ info });
        return true;
      } else {
        message.danger('两个节点之间只能有一条连接');
      }
    }
  }

  render() {
    const {
      configPanelWith,
      communityOptions,
      zoom,
      nodes,
      connections,
      expandIconRight,
      equiptemplateIndustryOptions,
      destroy,
      isNodeSelected,
      currentDeviceConfig,
      devicePanelStyle
    } = this.state;
    const { subviewId, subviewName, currentNode, imgName } = this.props;

    const dataSource = {
      nodes,
      connections
    };

    const nodeProps = {
      onDrop: this.onDropHandler
    };

    const _eventListeners = {
      ...eventListeners,
      beforeDrop: this.beforeDrop
    };

    let nodeId = this.nodeId;
    let newNode = currentNode;
    newNode.title = subviewName;
    newNode.num = nodes.length - 1;
    let equipmentId;
    let cfgParamJson;

    if (nodes !== undefined) {
      nodes.map(item => {
        // if (item.config.id === nodeId || item.nodeId === nodeId) {
        if (item.nodeId === nodeId) {
          equipmentId = item.equipmentId;
          cfgParamJson = item.equipmentParam;
        }
      });
    }
    let currentConfig = nodeId && nodes.filter(i => i.config.id === nodeId);
    if (currentConfig && currentConfig.length === 1) {
      currentConfig = currentConfig[0].config;
    }
    return (
      <div className="topo-content">
        <div className="dispatch-mask" ref={node => this.dispatchMask = node}>
          <AmosWebSocket ref={node => this.aws = node} url={this.websocketUrl} onMessage={this.handleData} onOpen={this.send} reconnect debug />
        </div>
        <div className="topo-content-view" style={{ width: configPanelWith }}>
          <ChooseEquipmentPanel
            communityOptions={communityOptions}
            handleCriterias={this.handleCriterias}
            generatePanelByDevice={this.generatePanelByDevice}
            equiptemplateIndustryOptions={equiptemplateIndustryOptions}
            changeLeftPanelWidth={this.changeLeftPanelWidth}
          />
          <div className="topo-content-header">
            <label style={{ 'font-size': '15px' }}>●{subviewName}</label>
            <div className="edit-view-root">
              <div className="tree-header-extra-item-edit" onClick={this.exit} title="退出">
                <img src={require('./../../../assets/iot/topo/exit.png')} alt="" />
              </div>
            </div>
            <div className="save-view" onClick={this.saveSubgraphData} title="保存">
              <img src={require('./../../../assets/iot/topo/save.png')} alt="" />
            </div>
            <div className="start-stop-view">
              <Switch onLabel="启" offLabel="停" onOff={this.state.checked} onChange={checked => this.oneOpenOrClose(checked)} />
            </div>
          </div>
          <div style={{ height: '100%' }}>
            <div
              onDragOver={e => this.enableDrag(e)}
              onDrop={e => this.stopDrag(e)}
              ref={node => this.topoView = node}
              onKeyDown={this.deleteLink}
              className={devicePanelStyle}
              onFocus={this.mapFocus}
              tabIndex={'-1'}
            >
              <TopoStagePlumb
                eventListeners={_eventListeners}
                onPlumbClick={this.onPlumbClick}
                onSceneCreated={this.onSceneCreated}
                zoom={zoom}
                dataSource={dataSource}
                destroy={destroy}
                onAddConnection={this.onAddConnection}
                onRemoveConnection={this.onRemoveConnection}
                onRemoveNode={this.onRemoveNode}
                onZoom={this.onZoom}
                nodeProps={nodeProps}
              />
            </div>
          </div>
        </div>
        <TopoConfigPanel
          isNodeSelected={isNodeSelected}
          subviewInfo={newNode}
          currentDeviceConfig={currentDeviceConfig}
          config={currentConfig}
          equipmentId={equipmentId}
          nodeId={nodeId}
          getSubgraphData={this.getSubgraphData}
          showProperty={this.showProperty}
          chooseBackground={this.chooseBackground}
          changePanelWidth={this.changePanelWidth}
          expandIconRight={expandIconRight}
          {...this.props}
        />
      </div>
    );
  }
}

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

export default TopoContent;
