import { setVideo, setVideoRefresh } from "@/request/api.js";
import { ElLoading, ElMessage } from "element-plus";

export default function useAliYunUpload({
  addFileSuccess,
  onUploadstarted,
  onUploadSucceed,
  onUploadFailed,
  onUploadCanceled,
  onUploadProgress,
  onUploadTokenExpired,
  onUploadEnd,
}) {
  let loading;
  const uploader = new window.AliyunUpload.Vod({
    timeout: 60000,
    partSize: 1048576,
    parallel: 5,
    retryCount: 3,
    retryDuration: 2,
    region: "cn-shanghai",
    userId: "1663991162946873",
    addFileSuccess(uploadInfo) {
      addFileSuccess && addFileSuccess(uploadInfo);
    },
    async onUploadstarted(uploadInfo) {
      onUploadstarted && onUploadstarted();
      let uploadAddress;
      let uploadAuth;
      let videoId;
      if (!uploadInfo.videoId) {
        const resData = await setVideo({
          Title: uploadInfo.file.name,
          FileName: uploadInfo.file.name,
        });
        uploadAddress = resData.data.uploadAddress;
        uploadAuth = resData.data.uploadAuth;
        videoId = resData.data.videoId;
      } else {
        const resData = await setVideoRefresh({
          Title: uploadInfo.file.name,
          FileName: uploadInfo.file.name,
          VideoId: uploadInfo.videoId,
        });
        uploadAddress = resData.data.uploadAddress;
        uploadAuth = resData.data.uploadAuth;
        videoId = resData.data.videoId;
      }
      uploader.setUploadAuthAndAddress(
        uploadInfo,
        uploadAuth,
        uploadAddress,
        videoId
      );
      loading = ElLoading.service({
        lock: true,
        text: "加载中...",
        background: "rgba(0, 0, 0, 0.5)",
      });
    },
    onUploadSucceed(uploadInfo) {
      loading.close();
      onUploadSucceed && onUploadSucceed(uploadInfo);
    },
    onUploadFailed(uploadInfo, code, message) {
      ElMessage.success("上传失败，请重新上传");
      onUploadFailed && onUploadFailed(uploadInfo, code, message);
    },
    onUploadCanceled(uploadInfo, code, message) {
      onUploadCanceled && onUploadCanceled(uploadInfo, code, message);
    },
    onUploadProgress(uploadInfo, totalSize, progress) {
      onUploadProgress && onUploadProgress(uploadInfo, totalSize, progress);
    },
    onUploadTokenExpired(uploadInfo) {
      onUploadTokenExpired && onUploadTokenExpired(uploadInfo);
    },
    onUploadEnd(uploadInfo) {
      onUploadEnd && onUploadEnd(uploadInfo);
    },
  });
  return uploader;
}
