import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Tree,Modal } from 'amos-antd';
import Icon from 'amos-icon';
import dt2react from 'dt2react';
// import { currentUser } from 'amos-security/lib/model/auth';
import { AmosFetch } from '../../../../utils/processor';
import OltSerUrl from '../../../../consts/urlConsts';
import { message } from 'amos-framework';
import TreeHeader from './../header/TreeHeader';
import AddView from './AddView';
import ContextMenu from './ContextMenu';
import { currentUser } from './../../../../utils/userConfig';

const TreeNode = Tree.TreeNode;
const loop = (data, key, callback) => {
  data.forEach((item, index, arr) => {
    if (item.key === key) {
      return callback(item, index, arr);
    }
    if (item.children) {
      return loop(item.children, key, callback);
    }
  });
};
const rootNode = { title: '根目录', key: '0',parentKey: '-1',children: [],sourceId: 0 };
/**
 *
 * 拓扑图树
 * @class TopoTree
 * @extends {Component}
 */
class TopoTree extends Component {
  constructor(props) {
    super(props);
    this.state = {
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      treeLocation: {},
      currentTreeData: [],
      currentNode: {},
      viewVisable: false
    };
  }

  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.children === null ? info.node.props.parentKey : info.node.props.dataRef.parentKey;
    let title = info.node.props.children === null ? info.node.props.title : info.node.props.dataRef.title;
    let sourceId = info.node.props.children === null ? info.node.props.sourceId : info.node.props.dataRef.sourceId;
    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.editTreeData);
  }

  //选中事件(手动)
  onArtificialSelect = (selectedKeys, info) => {
    let { parentKey,title,sourceId,key } = 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.editTreeData);
  }

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

  //获取用户管理的所有
  getTreeData = () => {
    let user = currentUser();
    let param = { userId: user.userId };
    // AmosFetch.post(OltSerUrl.fetchSubgraphInfos,{ data: param }).then(res => {
    //   if (res.ok) {
    //     return res.json();
    //   }
    //   else
    //   {
    //     throw new Error('从服务端获取数据失败！');
    //   }
    // }).then((data)=>{
    //   if (data.result === 'SUCCESS'){
    //     let subgraphList = data.dataList;
    //     let currentTreeData = [];
    //     if (subgraphList && subgraphList.length > 0) {
    //       rootNode.children = subgraphList;
    //     }
    //     currentTreeData.push(rootNode);
    //     this.setState({ currentTreeData });
    //   }
    // });
    let currentTreeData = [
      {
        'sourceId': 0,
        'key': '0',
        'parentKey': '-1',
        'title': '昆山宁华',
        'children': [
          {
            'sourceId': 1,
            'key': '0-0',
            'parentKey': '0',
            'title': '昆山A区',
            'value': '昆山A区'
          },{
            'sourceId': 2,
            'key': '0-1',
            'parentKey': '0',
            'title': '昆山B区',
            'children': [
              {
                'sourceId': 3,
                'key': '0-1-0',
                'parentKey': '0-1',
                'title': '一楼',
                'value': '一楼'
              },{
                'sourceId': 4,
                'key': '0-1-1',
                'parentKey': '0-1',
                'title': '二楼',
                'value': '二楼'
              }
            ],
            'value': '昆山B区'
          }
        ],
        'value': '昆山宁华'
      },{
        'sourceId': 11,
        'key': '1',
        'parentKey': '-1',
        'title': '信达可恩',
        'children': [],
        'value': '信达可恩'
      },{
        'sourceId': 11,
        'key': '2',
        'parentKey': '-1',
        'title': '中安消防',
        'children': [],
        'value': '中安消防'
      },{
        'sourceId': 11,
        'key': '3',
        'parentKey': '-1',
        'title': '鼎信消防',
        'children': [],
        'value': '鼎信消防'
      },{
        'sourceId': 11,
        'key': '4',
        'parentKey': '-1',
        'title': '坚锐消防',
        'children': [],
        'value': '坚锐消防'
      }
    ];
    this.setState({ currentTreeData });
  }

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

  toggleView = (flag = false) => {
    this.setState({
      viewVisable: flag
    });
  }

  addView = () => {
    const { selectedKeys } = this.state;
    if (selectedKeys.length === 1) {
      this.setState({ viewVisable: true });
    } else {
      message.danger('新选择父节点！');
    }
  }

  delView = (e) => {
    let { currentNode,selectedKeys } = this.state;
    let currentParentkey = currentNode.parentKey;
    if (currentParentkey === '-1') {
      Modal.info({ title: '系统提示',content: '不能删除根节点', okText: '确定' });
      return;
    }
    let delfunc = this.delTreeData;
    if (selectedKeys.length === 1) {
      Modal.confirm({
        title: '批量删除',
        content: '是否删除所选信息？',
        okText: '确定',
        cancelText: '取消',
        onOk() {
          delfunc(currentParentkey,currentNode.key);
        },
        onCancel() {}
      });
    } else {
      message.danger('新选择要删除的节点节点！');
    }
  }

  //新增元素
  addTreeData = (newNodeName) => {
    let { currentTreeData,expandedKeys,currentNode } = this.state;
    let selectedKey = currentNode.key;
    loop(currentTreeData,selectedKey,(item) => {
      item.children = item.children || [];
      let childKey = this.generateKey(item.children,selectedKey);
      //待保存的设备
      let time = new Date().getTime();
      let persistObj = { createTime: time,name: newNodeName,currentKey: childKey,parentKey: selectedKey,userId: currentUser().userId };
      //保存到数据库
      this.saveSubgraphData(persistObj);
      //如果选中的节点没有展开，则展开
      if (expandedKeys.indexOf(childKey) === -1) {
        expandedKeys.push(selectedKey);
        this.setState({ expandedKeys });
      }
    });
  }

  //编辑元素
  editTreeData = (newNodeName) => {
    let { currentTreeData,currentNode } = this.state;
    let currentParentkey = currentNode.parentKey;
    if (currentParentkey === '-1') {
      Modal.info({ title: '系统提示',content: '不能编辑根节点', okText: '确定' });
      return;
    }
    let selectedKey = currentNode.key;
    loop(currentTreeData,selectedKey,(item) => {
      item.title = newNodeName;
      //待编辑的设备
      let time = new Date().getTime();
      let persistObj = { id: currentNode.id, createTime: time,name: newNodeName,currentKey: item.key,parentKey: item.parentKey,userId: currentUser().userId };
      //保存到数据库
      this.saveSubgraphData(persistObj);
    });
  }

  //保存子图
  saveSubgraphData = (paramdata) => {
    AmosFetch.post(OltSerUrl.addSubgraph, { data: paramdata }).then(res => {
      if (res.ok) {
        return res.text();
      }
      else {
        throw new Error('从服务端获取数据失败！');
      }
    }).then((data) => {
      let { setCurrentName } = this.props;
      let result = JSON.parse(data);
      let resultStatus = result.result;
      if (resultStatus === 'SUCCESS') {
        //界面刷新
        this.getTreeData();
        setCurrentName(paramdata.name);
        message.success('保存成功');
      } else {
        message.success(`保存失败：${result.message}`);
      }
    });
  }

  //删除元素
  delTreeData = (parentKey,nodeKey) => {
    let url = `${OltSerUrl.delSubgraph}/${nodeKey}`;
    // AmosFetch.del(url).then(res => {
    //   if (res.ok) {
    //     return res.text();
    //   }
    //   else
    //   {
    //     throw new Error('从服务端获取数据失败！');
    //   }
    // }).then((data)=>{
    // //重新刷新数据
    //   const modal = Modal.warning({
    //     title: '系统提示',
    //     content: '删除成功！',
    //     okText: '确定'
    //   });
    //   setTimeout(() => modal.destroy(), 1000);
    //   //界面刷新
    //   this.updateTreeData(parentKey);
    // });
    this.updateTreeData(parentKey);
  }

  //获取用户管理的所有
  updateTreeData = (parentKey) => {
    let user = currentUser();
    let param = { userId: user.userId };
    // AmosFetch.post(OltSerUrl.fetchSubgraphInfos,{ data: param }).then(res => {
    //   if (res.ok) {
    //     return res.json();
    //   }
    //   else
    //   {
    //     throw new Error('从服务端获取数据失败！');
    //   }
    // }).then((data)=>{
    //   if (data.result === 'SUCCESS'){
    //     let subgraphList = data.dataList;
    //     let currentTreeData = [];
    //     if (subgraphList) {
    //       rootNode.children = subgraphList;
    //     }
    //     currentTreeData.push(rootNode);
    //     //自动选中父节点
    //     let selectedKeys = [];
    //     selectedKeys.push(parentKey);
    //     loop(currentTreeData,parentKey,(item) => {
    //       let info = { parentKey: item.parentKey,title: item.title,sourceId: item.sourceId,key: item.key };
    //       this.onArtificialSelect(selectedKeys,info);
    //     });
    //     this.setState({ currentTreeData });
    //   }
    // });
    // const rootNode = { title: '根目录', key: '0',parentKey: '-1',children: [],sourceId: 0 };
    let currentTreeData = [
      {
        'sourceId': 0,
        'key': '0',
        'parentKey': '-1',
        'title': '昆山宁华',
        'children': [
          {
            'sourceId': 1,
            'key': '0-0',
            'parentKey': '0',
            'title': '昆山A区',
            'value': '昆山A区'
          },{
            'sourceId': 2,
            'key': '0-1',
            'parentKey': '0',
            'title': '昆山B区',
            'children': [
              {
                'sourceId': 3,
                'key': '0-1-0',
                'parentKey': '0-1',
                'title': '一楼',
                'value': '一楼'
              },{
                'sourceId': 4,
                'key': '0-1-1',
                'parentKey': '0-1',
                'title': '二楼',
                'value': '二楼'
              }
            ],
            'value': '昆山B区'
          }
        ],
        'value': '昆山宁华'
      },{
        'sourceId': 11,
        'key': '1',
        'parentKey': '-1',
        'title': '信达可恩',
        'children': [],
        'value': '信达可恩'
      },{
        'sourceId': 11,
        'key': '2',
        'parentKey': '-1',
        'title': '中安消防',
        'children': [],
        'value': '中安消防'
      },{
        'sourceId': 11,
        'key': '3',
        'parentKey': '-1',
        'title': '鼎信消防',
        'children': [],
        'value': '鼎信消防'
      },{
        'sourceId': 11,
        'key': '4',
        'parentKey': '-1',
        'title': '坚锐消防',
        'children': [],
        'value': '坚锐消防'
      }
    ];
    this.setState({ currentTreeData });
  }

  //按自然数顺序生成key
  generateKey = (childList,parentKey) => {
    if (childList === undefined || (childList.length === 0)) {
      return `${parentKey}-0`;
    } else {
      let childListNum = [];
      childList.map((item)=>{
        let nums = item.key.split('-');
        childListNum.push(parseInt(nums[nums.length - 1]));
      });
      let maxValue = Math.max.apply(null, childListNum);
      return `${parentKey}-${maxValue + 1}`;
    }
  }

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

  renderTreeHeaderExtra = () => {
    const extra = [
      <div key="create-view" className="tree-header-extra-item" onClick={this.addView} title="创建视图">
        <Icon icon="luru" />
      </div>,
      <div key="del-view" className="tree-header-extra-item" onClick={this.delView} title="删除视图">
        <Icon icon="delete" />
      </div>
    ];
    return extra;
  }

  render() {
    const { treeLocation, viewVisable, selectedKeys, currentTreeData, expandedKeys, currentNode } = this.state;
    return (
      <div className='topo-tree' ref={node => this.treeRoot = node}>
        <TreeHeader title="物理拓扑图" extra={this.renderTreeHeaderExtra()} />
        <div className='topo-tree-content'>
          <Tree
            showLine
            onExpand={this.onExpand}
            expandedKeys={expandedKeys}
            autoExpandParent={this.state.autoExpandParent}
            onCheck={this.onCheck}
            checkedKeys={this.state.checkedKeys}
            onSelect={this.onSelect}
            selectedKeys={this.state.selectedKeys}
            onRightClick={this.nodeRightClick}
          >
            {this.renderTreeNodes(currentTreeData)}
          </Tree>
          <ContextMenu
            treeLocation={treeLocation}
            selectedKeys={selectedKeys}
            addTreeData={this.addTreeData}
            onDelClick={this.delView}
            currentNode={currentNode}
            editTreeData={this.editTreeData}
            ref='contextMenu'
          />
        </div>
        <AddView visible={viewVisable} selectedKeys={selectedKeys} addTreeData={this.addTreeData} toggleView={this.toggleView} />
      </div>
    );
  }
}

TopoTree.propTypes = {
  setCurrentSubviewId: PropTypes.func,
  setCurrentName: PropTypes.func
};

export default TopoTree;
