import { FC, useEffect, useState } from "react";
import { Button, Empty, Modal, ModalProps, Table, Tag } from "antd";
import { MaterialType, YES_OR_NO } from "@/types";
import { getBaseURL } from "@dage/service";
import { deleteFileApi, getFileListApi, saveManageFileApi } from "@/api";
import { downloadFile, beforeUpload } from "@/utils";
import {
  DageFileResponseType,
  DageLoading,
  DageTableActions,
  DageUpload,
  DageUploadConsumer,
  DageUploadProvider,
  DageUploadType,
} from "@dage/pc-components";
import classNames from "classnames";
import style from "./index.module.scss";

export interface IndexDetailModalProps extends Omit<ModalProps, "onOk"> {
  id: number;
  title: string;
  onCancel?: () => void;
  onOk?: (val: any) => void;
}

export const IndexDetailModal: FC<IndexDetailModalProps> = ({
  open,
  id,
  title,
  onOk,
  onCancel,
  ...rest
}) => {
  const baseUrl = getBaseURL();
  const [loading, setLoading] = useState(false);
  const [list, setList] = useState<MaterialType[]>([]);
  // 已上传附件映射
  const [uploadedFileMap, setUploadedFileMap] = useState<
    Record<number, MaterialType[]>
  >({});

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

  const saveManageFile = async (
    item: MaterialType,
    list: DageFileResponseType[]
  ) => {
    // @ts-ignore
    const li = list.filter((i) => i.status === "done" && !i.uploaded);

    for (let i = 0; i < li.length; i++) {
      const file = li[i];

      if (!file.response) return;

      await saveManageFileApi({
        name: file.name,
        fileName: file.response.fileName,
        filePath: file.response.filePath,
        level: 2,
        suffix: item.suffix,
        parentId: item.id,
        module: "fill-norm",
        moduleId: id,
      });
      // @ts-ignore
      file.uploaded = true;
    }

    getList();
  };

  const getList = async () => {
    try {
      setLoading(true);
      const data = await getFileListApi(id, "norm");
      setList(data.filter((i) => i.module === "norm"));

      const temp: typeof uploadedFileMap = {};
      data
        .filter((i) => i.module === "fill-norm")
        .forEach((item) => {
          if (!item.parentId) return;
          if (Array.isArray(temp[item.parentId]))
            temp[item.parentId].push(item);
          else temp[item.parentId] = [item];
        });
      setUploadedFileMap(temp);
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteFile = async (id: number) => {
    await deleteFileApi(id);
    getList();
  };

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

  return (
    <Modal
      className={style.modal}
      title={title}
      open={open}
      width={900}
      footer={null}
      onCancel={handleCancel}
      {...rest}
    >
      {loading && <DageLoading />}

      {!list.length && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}

      {list.map((item) => {
        const isUpload = item.isUpload === YES_OR_NO.YES;

        return (
          <div key={item.id} className={style.fileUpload}>
            <div className={style.fileUploadHeader}>
              <div className={style.fileUploadHeaderInfo}>
                <Tag color={isUpload ? "red" : ""}>
                  {isUpload ? "必填" : "选填"}
                </Tag>
                <h3>
                  {item.name} | {item.suffix || "*"}
                </h3>
              </div>
              <Button
                type="primary"
                ghost
                onClick={() =>
                  downloadFile(
                    baseUrl + process.env.REACT_APP_IMG_PUBLIC + item.filePath,
                    item.fileName
                  )
                }
              >
                下载模板
              </Button>
              <DageUploadProvider>
                <DageUploadConsumer>
                  {(res) => (
                    <DageUpload
                      className={classNames(style.uploadBtn, "no-list")}
                      dType={DageUploadType.DOC}
                      action="/api/cms/fill/file/upload"
                      // @ts-ignore
                      accept={item.suffix}
                      // @ts-ignore
                      beforeUpload={beforeUpload.bind(undefined, item.suffix)}
                      onChange={saveManageFile.bind(undefined, item)}
                    >
                      <Button type="primary" ghost loading={res?.uploading}>
                        上传附件
                      </Button>
                    </DageUpload>
                  )}
                </DageUploadConsumer>
              </DageUploadProvider>
            </div>

            <Table
              rowKey="id"
              className="cus-table"
              pagination={false}
              dataSource={uploadedFileMap[item.id]}
              columns={[
                {
                  title: "附件名称",
                  dataIndex: "fileName",
                  align: "center",
                },
                {
                  title: "责任部门",
                  dataIndex: "deptName",
                  align: "center",
                },
                {
                  title: "上传用户",
                  dataIndex: "creatorName",
                  align: "center",
                },
                {
                  title: "上传时间",
                  dataIndex: "updateTime",
                  align: "center",
                },
                {
                  title: "评定结果",
                  dataIndex: "creatorName",
                  align: "center",
                },
                {
                  title: "评定意见",
                  dataIndex: "updateTime",
                  align: "center",
                },
                {
                  title: "操作",
                  align: "center",
                  render: (val) => (
                    <DageTableActions
                      renderBefore={
                        <Button
                          size="small"
                          type="link"
                          onClick={() =>
                            downloadFile(
                              baseUrl +
                                process.env.REACT_APP_IMG_PUBLIC +
                                item.filePath,
                              item.fileName
                            )
                          }
                        >
                          下载
                        </Button>
                      }
                      showEdit={false}
                      onDelete={handleDeleteFile.bind(undefined, val.id)}
                    />
                  ),
                },
              ]}
            />
          </div>
        );
      })}
    </Modal>
  );
};
