import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Tree } from 'amos-framework';
import { keysPartsTreeAction } from './../../api';

const TreeNode = Tree.TreeNode;
/**
 * 重点部位树
 *
 * @class PartsTree
 * @extends {Component}
 */
class PartsTree extends Component {
  constructor(props) {
    super(props);
    this.state = {
      // key 为地图图层名称
      treeData: [],
      expandedKeys: [],
      selectedKeys: []
    };
  }

  componentDidMount() {
    this.onRequest();
  }

  onRequest = () => {
    const { alarm } = this.props;
    keysPartsTreeAction(alarm.sequenceNbr).then(d => {
      this.setState({ treeData: d, expandedKeys: d[0] ? [d[0].key] : [] });
      d[0] && d[0].children && d[0].children[0] && this.handleSelect([d[0].children[0].key]);
    });
  }

  handleSelect = (selectedKeys) => {
    console.log(selectedKeys);
    if (!selectedKeys || selectedKeys.length === 0 || selectedKeys[0] === this.state.treeData[0].key) {
      return;
    }
    this.setState({ selectedKeys });
    this.props.onSelect(selectedKeys[0]);
  }

  renderTree = (data, parentKey = '') => {
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} parentKey={parentKey}>
            {this.renderTree(item.children, item.key)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.key} parentKey={parentKey} {...item} />;
    });
  }

  render() {
    const { treeData, expandedKeys, selectedKeys } = this.state;
    return (
      <div className="ccs-keyparts-tree ccs-scrollbar">
        <Tree
          className="ccs-tree"
          expandedKeys={expandedKeys}
          selectedKeys={selectedKeys}
          onExpand={(d) => this.setState({ expandedKeys: d })}
          onSelect={this.handleSelect}
        >
          {this.renderTree(treeData)}
        </Tree>
      </div>
    );
  }
}

PartsTree.propTypes = {
  alarm: PropTypes.object,
  onSelect: PropTypes.func
};

export default PartsTree;
