import React from 'react';
import { TreeSelect, Modal, message } from 'antd';

export default class OperateDialog extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      treeData: [],
      open: false,
      confirmLoading: false,
      title: '',
      operateType: '',
      root: '',
      type: 1,
    };
  }

  componentDidMount() {}

  handleOk = () => {
    const { type } = this.state;
    if (type === 1) {
      this.props.addFolderNode();
    } else {
      this.props.deleteNode();
    }
    setTimeout(() => {
      this.setState({ open: false });
      message.success('操作成功');
    }, 200);
  };

  /**
   * 根节点树数据
   * @param {} parentId
   * @returns
   */
  getNodeTreeNode = (parentId) => {
    this.setState({ confirmLoading: true });
    fetch(`/api/bs/hrmorganization/orgchart/getSubCompanyTree`)
      .then((res) => res.json())
      .then((data) => {
        if (data.api_status) {
          let arr = [];
          arr = [...this.state.treeData, ...data.companyTree];
          this.setState({
            treeData: arr,
            confirmLoading: false,
          });
        }
      });
  };

  /**
   * 根节点树异步加载
   * @param {} parentId
   * @returns
   */
  onRootLoadData = (treeNode) =>
    new Promise((resolve) => {
      const { id } = treeNode.props;
      setTimeout(() => {
        let api = `/api/bs/hrmorganization/orgchart/getSubCompanyTree?subcompany=${id}`;
        this.getNodeTreeNode(api);
        resolve(undefined);
      }, 500);
    });

  showOperate = (id, title, type) => {
    this.setState({
      open: true,
      confirmLoading: true,
      title: title,
      type: type,
    });
    this.getNodeTreeNode(id);
  };

  onRootChange = (value) => {
    this.setState({ root: value });
  };

  render() {
    const { treeData, open, confirmLoading, title } = this.state;
    return (
      <>
        <Modal
          title={title}
          cancelText="取消"
          okText="确定"
          open={open}
          onOk={this.handleOk}
          confirmLoading={confirmLoading}
          onCancel={() => this.setState({ open: false })}
        >
          <TreeSelect
            treeDataSimpleMode
            allowClear
            style={{ width: '100%' }}
            value={this.state.root}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            placeholder="请选择要删除的节点"
            onChange={this.onRootChange}
            loadData={this.onRootLoadData}
            treeData={treeData}
          />
        </Modal>
      </>
    );
  }
}
