import React from 'react';
import { Card, Col, Icon, Input, Modal, Tree } from 'antd';
import { config, networkUtils } from '../../utils';

const { api } = config;
const { tree } = api.common;

const TreeNode = Tree.TreeNode;
const Search = Input.Search;

class TreeView extends React.PureComponent {
  componentWillMount = () => {
    this.fetchData();
  };

  fetchData = () => {
    const dataList = [];
    let dataTree = [];

    // if (params.key === '' || params.key === ' ') return 0
    this.setState({ fetching: true });
    networkUtils.request({ method: 'get', url: tree[this.props.apiName], data: [] }).then((data) => {

      if (data.success) {
        dataTree = data.data;
        this.setState({
          dataTree: data.data,
          // dataTree,
          fetching: false,
        });

        const generateList = (tr) => {
          for (let i = 0; i < tr.length; i++) {
            const node = tr[i];
            const key = node.key;
            // dataList.push({ key, title: key })
            dataList.push(node);
            if (node.children) {
              generateList(node.children, node.code);
            }
          }
        };

        generateList(dataTree);

        this.setState({
          dataTree,
          dataList,
        });
      } else {
        throw data;;
      }
    });
  };
  onSelect = (selectedKeys, info) => {
    // console.log(selectedKeys, info)
    const target = this.state.dataList.filter(item => item.code === info.node.props.eventKey);
    const sl = { code: target[0].code, name: target[0].name, id: target[0].id };

    // this.props.onChange(sl.id)
    this.props.onChange(sl[this.props.dataKey]);

    this.setState({
      selected: sl,
      modalVisible: false,
    });
  };
  openModal = () => {
    // this.fetchData()
    this.setState({
      modalVisible: true,
    });
  };
  handleOk = () => {
    this.setState({});
  };
  handleCancel = () => {
    this.setState({
      modalVisible: false,
    });
  };
  handleClose = () => {
    this.searchInput.input.refs.input.value = '';
  };
  getParentKey = (code, tree) => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some(item => item.code === code)) {
          parentKey = node.code;
        } else if (this.getParentKey(code, node.children)) {
          parentKey = this.getParentKey(code, node.children);
        }
      }
    }
    return parentKey;
  };
  onExpand = (expandedKeys) => {
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
  };
  onChange = (e) => {
    const value = e.target.value;
    const expandedKeys = this.state.dataList.map((item) => {
      if (item.name.indexOf(value) > -1) {
        return this.getParentKey(item.code, this.state.dataTree);
      }
      return null;
    }).filter((item, i, self) => item && self.indexOf(item) === i);

    this.setState({
      expandedKeys,
      searchValue: value,
      autoExpandParent: true,
    });
  };
  emitEmpty = () => {
    // this.mainInput.focus()
    this.searchInput.input.refs.input.value = '';
    const sl = {};
    this.setState({
      selected: sl,
      expandedKeys: [],
      searchValue: '',
      autoExpandParent: false,
    });
  };
  findNameById = (id) => {
    const target = this.state.dataList.filter(item => item.id == id);

    // console.log('target', target)

    if (target.length) {
      return target[0].name;
    } else {
      return '';
    }

  };

  constructor(props) {
    super(props);

    this.state = {
      fetching: false,
      modalVisible: false,
      selected: {},
      expandedKeys: [],
      searchValue: '',
      autoExpandParent: true,
      dataList: [],
      dataTree: [],
    };
  }

  render() {
    const { dataTree, modalVisible, selected, searchValue, expandedKeys, autoExpandParent, fetching } = this.state;

    const { title, value, disabled } = this.props;

    const suffix = selected.value ? <Icon type="close-circle" onClick={this.emitEmpty} /> : null;

    const loop = data => data.map((item) => {
      const index = item.name.search(searchValue);
      const beforeStr = item.name.substr(0, index);
      const afterStr = item.name.substr(index + searchValue.length);
      const name = index > -1 ? (
        <span>
          {beforeStr}
          <span style={{ color: '#f50' }}>{searchValue}</span>
          {afterStr}
        </span>
      ) : <span>{item.name}</span>;
      if (item.children) {
        return (
          <TreeNode key={item.code} title={name}>
            {loop(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.code} title={name} />;
    });

    // console.log(selected.name)
    // console.log(value)

    return (
      <Col>
        <Input
          addonAfter={!disabled && <Icon type="search" onClick={this.openModal} />}
          suffix={suffix}
          disabled={disabled}
          data-id={selected.code === undefined ? value : selected.code}
          value={selected.name === undefined ? this.findNameById(value) : selected.name}
          style={{ width: '100%' }}
          ref={node => this.mainInput = node}
        />
        <Modal
          wrapClassName="vertical-center-modal"
          width="60%"
          maskClosable={false}
          visible={modalVisible}
          title={title || '树形选择'}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          afterClose={this.handleClose}
          footer={null}
        >

          <Search
            style={{ width: '30%' }}
            placeholder="搜索"
            onChange={this.onChange}
            ref={node => this.searchInput = node}
          />
          <Card
            title={false}
            loading={fetching}
            bodyStyle={{ padding: 10 }}
            style={{ maxHeight: 600, height: 600, overflowY: 'scroll', border: 'none' }}>
            <Tree
              onSelect={this.onSelect}
              onExpand={this.onExpand}
              expandedKeys={expandedKeys}
              autoExpandParent={autoExpandParent}
            >
              {loop(dataTree)}
            </Tree>
          </Card>
          {/*</Card>*/}
        </Modal>
      </Col>);
  }
}

export default TreeView;
