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 { PubSub } from 'ray-eventpool';
import { Scrollbars } from 'amos-framework';
import { TREE_FETCH_TOPIC } from './../../ruleStatge/modelConf/stageConf';
import Icon from 'amos-icon';

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 RuleTree
 * @extends {Component}
 */
class RuleTree 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 });
    this.props.setCurrentSubviewId(sourceId,title,currentNode,selectedKeys,this.state.expandedKeys);
    PubSub.publish(TREE_FETCH_TOPIC.trigger,{ id: sourceId });
  }

  //选中事件(手动)
  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;

    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].orgCode;
          if (this.props.orgCode != null){
            defaultSelectedKeys = this.props.orgCode;
          }
          let selectedKeys = [];
          selectedKeys.push(defaultSelectedKeys);
          loop(currentTreeData,defaultSelectedKeys,(item) => {
            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 });
          PubSub.publish(TREE_FETCH_TOPIC.trigger,{ id: currentTreeData[0].orgCode });
        }

      }
    });
  }

  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='rule-tree' ref={node => this.treeRoot = node}>
        <div className='rule-tree-content'>
        <Scrollbars>
          <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>
          </Scrollbars>
        </div>
      </div>
    );
  }
}

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

export default RuleTree;
