import { FC, Key, useEffect, useState } from "react";
import { Checkbox, Form, Modal, ModalProps, Tree } from "antd";
import {
  IManageDeptAllocationOfIndexItem,
  ASS_INDEX_TYPE,
  IManageDeptItem,
} from "@/types";
import { DageLoading } from "@dage/pc-components";
import {
  getManageDeptAllocationOfIndexListApi,
  saveManageDeptAllocationOfIndexApi,
} from "@/api";

export interface AllocationOfIndexModalProps extends Omit<ModalProps, "onOk"> {
  type: ASS_INDEX_TYPE;
  assessId: number | string;
  item?: null | IManageDeptItem;
  onCancel?: () => void;
  onOk?: () => void;
}

export const AllocationOfIndexModal: FC<AllocationOfIndexModalProps> = ({
  open,
  type,
  assessId,
  item,
  onOk,
  onCancel,
  ...rest
}) => {
  const [form] = Form.useForm<any>();
  const [_checkedKeys, setCheckedKeys] = useState<Key[]>([]);
  const [treeData, setTreeData] = useState<IManageDeptAllocationOfIndexItem[]>(
    []
  );
  const [loading, setLoading] = useState(false);
  const assign = Form.useWatch("assign", form);

  const transformTreeData = (data: IManageDeptAllocationOfIndexItem[]) => {
    return data.map((item) => {
      const newNode: any = {
        ...item,
        disableCheckbox: item.perm,
      };

      if (item.children && item.children.length > 0) {
        newNode.children = transformTreeData(item.children);
      }

      return newNode;
    });
  };

  const getAssIndexTree = async (assign?: number) => {
    try {
      setLoading(true);
      const data = await getManageDeptAllocationOfIndexListApi(
        assessId,
        item?.id as number,
        type,
        assign
      );
      setTreeData(assign ? transformTreeData(data) : data);
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    onCancel?.();
    form.resetFields();
    setCheckedKeys([]);
  };

  const handleConfirm = () => {
    form.submit();
  };

  const handleSubmit = async (values: any) => {
    await saveManageDeptAllocationOfIndexApi({
      assessId,
      deptId: item?.id as number,
      normIds: values.onlyChildKeys,
    });
    onOk?.();
    handleCancel();
  };

  const handleAfterOpenChange = (open: boolean) => {
    if (open && !treeData.length) getAssIndexTree();
  };

  useEffect(() => {
    if (!Array.isArray(assign)) return;
    getAssIndexTree(assign[0]);
    form.resetFields(["onlyChildKeys"]);
  }, [assign]);

  return (
    <Modal
      title="分配指标"
      okText="提交"
      cancelText="取消"
      open={open}
      width={640}
      maskClosable={false}
      okButtonProps={{
        disabled: false,
      }}
      onOk={handleConfirm}
      onCancel={handleCancel}
      {...rest}
      afterOpenChange={handleAfterOpenChange}
    >
      <Form
        labelCol={{ span: 4, offset: 2 }}
        form={form}
        onFinish={handleSubmit}
      >
        <Form.Item name="assign" label=" " colon={false}>
          <Checkbox.Group
            options={[
              {
                label: "仅查看尚未分配的指标",
                value: 1,
              },
            ]}
          />
        </Form.Item>
        <Form.Item
          label="采用指标"
          name="onlyChildKeys"
          required
          rules={[{ required: true, message: "请选择指标" }]}
        >
          <Tree
            checkable
            defaultExpandAll
            fieldNames={{ title: "name", key: "id" }}
            checkedKeys={_checkedKeys}
            treeData={treeData}
            onCheck={(checkedKeys, { checkedNodes }) => {
              const onlyChildKeys = (checkedKeys as Key[]).filter((i) => {
                const node = checkedNodes.find((n) => n.id === i);
                return !node?.children.length;
              });
              setCheckedKeys(onlyChildKeys);
              form.setFieldsValue({
                onlyChildKeys,
              });
            }}
          />
        </Form.Item>
      </Form>

      {loading && <DageLoading />}
    </Modal>
  );
};
