var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/dataSourceComponents/fields/Upload/shopUploadServe.ts
var shopUploadServe_exports = {};
__export(shopUploadServe_exports, {
  dataURLtoFile: () => dataURLtoFile,
  filetypes: () => filetypes,
  formatFileName: () => formatFileName,
  getImageWidth: () => getImageWidth,
  getPolicy: () => getPolicy,
  getPolicyFile: () => getPolicyFile,
  getSignature: () => getSignature,
  getVideoCover: () => getVideoCover,
  uploadFile: () => uploadFile,
  uploadFileAli: () => uploadFileAli,
  uploadFileTencent: () => uploadFileTencent
});
module.exports = __toCommonJS(shopUploadServe_exports);
var import_dayjs = __toESM(require("dayjs"));
var import_utils = require("@pisell/utils");
var import_vod_js_sdk_v6 = __toESM(require("vod-js-sdk-v6"));
var import_utils2 = require("../../../table/utils");
var filetypes = {
  "vnd.openxmlformats-officedocument.wordprocessingml.document": {
    icon: "iconword",
    type: "applicatio",
    format: "docx"
  },
  "vnd.openxmlformats-officedocument.spreadsheetml.sheet": {
    icon: "iconxlsx",
    type: "applicatio",
    format: "xlsx"
  },
  csv: {
    icon: "icontxt",
    type: "text",
    format: "csv"
  },
  "vnd.ms-excel": {
    icon: "iconxlsx",
    type: "applicatio",
    format: "xls"
  },
  msword: {
    icon: "iconword",
    type: "applicatio",
    format: "doc"
  },
  pdf: {
    icon: "iconpdf",
    type: "applicatio",
    format: "pdf"
  }
};
var getPolicy = () => import_utils2.request.getRequest().get("/shop/ali-upload/policy", { type: "image" });
var getPolicyFile = () => import_utils2.request.getRequest().get("/shop/ali-upload/policy", { type: "file" });
var getImageWidth = async (file) => {
  return new Promise((resolve, reject) => {
    try {
      let url = window.URL || window.webkitURL;
      let img = new Image();
      img.src = url.createObjectURL(file);
      img.onload = function() {
        resolve({ width: img.width, height: img.height });
      };
      img.onerror = function() {
        resolve({ width: 0, height: 0 });
      };
    } catch (err) {
      resolve({ width: 0, height: 0 });
    }
  });
};
var formatFileName = async (file) => {
  var _a;
  const imgSize = await getImageWidth(file);
  let _suffix = ((file == null ? void 0 : file.type) || "image/png").split("/")[1];
  let fileType = (_a = filetypes[_suffix]) == null ? void 0 : _a.format;
  if (fileType) {
    _suffix = fileType;
  }
  return (0, import_dayjs.default)().format("YYYY_MM_DD_HH_mm_ss_SSS") + "_" + (0, import_utils.getUniqueId)() + "__" + imgSize.width + "_" + imgSize.height + "__." + _suffix;
};
var uploadFileAli = async (file) => {
  const policyData = await getPolicy();
  let _name = await formatFileName(file);
  let formData = new FormData();
  formData.append("Content-Type", "multipart/form-data");
  formData.append("OSSAccessKeyId", policyData.data.access_key_id);
  formData.append("policy", policyData.data.policy);
  formData.append("Signature", policyData.data.signature);
  formData.append("key", policyData.data.dir + _name);
  formData.append("success_action_status", "200");
  formData.append("callback", policyData.data.callback);
  formData.append("file", file);
  return import_utils2.request.getRequest().post(policyData.data.cdn_domain, formData);
};
var uploadAli = async (file) => {
  return uploadFileAli(file);
};
var getObjectURL = (file) => {
  var url = null;
  if (window.createObjectURL != void 0) {
    url = window.createObjectURL(file);
  } else if (window.URL != void 0) {
    url = window.URL.createObjectURL(file);
  } else if (window.webkitURL != void 0) {
    url = window.webkitURL.createObjectURL(file);
  }
  return url;
};
var dataURLtoFile = (dataurl, filename) => {
  var arr = dataurl.split(","), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime });
};
var getVideoCover = (file) => {
  const url = getObjectURL(file);
  return new Promise(function(resolve, reject) {
    try {
      let _video = document.createElement("video");
      _video.setAttribute("crossOrigin", "anonymous");
      _video.setAttribute("preload", "auto");
      _video.muted = true;
      _video.setAttribute("autoplay", "autoplay");
      _video.src = url;
      _video.addEventListener("loadeddata", function() {
        this.currentTime = 1;
      });
      _video.addEventListener("seeked", function() {
        this.width = this.videoWidth;
        this.height = this.videoHeight;
        if (this.width === 0 || this.height === 0) {
          return resolve("");
        }
        let canvas = document.createElement("canvas");
        let ctx = canvas.getContext("2d");
        canvas.width = this.width;
        canvas.height = this.height;
        if (ctx === null) return;
        ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
        let _cover = canvas.toDataURL("image/jpeg", 1);
        let _cover_name = file.name.split(".")[0] + "_cover.jpeg";
        resolve(dataURLtoFile(_cover, _cover_name));
      });
    } catch (err) {
      reject();
    }
  });
};
var getSignature = () => import_utils2.request.getRequest().get("/shop/core/tx-video-sign").then((res) => {
  var _a;
  return (_a = res == null ? void 0 : res.data) == null ? void 0 : _a.sign;
});
var uploadFileTencent = async (file) => {
  return new Promise(async (resolve, reject) => {
    try {
      const coverFile = await getVideoCover(file);
      console.log(coverFile);
      const coverData = await uploadFileAli(coverFile);
      const tcVod = new import_vod_js_sdk_v6.default({
        // 传入鉴权函数
        getSignature
      });
      const uploader = tcVod.upload({
        mediaFile: file,
        mediaName: file.name
      });
      uploader.on("media_upload", (info) => {
      });
      uploader.done().then((doneResult) => {
        var _a, _b;
        let res = {
          status: true,
          data: {
            ...doneResult,
            cover: {
              ...doneResult == null ? void 0 : doneResult.cover,
              url: (_a = coverData == null ? void 0 : coverData.data) == null ? void 0 : _a.url
            },
            url: (_b = doneResult == null ? void 0 : doneResult.video) == null ? void 0 : _b.url
          }
        };
        return resolve(res);
      }).catch((err) => {
        return reject(err);
      });
    } catch (err) {
      return reject(err);
    }
  });
};
var uploadTencent = async (file) => {
  const res = await uploadFileTencent(file);
  return res;
};
var uploadFile = (file) => {
  if (file.type.startsWith("image")) {
    return uploadAli(file);
  } else if (file.type.startsWith("video")) {
    return uploadTencent(file);
  } else {
    return uploadAli(file);
  }
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  dataURLtoFile,
  filetypes,
  formatFileName,
  getImageWidth,
  getPolicy,
  getPolicyFile,
  getSignature,
  getVideoCover,
  uploadFile,
  uploadFileAli,
  uploadFileTencent
});
