import { Modal, ModalProps, Select, Tag } from "antd";
import { FC, useEffect, useMemo, useRef, useState } from "react";
import style from "./index.module.scss";
import {
  EditableProTable,
  ProForm,
  ProFormInstance,
} from "@ant-design/pro-components";
import {
  IAssIndexDetail,
  IManageDeptItem,
  IManageDeptMaterialItem,
  MaterialType,
  YES_OR_NO,
} from "@/types";
import { saveManageDeptAllocationOfDataApi } from "@/api";

export interface AllocationOfIndexDataModalProps
  extends Omit<ModalProps, "onOk"> {
  indexList: IAssIndexDetail[];
  deptList: IManageDeptItem[];
  onCancel?: () => void;
  onOk?: () => void;
}

export const AllocationOfIndexDataModal: FC<
  AllocationOfIndexDataModalProps
> = ({ open, indexList, deptList, onOk, onCancel, ...rest }) => {
  const formRef = useRef<ProFormInstance<any>>();
  const [loading, setLoading] = useState(false);
  const list = useMemo(
    () => indexList.filter((item) => Boolean(item.materials.length)),
    [indexList]
  );

  useEffect(() => {
    if (!list.length) return;

    list.forEach((item, index) => {
      formRef.current?.setFieldValue("table" + index, item.materials);
    });
  }, [list]);

  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> = {};

    Object.keys(vals).forEach((key) => {
      const arr = vals[key];
      arr.forEach((i: IManageDeptMaterialItem) => {
        temp[i.id] = i.deptId as number;
      });
    });

    try {
      setLoading(true);
      await saveManageDeptAllocationOfDataApi(temp);
      onOk?.();
      handleCancel();
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal
      title="分配指标"
      okText="提交"
      cancelText="取消"
      open={open}
      width={960}
      okButtonProps={{
        disabled: loading,
      }}
      maskClosable={false}
      onOk={handleConfirm}
      onCancel={handleCancel}
      {...rest}
    >
      <p style={{ marginBottom: 15 }}>
        以下指标由多个部门负责，需为关联资料上传指定唯一部门
      </p>

      <ProForm
        labelCol={{ span: 4, offset: 2 }}
        formRef={formRef}
        submitter={false}
      >
        {list.map((item, index) => (
          <div className={style.pane} key={item.id}>
            <p>{item.name}</p>

            <EditableProTable<MaterialType>
              name={`table${index}`}
              rowKey="id"
              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,
                  width: 300,
                  render: (node, item) => {
                    const arr = item.suffix?.split(",") || [];
                    return (
                      <>
                        {arr.map((i) => (
                          <Tag key={i}>{i}</Tag>
                        ))}
                      </>
                    );
                  },
                },
                {
                  title: "责任部门",
                  dataIndex: "deptId",
                  width: 260,
                  formItemProps: () => {
                    return {
                      rules: [{ required: true, message: "此项为必填项" }],
                    };
                  },
                  renderFormItem: () => (
                    <Select
                      allowClear
                      options={deptList}
                      fieldNames={{ value: "id", label: "name" }}
                      placeholder="请选择"
                    />
                  ),
                },
              ]}
              editable={{
                type: "multiple",
                editableKeys: item.materials.map((i) => i.id),
              }}
            />
          </div>
        ))}
      </ProForm>
    </Modal>
  );
};
