import { reactive, watch, ref, defineEmits, defineExpose } from "vue";
import { ElMessage } from "element-plus";
import { upload, getUploadConfigInfo } from "../axios/model/user";
import axios from "axios";
import COS from "cos-js-sdk-v5";
interface UploadMixin {
  uploadMixinPath: string;
  uploadMixinType: string;
  uploadMixinCredentials: any;
  uploadMixinTimeStamp: number;
  upLoadMixinResult: object;
}
const uploadMixin: UploadMixin = {
  uploadMixinPath: "",
  uploadMixinType: "",
  uploadMixinCredentials: {},
  uploadMixinTimeStamp: 0,
  upLoadMixinResult: {},
};
interface CustomAxiosResponse {
  code: number;
  result: {
    bucketName: string;
    regionid: string;
    upLoadPath: string;
    uploadType: string;
    staticDomain: string;
    startTime: string;
    expiredTime: string;
    credentials: {
      tmpSecretId: string;
      tmpSecretKey: string;
      sessionToken: string;
    };
  };
}
export const upLoadFilesHander = (file: any) => {
  return new Promise((resolve) => {
    const loadHandler = ({ success, message }: any) => {
      if (!success) {
        ElMessage({
          message: `上传失败，请重新上传！`,
          type: "warning",
        });
      } else {
        resolve({ success: true, result: message });
      }
    };
    const obj = {
      file: file,
      onSuccess: ({ success, message }: any) => {
        loadHandler({ success, message });
      },
      onError: ({ success, message }: any) => {
        loadHandler({ success: false, message: "" });
      },
    };
    //进行上传
    upLoadHander(obj);
  });
};

export const upLoadHander = async (obj: any) => {
  const { file } = obj;
  const fileName = file.name.split(".");
  const fileInfo = {
    fileTyle: fileName.length > 1 ? fileName[fileName.length - 1] : "",
    fileName: fileName[0],
    biz: obj?.data?.biz || "temp",
    file: file,
  };
  const none = async function hander(noCredentials: boolean) {
    // const res:CustomAxiosResponse = reactive({
    //   code: 0,
    //   result: {
    //     bucketName: "",
    //     regionid: "",
    //     upLoadPath: "",
    //     uploadType: "",
    //     staticDomain: "",
    //     startTime: "",
    //     expiredTime: "",
    //     credentials: {
    //       tmpSecretId: "",
    //       tmpSecretKey: "",
    //       sessionToken: "",
    //     },
    //   },
    // });
    let staticDomain = "";
    let resResult = true;
    //noCredentials变量控制是否走对象存储
    if (noCredentials) {
      const query = {};
      const res: any = await getUploadConfigInfo(query);
      if (res.code === 200 && res.result) {
        const result = res.result;
        uploadMixin.uploadMixinPath = result.upLoadPath;
        uploadMixin.uploadMixinType = result.uploadType;
        staticDomain = result.staticDomain || "https://cdn.tikcos.cn";
        if (uploadMixin.uploadMixinType === "txcos") {
          const ress = res.result.response;
          const credentials = ress.credentials;
          uploadMixin.uploadMixinCredentials = {
            TmpSecretId: credentials?.tmpSecretId,
            TmpSecretKey: credentials?.tmpSecretKey,
            SecurityToken: credentials?.sessionToken,
            StartTime: ress?.startTime,
            ExpiredTime: ress?.expiredTime,
          };
        }
      } else {
        resResult = false;
      }
    }
    //resResult判断接口是否正常
    if (resResult) {
      const query = {};
      // const res: any = await getUploadConfigInfo(query);
      const result: any = uploadMixin.upLoadMixinResult;
      if (uploadMixin.uploadMixinType === "txcos") {
        //走对象存储
        const cos = new COS({
          getAuthorization: (options, callback) => {
            callback(uploadMixin.uploadMixinCredentials);
          },
        });

        const tempFolder = fileInfo.biz === "temp" ? "" : `${fileInfo.biz}/`;
        const folder = `${fileInfo.fileName}_${new Date().getTime()}.${
          fileInfo.fileTyle
        }`;
        cos.putObject(
          {
            Bucket: result.bucketName || "tikcos-1257774783",
            Region: result.regionid || "ap-guangzhou",
            Key: uploadMixin.uploadMixinPath + tempFolder + folder,
            Body: fileInfo.file,
            onProgress: function (progressData) {
              obj.onProgress(progressData);
            },
          },
          (err, data) => {
            if (!err && data.statusCode === 200) {
              const imgurl = `${staticDomain}/${uploadMixin.uploadMixinPath}${tempFolder}${folder}`;

              obj.onSuccess({ success: true, message: imgurl });
            } else {
              obj.onError({ success: false, message: err || "图片上传失败" });
            }
          }
        );
      } else {
        //走系统上传
        let VITE_USER_APP_API_URL = import.meta.env.VITE_USER_APP_API_URL;
        let newFile = fileInfo.file;
        if (/[\u4e00-\u9fa5]/.test(newFile.name)) {
          const folder = newFile.name.replace(/[\u4e00-\u9fa5]{1,}/g, "_");
          newFile = new File([newFile], folder, { type: newFile.type });
        }
        let formData = new FormData();
        formData.append("biz", fileInfo.biz);
        formData.append("file", newFile);
        const uploadRes = await axios.post(
          `${VITE_USER_APP_API_URL}/common/uploadFile`,
          formData,
          {
            headers: { ...obj.headers },
            processData: false,
            contentType: false,
            async: false,
          }
        );
        let res = uploadRes.data;
        console.log(res, "uploadRes");
        if (res.code == "200" && res.data) {
          //保存绝对路径，不然小程序会有问题
          let url = res.data;
          // console.log(url,'url')
          // url = data.message.replaceAll("//", "/");
          // const pre = url.startsWith("/") ? "" : "/";
          // url = `http://${VUE_APP_API_URL}/sys/common/static` + pre + url;
          // console.log(url, "图片上传成功");
          obj.onSuccess({ success: true, message: url });
        } else {
          obj.onError({
            success: false,
            message: res.description || "图片上传失败",
          });
        }
      }
    } else {
      obj.onError({
        success: false,
        message: "服务接口报错",
      });
    }
  };
  none(false);
};
