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 mqtt from 'mqtt';
import * as endConf from 'amos-processor/lib/config/endconf';
import { getSelfTopoTreeAction, getSelfTopographyAction, updateSelfTopographyAction, getTopographyEventsAction, getDeivceListAction } from './../../../services/selfServices';

// import AmosGridTable from './../../bizview/common/tableComponent/table/AmosGridTable';
import AmosGridTable from './../../component/table/table/AmosGridTable';
import SysWsURL from './../../../consts/wsUrlConsts';

const AmosConfig = endConf.AmosConfig;
const mqttURI = AmosConfig.wsURI.mqttURI;
const options = {
  //默认 30 * 1000毫秒，收到 CONNACK 之前等待的时间，即连接超时时间。
  connectTimeout: 40000,
  // 客户端 ID,随机生成
  clientId: 'bank_self_mqtt' + Math.random().toString(16).substr(2, 8),
  clean: true,
  //默认 1000 毫秒，两次重新连接之间的间隔，客户端 ID 重复、认证失败等客户端会重新连接；
  reconnectPeriod: 1000 * 50
}
let client = mqtt.connect(mqttURI, options)

const checkListColumns = (self) => {
  return [
    {
      title: '时间',
      dataIndex: 'updateDate',
      key: 'updateDate',
      width: '45%',
      render: (text, record) => {
        let font = document.createElement('font');
        if (record.deviceStatus === 1) {
          font.innerText = text;
          font.style.color = 'red';
        } else {
          font.innerText = text;
        }
        return <div dangerouslySetInnerHTML={{ __html: font.outerHTML }} ></div>
      }
    }, {
      title: '设备名称',
      dataIndex: 'name',
      key: 'name',
      width: '30%',
      render: (text, record) => {
        let font = document.createElement('font');
        if (record.deviceStatus === 1) {
          font.innerText = text;
          font.style.color = 'red';
        } else {
          font.innerText = text;
        }
        return <div dangerouslySetInnerHTML={{ __html: font.outerHTML }} ></div>
      }
    }, {
      title: 'ping结果',
      dataIndex: 'deviceStatus',
      key: 'deviceStatus',
      render: (text, record) => {
        let p = document.createElement('span');
        if (text === 0) {
          let font = document.createElement('font');
          font.innerText = '连接正常';
          p.append(font);
        }

        if (text === 1) {
          let font = document.createElement('font');
          font.innerText = '连接异常';
          font.style.color = 'red';
          p.append(font);
        }
        return <div dangerouslySetInnerHTML={{ __html: p.outerHTML }} ></div>
      }
    }
  ];
};


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

class SelfSupport extends Component {

