import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { message } from 'amos-framework';
import dt2react from 'dt2react';
import AmosWebSocket from 'amos-websocket';
import TopologyComponent from './TopologyComponent';
import TreeComponent from './TreeComponent';
import { getTopoTreeAction,getTopographyAction,updateTopographyAction,getTopographyEventsAction } from './../../../services/pamsServices';
// import AmosGridTable from './../../bizview/common/tableComponent/table/AmosGridTable';
import AmosGridTable from './../../component/table/table/AmosGridTable';
import IndexChart from './indexChart';
import SysWsURL from './../../../consts/wsUrlConsts';

const checkListColumns = (self) => {
  return [
    {
      title: '节点机器',
      dataIndex: 'nodeMachine',
      key: 'nodeMachine',
      width: '30%'
    },{
      title: '事件内容',
      dataIndex: 'eventContent',
      key: 'eventContent',
      width: '50%'
    },{
      title: '级别',
      dataIndex: 'eventLevel',
      key: 'eventLevel'
    }
  ];
};

//偏移
const offsetHeight = 110;
const defaultHeight = 450;

class Pams extends Component {

  constructor(props) {
    super(props);
    this.state = {
      treeData: [
        {
          name: '',
          id: '1',
          children: []
        }
      ], //树数据
      autoExpandParent: true,
      selectedKeys: [],
      expandedKeys: [],
      topologyData: {}, //拓扑图数据
      tableData: [],
      isTreeDisplay: true,
      isTableDisplay: true,
      activeView: 'left',
      pHeight: 0,
      cityLine: ''
    };
    this.updateTopologyData = {};
    this.mapView = true;
  }

  componentDidMount() {
    this.initData();
    if (this.props.location.state) {
      this.state.cityLine = JSON.parse(this.props.location.state.cityLine);
      this.viewlineItem();
    }

  }
  componentWillReceiveProps(nextProps) {
    if (nextProps.location.state) {
      this.state.cityLine = JSON.parse(nextProps.location.state.cityLine);
      this.viewlineItem();
    }

  }
  //点击地图线操作
  viewlineItem = () => {
    let { treeData,selectedKeys,cityLine } = this.state;
    if (cityLine) {
      let currentLine = `${cityLine.citys[0]}-${cityLine.citys[1]}`;
      for ( let i = 0; i < treeData.length; i++ ) {
        let dataItem = treeData[i].children;
        for (let j = 0; j < dataItem.length; j++ ) {
          if (dataItem[j].name === currentLine) {
            // selectedKeys.push(dataItem[j].id)
            selectedKeys = [dataItem[j].id];
            console.log(selectedKeys);
            if (selectedKeys[0]) {
              this.initTopologyData(selectedKeys[0]);
            }
            this.setState({
              selectedKeys
            });
          }
        }
      }
    }

  }
  componentWillUnmount() {
    window.localStorage.removeItem('cityLine');
  }
  getPanelHeight = () => {
    let tableNode = this.tableNode;
    let tableLocation = dt2react.getOffset(tableNode) || {};
    return tableLocation !== undefined ? tableLocation.height - offsetHeight : defaultHeight;
  };

  // 数据初始化
  initData = () => {
    let expandedKeysData = [];
    getTopoTreeAction().then(data => {
      data.map(item => {
        expandedKeysData.push(item.id);
      });
      this.initTopologyData(data[0].id);
      this.initTopologyEventData();
      this.setState({
        treeData: data,
        selectedKeys: [data[0].id],
        expandedKeys: expandedKeysData,
        pHeight: this.getPanelHeight()
      }, () => {
        this.viewlineItem();
      });
    });
  }

  // 拓扑图数据初始化
  initTopologyData = (id,value = '') => {
    getTopographyAction(id).then(data => {
      if (value === 'refresh') {
        message.success('拓扑图刷新成功!');
      }
      this.setState({
        topologyData: data
      });
    });
  }

  // 拓扑图事件数据初始化
  initTopologyEventData = () => {
    getTopographyEventsAction().then(data => {
      this.setState({
        tableData: data
      });
    });
  }


  // 树选择
  onSelect = (selectedKeys,e) => {
    if (selectedKeys.length) {
      window.localStorage.removeItem('cityLine');
      this.initTopologyData(selectedKeys[0]);
      this.setState({
        selectedKeys
      });
    }
  }
  mapLineClick = (data) => {
    window.localStorage.removeItem('cityLine');
    this.state.cityLine = data;
    this.viewlineItem();

  }

  // 树展开
  onExpand = (expandedKeys) => {
    this.setState({
      expandedKeys,
      autoExpandParent: false
    });
  };

