<template>
  <a-upload
    ref="uploadBtn"
    :headers="headers"
    :custom-request="customRequest"
    :disabled="disabled || loading"
    :before-upload="beforeUpload"
    :file-list="fileList"
    @change="fileChange"
  >
    <qm-button :loading="loading" :icon="h(ImportOutlined)">
      {{ btnText }}
    </qm-button>
  </a-upload>
</template>
<script name="ImportButton" lang="ts" setup>
import { ref, h, Ref, Reactive } from "vue";
import type { UploadProps } from "@qmth/ui";
import { getFileMD5 } from "@/utils/crypto";
import { request } from "@/utils/request";
import { ImportOutlined } from "@ant-design/icons-vue";
import type { AxiosError, AxiosProgressEvent } from "axios";

const emit = defineEmits(["success", "fileChange"]);
const props = withDefaults(
  defineProps<
    {
      maxSize?: number;
      disabled?: boolean;
      fileParamsName?: string;
      btnText?: string;
      uploadParams?: Record<string, any> | Ref | Reactive<any>;
    } & UploadProps
  >(),
  {
    maxSize: 20 * 1024 * 1024,
    fileParamsName: "file",
    disabled: false,
    btnText: "点击导入",
    uploadParams: () => ({}),
  }
);
const fileList = ref<UploadProps["fileList"]>([]);
const uploadBtn = ref();
const headers = ref<any>({ "Content-Type": "multipart/form-data", md5: "" });
const loading = ref(false);
const uploadProgress = ref(0);

const beforeUpload: UploadProps["beforeUpload"] = async (file) => {
  if (file.size > props.maxSize) {
    window.$message.error("文件大小不能大于20M！");
    return false;
  }
  if (!props.action) {
    // fileList.value = [...(fileList.value || []), file];
    fileList.value = [file]; //暂时只考虑单文件上传
    return false;
  }
  const md5 = await getFileMD5(file);
  headers.value.md5 = md5;

  return true;
};

const customRequest: UploadProps["customRequest"] | undefined = !props.action
  ? undefined
  : (option) => {
      const { file, data } = option;
      const formData = new FormData();
      const paramData: Record<string, any> = data || {};
      Object.entries(paramData).forEach(([k, v]) => {
        formData.append(k, v);
      });
      formData.append(props.fileParamsName, file as File);

      request({
        url: option.action as string,
        data: formData,
        headers: option.headers,
        onUploadProgress: (data: AxiosProgressEvent) => {
          uploadProgress.value = data.total
            ? Math.floor((100 * data.loaded) / data.total)
            : 0;
        },
      })
        .then((res: any) => {
          // 所有excel导入的特殊处理
          if (res.hasError) {
            const failRecords = res.failRecords;
            const message = failRecords
              .map((item: any) => `第${item.lineNum}行：${item.msg}`)
              .join("。");

            window.$message.error(message);
            return;
          }
          emit("success");
        })
        .catch((error: AxiosError<{ message: string }> | null) => {
          window.$message.error(error?.response?.data?.message || "上传失败！");
        });
    };

const fileChange = ({ file }: any) => {
  //   const formData = new FormData();
  //   const paramData: any = isRef(props.uploadParams)
  //     ? { ...(props.uploadParams?.value || {}) }
  //     : { ...props.uploadParams };
  //   Object.keys(paramData).forEach((key: string) => {
  //     formData.append(key, paramData[key]);
  //   });
  //   formData.append(props.fileParamsName, file as File);
  emit("fileChange", file as File);
};
</script>
<style lang="less" scoped></style>
