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

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

export const AllocationOfIndexModal: FC<AllocationOfIndexModalProps> = ({
  open,
  type,
  assessId,
  item,
  deptList,
  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 [indexList, setIndexList] = useState<IAssIndexDetail[]>([]);
  const [allocationOfIndexDataVisible, setAllocationOfIndexDataVisible] =
    useState(false);

  const getDefaultCheckedKeys = (data: IManageDeptAllocationOfIndexItem[]) => {
    let keys: number[] = [];

    data.forEach((item) => {
      if (item.perm) keys.push(item.id);

      if (item.children && item.children.length > 0) {
        keys = keys.concat(getDefaultCheckedKeys(item.children));
      }
    });

    return keys;
  };

  const getUnAllocationTree = (data: IManageDeptAllocationOfIndexItem[]) => {
    return data.filter((item) => {
      if (item.perm) return false;

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

      return true;
    });
  };

  const getAssIndexTree = async (assign?: number) => {
    try {
      setLoading(true);
      setCheckedKeys([]);
      setTreeData([]);
      const data = await getManageDeptAllocationOfIndexListApi(
        assessId,
        item?.id as number,
        type,
        assign
      );
      if (!assign) {
        const keys = getDefaultCheckedKeys(data);
        setTreeData(data);
        setCheckedKeys(keys);
        form.setFieldsValue({
          checkedKeys: keys,
        });
      } else {
        setTreeData(getUnAllocationTree(data));
      }
    } finally {
      setLoading(false);
    }
  };

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

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

  const handleSubmit = async (values: any) => {
    const data = await checkManageIndexApi({
      assessId,
      normIds: values.checkedKeys.join(","),
    });

    if (!data.length) {
      await saveManageDeptAllocationOfIndexApi({
        assessId,
        deptId: item?.id as number,
        normIds: values.checkedKeys,
      });
      onOk?.();
    } else {
      setIndexList(data);
      setAllocationOfIndexDataVisible(true);
    }

    handleCancel();
  };

  const handleAfterOpenChange = (open: boolean) => {
    if (open) getAssIndexTree();
  };

  useEffect(() => {
    if (!Array.isArray(assign)) return;
    getAssIndexTree(assign[0]);
    form.resetFields(["checkedKeys"]);
  }, [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="checkedKeys"
            required
            rules={[{ required: true, message: "请选择指标" }]}
          >
            <div>
              {!treeData.length && !loading && (
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
              )}

              <Tree
                checkable
                defaultExpandAll
                fieldNames={{ title: "name", key: "id" }}
                checkedKeys={_checkedKeys}
                treeData={treeData}
                onCheck={(keys) => {
                  setCheckedKeys(keys as Key[]);
                  form.setFieldsValue({
                    checkedKeys: keys,
                  });
                }}
              />
            </div>
          </Form.Item>
        </Form>

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

      <AllocationOfIndexDataModal
        open={allocationOfIndexDataVisible}
        indexList={indexList}
        deptList={deptList}
        onOk={() => {
          onOk?.();
          setAllocationOfIndexDataVisible(false);
        }}
        onCancel={() => setAllocationOfIndexDataVisible(false)}
      />
    </>
  );
};
