import { FC, Key, useEffect, useRef, useState } from "react";
import { Modal, ModalProps, Select, Tag } from "antd";
import { IManageDeptMaterialItem, IManageDeptItem, YES_OR_NO } from "@/types";
import {
  getManageDeptAllocationOfDataListApi,
  saveManageDeptAllocationOfDataApi,
} from "@/api";
import {
  EditableProTable,
  ProForm,
  ProFormInstance,
} from "@ant-design/pro-components";

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

export const AllocationOfDataModal: FC<AllocationOfDataModalProps> = ({
  assessId,
  open,
  deptList,
  onOk,
  onCancel,
  ...rest
}) => {
  const formRef = useRef<ProFormInstance<any>>();
  const [loading, setLoading] = useState(false);
  const [listLoading, setListLoading] = useState(false);
  const [editableKeys, setEditableKeys] = useState<Key[]>([]);

  const handleCancel = () => {
    onCancel?.();
    formRef.current?.resetFields();
  };

  const handleConfirm = async () => {
    if (!(await formRef.current?.validateFields())) return;

    const vals = formRef.current?.getFieldsValue();
    const temp: Record<number, number> = {};

    vals.table.forEach((i: IManageDeptMaterialItem) => {
      temp[i.id] = i.deptId as number;
    });

    handleSubmit(temp);
  };

  const handleSubmit = async (values: any) => {
    try {
      setLoading(true);
      await saveManageDeptAllocationOfDataApi(values);
      onOk?.();
      handleCancel();
    } finally {
      setLoading(false);
    }
  };

  const getList = async () => {
    try {
      setListLoading(true);
      const data = await getManageDeptAllocationOfDataListApi(assessId);
      if (data) {
        formRef.current?.setFieldValue("table", data);
        setEditableKeys(data.map((i) => i.id));
      }
    } finally {
      setListLoading(false);
    }
  };

  useEffect(() => {
    open && getList();
  }, [open]);

  return (
    <Modal
      title="分配资料"
      okText="提交"
      cancelText="取消"
      maskClosable={false}
      open={open}
      width={640}
      okButtonProps={{
        disabled: loading,
      }}
      onOk={handleConfirm}
      onCancel={handleCancel}
      {...rest}
    >
      <ProForm
        labelCol={{ span: 4, offset: 2 }}
        formRef={formRef}
        submitter={false}
      >
        <EditableProTable<IManageDeptMaterialItem>
          name="table"
          rowKey="id"
          loading={listLoading}
          recordCreatorProps={{
            style: {
              display: "none",
            },
            // @ts-ignore
            record: () => ({}),
          }}
          columns={[
            {
              title: "标题",
              dataIndex: "name",
              editable: false,
            },
            {
              title: "是否必填",
              editable: false,
              render: (node, item) => {
                return item.isUpload === YES_OR_NO.YES ? "是" : "否";
              },
            },
            {
              title: "文件类型",
              editable: false,
              render: (node, item) => {
                const arr = item.suffix?.split(",") || [];
                return (
                  <>
                    {arr.map((i) => (
                      <Tag key={i}>{i}</Tag>
                    ))}
                  </>
                );
              },
            },
            {
              title: "责任部门",
              dataIndex: "deptId",
              width: 200,
              formItemProps: () => {
                return {
                  rules: [{ required: true, message: "此项为必填项" }],
                };
              },
              renderFormItem: () => (
                <Select
                  allowClear
                  options={deptList}
                  fieldNames={{ value: "id", label: "name" }}
                  placeholder="请选择"
                />
              ),
            },
          ]}
          editable={{
            type: "multiple",
            editableKeys,
          }}
        />
      </ProForm>
    </Modal>
  );
};