  // 选择节点连线
  nodeSelectionLinkChanged = (node) => {
    if (node.isSelected) {
      // 点击选择节点
      if (node.data.clickable) {
        this.initTopologyData(node.data.treeNodeId);
        this.setState({
          selectedKeys: [node.data.treeNodeId]
        });
      }
      // console.log(node.data);
    }
  }

  // 节点数据改变
  nodeChange = (e) => {
    // console.log(e.model.toJson());
    this.updateTopologyData = JSON.parse(e.model.toJson());
  }

  // 保存节点数据
  saveTopologyData = () => {
    const { selectedKeys } = this.state;
    const { nodeDataArray,linkDataArray } = this.updateTopologyData;
    const params = {
      treeid: selectedKeys[0],
      nodeData: nodeDataArray,
      linkData: linkDataArray
    };
    updateTopographyAction(params).then(data => {
      message.success('拓扑图保存成功!');
    });
  }

  // 刷新节点
  refreshTopologyData = () => {
    const { selectedKeys } = this.state;
    this.initTopologyData(selectedKeys[0], 'refresh');
  }

  // 视图切换
  toggleView = (value) => {
    if (value === 'left') {
      this.setState({
        isTreeDisplay: true,
        isTableDisplay: true,
        activeView: 'left'
      });
    } else {
      this.setState({
        isTreeDisplay: false,
        isTableDisplay: false,
        activeView: 'detail'
      });
    }
  }

  //webSocket 接收消息
  handleData = (data) => {
    let { selectedKeys } = this.state;
    if (selectedKeys[0] === data){
      this.onSelect([data]);
    }
  }

  render() {
    const { treeData,selectedKeys,expandedKeys,isTreeDisplay } = this.state;
    if (treeData[0] && treeData[0].children.length < 1) {
      return null;
    }
    if (treeData && treeData.length > 0 && selectedKeys && selectedKeys.length > 0) {
      if (treeData[0].id != selectedKeys[0]){
        this.mapView = false;
      } else {
        this.mapView = true;
      }
    }
    const { topologyData } = this.state;
    const { tableData,isTableDisplay,pHeight,activeView } = this.state;
    console.log(topologyData);
    return (
      <div className="pams-wrapper">
        <AmosWebSocket
          ref={node => this.aws = node}
          url={SysWsURL.pamsTopoURI}
          onMessage={this.handleData}
          reconnect
          debug
        />
        <div className="pams-header">
          <div className="pams-view">
            <div className={classnames('left-view', { 'left-active-view': activeView === 'left' })}>
              <img src="/src/assets/bizView/netTopology/left-view.png" alt="左视图"  onClick={() => this.toggleView('left')} />
            </div>
            <div className={classnames('detail-view', { 'detail-active-view': activeView === 'detail' })}>
              <img src="/src/assets/bizView/netTopology/detail-view.png" alt="详细视图"  onClick={() => this.toggleView('detail')} />
            </div>
          </div>
          <div className="pams-data">
            <div className="pams-topo-save">
              <img src="/src/assets/bizView/netTopology/save.png" alt="保存"  onClick={this.saveTopologyData} />
            </div>
            <div className="pams-topo-refresh">
              <img src="/src/assets/bizView/netTopology/refresh.png" alt="刷新"  onClick={this.refreshTopologyData} />
            </div>
          </div>
        </div>
        <div className="pams-content">
          {<div className={classnames({ 'left-content': isTreeDisplay,'left-content-close': !isTreeDisplay })} >
            <TreeComponent
              treeData={treeData}
              selectedKeys={selectedKeys}
              expandedKeys={expandedKeys}
              onSelect={this.onSelect}
              onExpand={this.onExpand}
            />
          </div>}
          <div className={`middle-content ${isTreeDisplay && isTableDisplay?'':'only-middle'}`}>
            <div className="paslogy-content">
              {
          this.mapView ? <IndexChart mapLineClick={this.mapLineClick} /> :
          <TopologyComponent
            topologyData={topologyData}
            nodeSelectionLinkChanged={this.nodeSelectionLinkChanged}
            nodeChange={this.nodeChange}
          />
        }
            </div>
          </div>
          <div className={classnames({ 'right-content': isTableDisplay,'right-content-close': !isTableDisplay })}>
            <div className="devive-title">
              事件列表
            </div>
            <div className="device-lists" ref={node => this.tableNode = node}>
              <AmosGridTable
                columns={checkListColumns(this)}
                getTableDataAction={()=>{}}
                callBack={()=>{}}
                isPageable={false}
                isChecked={false}
                dataList={tableData}
                getPanelHeight={this.getPanelHeight}
                pHeight={pHeight}
              />
            </div>
          </div>
        </div>
      </div>
    );
  }
}

Pams.propTypes = {

};

export default Pams;
