import { Apis } from "@/gen/Apis";

// #region pre_upload
export interface IPreUploadResult {
  success: boolean;
  data: {
    cosHost: string;
    cosKey: string;
    authorization: string;
  };
}

export interface IPreUploadData {
  /**
   * -
   */
  file_ext?: string;
}

const handlePreUpload = async (val: {
  file_ext: string;
  upload_type: string;
}) => {
  const res = await Apis.Common.Auth.PreUpload(val);
  return res;
};

export const upload = (count = 1, size = 2, mediaType = ["image"]) => {
  return new Promise<{ url: string; status: string; type: string | undefined }>(
    (resolve, reject) => {
      let currentCount = 0;
      let ArrImgList: any = [];
      uni.chooseMedia({
        count: count > 9 ? 9 : count, //默认9
        mediaType: mediaType as ["image"],
        sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
        success: async function (i) {
          console.log("filePath", i.tempFiles);
          i.tempFiles?.map((k: any) => {
            console.log(k, "??kj");
            const filePath = k.tempFilePath;
            const extIndex = filePath.lastIndexOf(".");
            const filePathName = filePath.substring(
              filePath.lastIndexOf(".") + 1
            );
            const fileExt = extIndex >= -1 ? filePath.substr(extIndex + 1) : "";
            const img_size = i.tempFiles[0].size;
            const max_size = 1024 * 1024 * (size || 2); // 默认2M
            if (img_size > max_size) {
              uni.showToast({
                title: `${filePathName}文件大小不能超过${size}M`,
                icon: "none",
              });
              return false;
            }
            handlePreUpload({
              file_ext: fileExt,
              upload_type: k?.fileType,
            }).then((res) => {
              if (res.success) {
                const prefix = res.data.cosHost;
                const key = res.data.cosKey;
                const wxfs = uni.getFileSystemManager();
                const timestamp = Date.now();
                wxfs.readFile({
                  filePath: filePath,
                  complete(e) {
                    if (e?.errMsg === "readFile:ok") {
                      currentCount = currentCount + 1;
                      const url: string = "https://" + prefix + key;
                      let data = {
                        url: url,
                        status: "done",
                        type: `${k?.fileType}/${filePath.split(".")[1]}`,
                        uid: timestamp,
                        size: k?.size,
                      };
                      console.log(data, "url");
                      ArrImgList?.push(data);
                    }
                    uni.showLoading({
                      title: `共${i.tempFiles?.length}张/${currentCount}张`,
                      mask: true,
                    });
                    if (currentCount === i.tempFiles?.length) {
                      setTimeout(() => {
                        uni.hideLoading();
                      }, 500);
                    }
                    console.log("complete", e);
                  },
                  success: function (fileRes) {
                    uni.request({
                      url: "https://" + prefix + key,
                      method: "PUT",
                      header: {
                        "Content-Type": "image/" + fileExt,
                        Authorization: res.data.authorization,
                      },
                      data: fileRes.data,
                      success: function success(res) {
                        console.log(res, "resUpadte");
                        if (res.statusCode !== 200) {
                          uni.showToast({
                            title: "上传失败",
                            icon: "none",
                          });
                          reject();
                        } else {
                          resolve(ArrImgList);
                        }
                      },
                      fail: function fail() {
                        uni.showToast({
                          title: "上传失败",
                          icon: "none",
                        });
                        reject();
                      },
                    });
                  },
                });
              }
            });
          });
        },
      });
    }
  );
};
