import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { Tree,Menu,Icon,Button } from 'amos-antd';
import { deepCopy } from 'amos-tool';
import { getWebTreeAction,addWebTreeAction,delWebTreeAction } from './../../../services/netTopologyService';

const TreeNode = Tree.TreeNode;

class TreeComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      treeData: [
        {
          name: '',
          id: '1',
          children: []
        }
      ], //树数据
      autoExpandParent: true,
      selectedKeys: [],
      expandedKeys: [],
      rightClickNodeTreeItem: {},
      isMenuVisible: false
    };
    this.treeLists = [];
    this.activeKey = null;
    this.activeValue = '';
  }

  componentDidMount() {
    document.addEventListener('click', this.bindBodyClick, false);
    this.initData();
  }

  componentWillUnmount() {
    document.removeEventListener('click', this.bindBodyClick);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.wSelectedKeys && nextProps.wSelectedKeys !== this.props.wSelectedKeys) {
      this.setState({
        selectedKeys: nextProps.wSelectedKeys
      });
    }
  }


  // 绑定body
  bindBodyClick = (e) => {
    e.stopPropagation();
    this.setState({
      isMenuVisible: false
    });
  }

  // 初始化树数据
  initData = (treeData) => {
    const { onSelect } = this.props;
    const expandedKeysData = [];
    getWebTreeAction().then(data => {
      data.map(item => {
        expandedKeysData.push(item.id);
      });
      this.treeLists = data;
      onSelect(data[0].id);
      this.setState({
        treeData: data,
        selectedKeys: [data[0].id],
        expandedKeys: expandedKeysData
      });
    });
  }

  // 树选择
  onSelect = (selectedKeys,e) => {
    const { onSelect } = this.props;
    if (!selectedKeys.length) {return;}
    if (!e.node.props.parent) {
      onSelect(selectedKeys[0]);
    }
    this.setState({
      selectedKeys
    });
  }

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

  // 节点右键事件
  treeNodeonRightClick = (e) => {
    // if (e.node.props.parent) {
    //   return;
    // }
    const x = e.event.currentTarget.offsetLeft + e.event.currentTarget.clientWidth;
    const y = e.event.currentTarget.offsetTop;
    this.activeKey = e.node.props.id;
    this.setState({
      rightClickNodeTreeItem: {
        pageX: x,
        pageY: y,
        id: e.node.props.id,
        parent: e.node.props.parent
      },
      isMenuVisible: true
    });
  }

  // 节点右键菜单
  getNodeTreeRightClickMenu = () => {
    const { rightClickNodeTreeItem } = this.state;
    const { pageX, pageY, id, parent } = rightClickNodeTreeItem;
    if (!rightClickNodeTreeItem.id) {
      return null;
    }
    const style = {
      position: 'absolute',
      left: `${pageX}px`,
      top: `${pageY}px`
    };
    const menu = (
      <Menu
        onClick={(e) => this.handleMenuClick(e, id)}
        style={style}
        className="tree-right"
      >
        {!parent && <Menu.Item key='1'><img src="/src/assets/bizView/netTopology/add-node.png" alt="添加子图" className="tree-add-img" />{'添加子图'}</Menu.Item>}
        <Menu.Item key='2'><img src="/src/assets/bizView/netTopology/del-node.png" alt="删除子图" className="tree-del-img" />{'删除'}</Menu.Item>
      </Menu>
        );
    return menu;
  }

  // 选择菜单
  handleMenuClick = (value, id) => {
    let { expandedKeys } = this.state;
    if (!expandedKeys.includes(id)) {
      expandedKeys = [...expandedKeys, id];
    }
    if (value.key === '1') {
      this.addNode(id);
    } else {
      this.deleteNode(id);
    }

    this.setState({
      isMenuVisible: false,
      expandedKeys
    });
  }

  // 添加拓扑插件
  addTopology = () => {
    this.treeLists.push({
      name: '',
      id: Math.random(100),
      isAdd: true,
      children: [],
      parent: null
    });
    this.setState({
      treeData: this.treeLists
    });
  }

  // 添加节点
  addNode = (id) => {
    this.treeLists.map(item => {
      if (item.id === id) {
        item.children.push({
          name: '',
          id: id + Math.random(100),
          isAdd: true,
          children: [],
          parent: null
        });
      }
    });
    this.setState({
      treeData: this.treeLists
    });
  }

  onInputChange = (e, id) => {
    this.activeValue = e.target.value;
    this.changeNode(id, e.target.value, this.treeLists);
    this.setState({
      treeData: this.treeLists
    });
  }

  // 改变节点
  changeNode = (id, value, data) => data.map((item) => {
    if (item.isAdd) {
      item.name = value;
      return;
    }
    if (item.children.length) {
      this.changeNode(id, value, item.children);
    }
  })

  onClose = (id) => {
    this.closeNode(id, this.treeLists);
    // this.setState({
    //   treeData: this.treeLists
    // });
    this.initData();
  }

  // 关闭节点
  closeNode = (id, data) => data.map((item,index) => {
    if (item.id === id) {
      data.splice(index, 1);
      return;
    }
    if (item.children.length) {
      this.closeNode(id, item.children);
    }
  })

  // 保存节点
  onSave = () => {
    const params = {
      name: this.activeValue,
      parent: this.activeKey
    };
    addWebTreeAction(params).then(() => {
      this.initData();
    });
  }

  // 删除节点
  deleteNode = (id) => {
    delWebTreeAction(id).then(() => {
      this.initData();
    });
  }

  renderTreeNodes = (data) => {
    let operableTreeData = deepCopy(data);
    return operableTreeData.map((item) => {
      if (item.isAdd) {
        item.name = (
          <div>
            <input
              value={item.name}
              onChange={(e) => this.onInputChange(e, item.id)}
            />
            <Icon type='close' style={{ marginLeft: 10 }} onClick={() => this.onClose(item.id)} />
            <Icon type='check' style={{ marginLeft: 10 }} onClick={() => this.onSave(item.id)} />
          </div>
      );
      }
      if (item.children && item.children.length) {
        return (
          <TreeNode title={item.name}
            key={item.id}
            id={item.id}
            dataRef={item}
            parent={item.parent}
            group={item.group}
          >
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return (<TreeNode key={item.id}
        title={item.name}
        id={item.id}
        dataRef={item}
        parent={item.parent}
        group={item.group}
      />);
    });
  }

  render() {
    const { treeData,selectedKeys,expandedKeys,autoExpandParent,isMenuVisible } = this.state;
    const { className } = this.props;
    return (
      <div className={classnames('tree-wrapper', className)}>
        <div className="tree-btn">
          <div className="add-topo" onClick={this.addTopology}>
            <img src="/src/assets/bizView/netTopology/add-topo.png" alt="添加拓扑图" />
          </div>
        </div>
        <Tree
          selectedKeys={selectedKeys}
          expandedKeys={expandedKeys}
          onSelect={this.onSelect}
          onExpand={this.onExpand}
          autoExpandParent={autoExpandParent}
          onRightClick={this.treeNodeonRightClick}
        >
          {this.renderTreeNodes(treeData)}
        </Tree>
        {isMenuVisible && this.getNodeTreeRightClickMenu()}
      </div>
    );
  }
}

TreeComponent.propTypes = {
  className: PropTypes.string,
  treeData: PropTypes.object,
  onSelect: PropTypes.func,
  wSelectedKeys: PropTypes.string
};

TreeComponent.defaultProps = {
  wSelectedKeys: ''
};

export default TreeComponent;
