import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Tree } from 'amos-antd';
import dt2react from 'dt2react';
import { AmosFetch } from 'UTILS/processor';
import OltSerUrl from 'CONSTS/urlConsts';
import Icon from 'amos-icon';
import ContextMenu from './ContextMenu';
import UploadMultiPicModal from './uploadPicture/UploadPicsModal';
import './topo.scss';
import { Store } from 'amos-tool';
const lsTool = Store.lsTool;



const TreeNode = Tree.TreeNode;
const loop = (data, key, callback) => {
  data.forEach((item, index, arr) => {
    if (item.orgCode === key) {
      return callback(item, index, arr);
    }
    if (item.children) {
      return loop(item.children, key, callback);
    }
  });
};
/**
 *
 * 拓扑图树
 * @class TopoTree
 * @extends {Component}
 */
class TopoTree extends Component {
  constructor(props) {
    super(props);
    this.state = {
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      treeLocation: {},
      currentTreeData: [],
      currentNode: {}
    };
  }

  componentDidMount(){
    this.getOffset();
    this.getTreeData();
  }

  onExpand = (expandedKeys) => {
    console.log('onExpand', arguments);
    // if not set autoExpandParent to false, if children expanded, parent can not collapse.
    // or, you can remove all expanded children keys.
    this.setState({
      expandedKeys,
      autoExpandParent: false
    });
  }

  onCheck = (checkedKeys) => {
    console.log('onCheck', checkedKeys);
    this.setState({ checkedKeys });
  }

  //选中事件(自动)
  onSelect = (selectedKeys, info) => {
    let parentKey = info.node.props.orgCode ? info.node.props.orgCode : info.node.props.dataRef.orgCode;
    let title = info.node.props.title ? info.node.props.title : info.node.props.dataRef.title;
    let sourceId = info.node.props.eventKey ? info.node.props.eventKey : info.node.props.dataRef.eventKey;
    let key = info.node.props.eventKey;
    let currentNode = { parentKey,title,key };
    if (sourceId !== undefined) {
      Object.assign(currentNode,{ id: sourceId });
    }
    this.setState({ selectedKeys,currentNode });
    let { setCurrentSubviewId } = this.props;
    setCurrentSubviewId(sourceId,title,currentNode,selectedKeys,this.state.expandedKeys);
  }

  //选中事件(手动)
  onArtificialSelect = (selectedKeys, info) => {
    let { title,sourceId,key,parentKey } = info;
    let currentNode = { parentKey,title,key };
    if (sourceId !== undefined) {
      Object.assign(currentNode,{ id: sourceId });
    }
    this.setState({ selectedKeys,currentNode });
    let { setCurrentSubviewId } = this.props;
    setCurrentSubviewId(sourceId,title,currentNode,selectedKeys,this.state.expandedKeys);
  }

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

  //获取用户管理的所有
  getTreeData = () => {
    let orgCode = this.props.orgCode;
    let orgName = this.props.orgName;
    let expandedKeys = this.props.expandedKeys;

    // let  dep=  lsTool.read('selectedRole');

    AmosFetch.get(OltSerUrl.fetchSubgraphInfos).then(res => {
      if (res.ok) {
        return res.json();
      } else {
        throw new Error('从服务端获取数据失败！');
      }
    }).then((data)=>{
      if (data.result === 'SUCCESS'){
        let currentTreeData = data.dataList;
        if (currentTreeData.length > 0){
         // let defaultSelectedKeys = currentTreeData[0].key;
          let defaultSelectedKeys = currentTreeData[0].orgCode;
          if (this.props.orgCode != null){
            defaultSelectedKeys = this.props.orgCode;
          }
          let selectedKeys = [];
          selectedKeys.push(defaultSelectedKeys);
          loop(currentTreeData,defaultSelectedKeys,(item) => {
            // let sourceId = item.key;
            // let title =  item.label;

            let sourceId = item.orgCode;
            let title =  item.companyName;
            if (this.props.orgCode != null ){
              sourceId = orgCode;
              title = orgName;
            }
            let info = { title,sourceId,key: sourceId };
            this.onArtificialSelect(selectedKeys,info);
          });
        }

        if (expandedKeys && expandedKeys.length > 0){
          this.setState({ currentTreeData,expandedKeys: this.props.expandedKeys,autoExpandParent: false });
        } else {
          this.setState({ currentTreeData,expandedKeys: currentTreeData[0].orgCode,autoExpandParent: false });
        }

      }
    });
  }

  nodeRightClick = (e) => {
    this.refs.contextMenu.showMenu(e.event,e.node.props.eventKey);
  }

  renderTreeNodes = (data) => {
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode title={item.companyName} key={item.orgCode} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      } else {
        return <TreeNode title={item.companyName} key={item.orgCode} {...item} />;
      }
    });
  }

  render() {
    let { treeLocation,selectedKeys,currentTreeData,expandedKeys,currentNode,defaultSelectedKeys } = this.state;
    return (
      <div className='topo-tree' ref={node => this.treeRoot = node}>
        {/*<div className='topo-tree-header'>
          <label style={{ width: '50px','font-size': '15px','font-weight': 'bold' }}>物理拓扑图</label>
          <UploadMultiPicModal currentNode={currentNode} {...this.props} />
        </div>*/}
        <div className='topo-tree-content'>
          <Tree
            showLine
            onExpand={this.onExpand}
            expandedKeys={expandedKeys}
            defaultSelectedKeys={defaultSelectedKeys}
            autoExpandParent={this.state.autoExpandParent}
            onCheck={this.onCheck}
            checkedKeys={this.state.checkedKeys}
            onSelect={this.onSelect}
            selectedKeys={this.state.selectedKeys}
          >
            {this.renderTreeNodes(currentTreeData)}
          </Tree>
          <ContextMenu
            treeLocation={treeLocation}
            selectedKeys={selectedKeys}
            addTreeData={this.addTreeData}
            onDelClick={this.delView}
            currentNode={currentNode}
            ref='contextMenu'
          />
        </div>
      </div>
    );
  }
}

TopoTree.propTypes = {
  setCurrentSubviewId: PropTypes.func,
  setCurrentName: PropTypes.func,
  orgCode: PropTypes.any,
  orgName: PropTypes.any,
  expandedKeys: PropTypes.any
};

export default TopoTree;
