import { Form, Input, Modal, TreeSelect, message, Checkbox } from 'antd';
import React, {
  useState,
  useEffect,
  useRef,
  forwardRef,
  useImperativeHandle,
} from 'react';
import * as d3 from 'd3';
import './index.less';
import { HomeOutlined } from '@ant-design/icons';
import './index.less';

const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 14 },
};

const CopyDialog = forwardRef(({ open, onCreate, onCancel }, ref) => {
  const [treeData, setData] = useState([]);
  const [form] = Form.useForm();
  const formRef = useRef(null);

  useImperativeHandle(ref, () => ({
    getTreeData() {
      form.resetFields();
      d3.json('/api/bs/hrmorganization/orgchart/getSubCompanyTree').then(
        (data) => {
          data.companyTree.map((item, index) => {
            item.icon = <HomeOutlined />;
          });
          setData(data.companyTree);
        },
      );
    },
  }));

  /**
   * 根节点树异步加载
   * @param {} parentId
   * @returns
   */
  const onRootLoadData = (treeNode) =>
    new Promise((resolve) => {
      const { id } = treeNode.props;
      setTimeout(() => {
        d3.json(
          `/api/bs/hrmorganization/orgchart/getSubCompanyTree?subcompany=${id}`,
        ).then((data) => {
          data.companyTree.map((item, index) => {
            item.icon = <HomeOutlined />;
          });
          let arr = [...treeData, ...data.companyTree];
          setData(arr);
        });
        resolve(undefined);
      }, 200);
    });

  return (
    <Modal
      open={open}
      title="部门合并"
      okText="确认"
      cancelText="取消"
      onCancel={onCancel}
      onOk={() => {
        form
          .validateFields()
          .then((values) => {
            onCreate(values);
          })
          .catch((info) => {
            console.log('Validate Failed:', info);
          });
      }}
    >
      <Form ref={formRef} {...layout} form={form} name="form_in_modal">
        <Form.Item
          name="company"
          label="复制到分部"
          rules={[
            {
              required: true,
              message: '【复制到分部】为必填项!',
            },
          ]}
        >
          <TreeSelect
            className="custom-tree-select"
            treeDataSimpleMode
            allowClear
            style={{ width: '100%' }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            loadData={onRootLoadData}
            treeData={treeData}
            treeIcon
          />
        </Form.Item>

        <Form.Item
          name="copySubDept"
          valuePropName="checked"
          label="是否复制子部门信息"
        >
          <Checkbox />
        </Form.Item>
      </Form>
    </Modal>
  );
});
export default CopyDialog;