  constructor(props) {
    super(props);
    this.pageConfig = {
      current: 1,
      pageSize: 10,
      pageNumber: 1
    };
    this.state = {
      treeData: [
        {
          name: '',
          id: '1',
          children: []
        }
      ], //树数据

      autoExpandParent: true,
      selectedKeys: [],
      expandedKeys: [],
      topologyData: {}, //拓扑图数据
      tableData: [],
      isTreeDisplay: true,
      isTableDisplay: true,
      activeView: 'left',
      pHeight: 0,
      cityLine: '',
      totalCount: 0,
      searchParam: [],
      selectedRows: [],
      selectedRowKeys: [],
      pagination: true,
      isChecked: false,
    };
    this.updateTopologyData = {};
    this.mapView = true;
  }
  componentWillMount() {
    
  }

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

  }

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

  }

  receivcemqtt = () => {
    client.on('connect', (e) => {
      console.log("连接成功！！！")
      //QoS0，最多一次送达。也就是发出去就fire掉，没有后面的事情了。
      // QoS1，至少一次送达。发出去之后必须等待ack，没有ack，就要找时机重发
      // QoS2，准确一次送达。消息id将拥有一个简单的生命周期。
      // client.subscribe('bank/equipment/ping', { qos: 1 }, (res) => {
      client.subscribe('bank/equipment/ping', { qos: 1 }, (res) => {
        if (!res) {
          console.log('订阅成功');

        } else {
          console.log('订阅失败')
        }
      });

      // 接收消息处理
      client.on('message', (topic, message) => {
       // console.log('收到来自', topic, '的消息', message.toString());
        const { selectedKeys } = this.state;
        this.initTopologyData(selectedKeys[0], '');

      });

      // 断开发起重连
      client.on('reconnect', (error) => {
        console.log('正在重连:', error)
      });
      // 链接异常处理
      client.on('error', (error) => {
        console.log('连接失败:', error)
      });
    });
  }

  //点击地图线操作
  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)-30;
  };

  // 数据初始化
  initData = () => {
    let expandedKeysData = [];
    getSelfTopoTreeAction().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 = '') => {
    getSelfTopographyAction(id).then(data => {
      if (value === 'refresh') {
        message.success('拓扑图刷新成功!');
      }

      //console.log('视图刷新成功!');
      this.setState({
        topologyData: data
      });
    });
    getDeivceListAction(0, 10, null).then(data => {
     // console.log('表格刷新成功!');
      this.setState({ tableData: data.content, totalCount: data.totalElements });
    });
  }

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

  /**
* 获取表格所选则的行数据
*/
  getSelectedRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
    let { riskSourceId, equipmentId, callBack } = this.props;
    // callBack(selectedRowKeys,riskSourceId,equipmentId);
  };


  // 树选择
  onSelect = (selectedKeys, e) => {
    if (selectedKeys.length && !e.node.props.parent) {
      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
    });
  };


  queryEquipPage = () => {
    let pageConfig = this.pageConfig;
    let pageNumber = pageConfig.pageNumber - 1;
    let pageSize = pageConfig.pageSize;
    getDeivceListAction(pageNumber, pageSize, null).then(data => {

      this.setState({ tableData: data.content, totalCount: data.totalElements });

    });
  }

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

  // 选择节点
  nodeSelectionChanged = (e) => {
    // console.log('e',e);
    if (e.isSelected) { }
  }

  // 节点数据改变
  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
    };
    updateSelfTopographyAction(params).then(data => {
      message.success('拓扑图保存成功!');
    });
  }

  /**
  * 分页设置参数
  */
  setPageConfig = ({ pageSize, current }) => {
    if (pageSize !== undefined) {
      this.pageConfig.pageSize = pageSize;
    }

    this.pageConfig.pageNumber = current;
  };

  /**
* 获取表格刷新方法
*/
  reload = r => {
    this.setState(
      {
        reload: () => {
          r();
          this.setState({ selectedRows: [], selectedRowKeys: [] });
        }
      },
      r()
    );
  };

  // 刷新节点
  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) => {
    const { selectedKeys } = this.state;
    this.initTopologyData(selectedKeys[0], '');
  }


  render() {
    const { treeData, selectedKeys, expandedKeys, isTreeDisplay, totalCount, selectedRowKeys, pagination, isChecked } = this.state;
    let defaultPageConfig = this.pageConfig;
    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="self-wrapper">
        <AmosWebSocket
          ref={node => this.aws = node}
          url={SysWsURL.selfURI}
          onMessage={this.handleData}
          reconnect
          debug
        />
        <div className="self-header">
          <div className="self-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="self-data">
            <div className="self-topo-save">
              <img src="/src/assets/bizView/netTopology/save.png" alt="保存" onClick={this.saveTopologyData} />
            </div>
            <div className="self-topo-refresh">
              <img src="/src/assets/bizView/netTopology/refresh.png" alt="刷新" onClick={this.refreshTopologyData} />
            </div>
          </div>
        </div>
        <div className="self-content">
          {<div className={classnames({ 'left-content': isTreeDisplay, 'left-content-close': !isTreeDisplay })} >

            <TreeComponent
              treeData={treeData}
              //treeData={moniTreeData}
              selectedKeys={selectedKeys}
              expandedKeys={expandedKeys}
              // onSelect={this.onSelect}
              onExpand={this.onExpand}
            />
          </div>}
          <div className={`middle-content ${isTreeDisplay && isTableDisplay ? '' : 'only-middle'}`}>
            <div className="paslogy-content">
              <div className="middle-content-div">
                <div className="content-left">
                  <div className="box">西安中心</div>
                </div>
                <div className="content-right">
                  <div className="box">咸阳中心</div>
                </div>
              </div>
              <div className="net-topo-content">
                <TopologyComponent
                  topologyData={topologyData}
                  //nodeSelectionLinkChanged={this.nodeSelectionLinkChanged}
                  nodeSelectionChanged={this.nodeSelectionChanged}
                  nodeChange={this.nodeChange}
                />
              </div>
            </div>
          </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={true}
                isChecked={false}
                dataList={tableData}
                //dataList={data}
                getPanelHeight={this.getPanelHeight}
                pHeight={pHeight}
              />
            </div> */}
              <AmosGridTable
                columns={checkListColumns(this)}
                callBack={this.reload}
                isPageable={pagination}
                totals={totalCount}
                dataList={tableData}
                getTableDataAction={this.queryEquipPage}
                //selectedRowKeys={selects}
                selectedRowKeys={selectedRowKeys}
                getSelectedRows={this.getSelectedRows}
                // rowClassName={this.getRowClassName}
                // onRowClick={this.onRowClick}
                isChecked={isChecked}
                setPageConfig={this.setPageConfig}
                defaultPageConfig={defaultPageConfig}
                getPanelHeight={this.getPanelHeight}
              />
            </div>
          </div>
        </div>
      </div>
    );
  }
}

SelfSupport.propTypes = {

};

export default SelfSupport;
