/**
 * 用于文件上传
 */
import { GET, POST } from "@mobileUI/utils/http";
import { proxy_api } from "@mobileUI/utils/env";
import Store from "@mobileUI/store";
//外呼
const getCosToken = (params) => {
  return GET(`${proxy_api[Store.node_env]}/api/cos/get_sts_token`, params);
};
// 获取对应小微欢迎码
const getVideoThumbnailLogo = (params) => {
  return POST(`${proxy_api[Store.node_env]}/api/cos/get_video_screen`, params);
};

import {
  TResponse,
  TCosInitParams,
  TCosUploadParams,
  TCosUploadResponse,
  TGetThumbnailLogoResponse,
} from "@mobileUI/typings/WlCosUpload";
import { judgeFileType } from "@mobileUI/utils/";
import WlLoading from "@mobileUI/components/WlLoading";

const onCosUpload = () => {
  let cos = null;
  const uploadParams: TCosUploadParams = {
    Bucket: "",
    Region: "",
    Key: "",
    StorageClass: "STANDARD",
    Body: null,
  };

  //生成随机数
  const getRandomSecret = (num: number) => {
    const t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",
      a = t.length;
    let n = "";
    for (let i = 0; i < num; i++) n += t.charAt(Math.floor(Math.random() * a));
    return n;
  };

  //获取十位的时间戳
  const getTimeStamp = (date?) => {
    return Math.floor(new Date(date).getTime() / 1000);
  };

  //获取密钥
  const getSDKToken = (file: File) => {
    return new Promise((resolve, reject) => {
      getCosToken({})
        .then(
          (res) => {
            const {
              access_secret_id,
              access_secret_key,
              expiration,
              security_token,
              config,
            } = res.data ?? {};
            const { bucket, region, tenant_id } = config;
            const fileType = file.name?.split(".")?.pop();
            const ExpiredTime = getTimeStamp(expiration);
            const StartTime = getTimeStamp(new Date());
            const random = getRandomSecret(7);
            uploadParams.Bucket = bucket;
            uploadParams.Region = region;
            //文件名是13位时间戳和7位随机数
            uploadParams.Key = `${tenant_id}/${StartTime}${random}.${fileType}`;
            const cosInitParams: TCosInitParams = {
              TmpSecretId: access_secret_id,
              TmpSecretKey: access_secret_key,
              SecurityToken: security_token,
              StartTime,
              ExpiredTime,
            };
            resolve(cosInitParams);
          },
          () => {
            reject({});
          },
        )
        .catch((err) => {
          reject(err);
        });
    });
  };

  //配置sdk
  const configSDK = (params: TCosInitParams) => {
    return new Promise((resolve) => {
      import("cos-js-sdk-v5").then((res) => {
        cos = new res.default({
          getAuthorization: (options, callback) => callback(params),
          FileParallelLimit: 10,
          ChunkParallelLimit: 10,
        });
        resolve("success");
      });
    });
  };

  //上传文件
  const onUpload = (file: File) => {
    return new Promise((resolve, reject) => {
      uploadParams.Body = file;
      cos.sliceUploadFile(
        {
          ...uploadParams,
          onTaskReady: function () {
            // onTaskReady: function (taskId) {
            /* 非必须 */
            console.log("--------onTaskReady--------", WlLoading);
            // WlLoading({
            //   type: "show",
            //   tips: "视频上传中...",
            //   needPercent: true,
            //   onCancel() {
            //     cos.cancelTask(taskId);
            //   },
            // });
          },
          onHashProgress: function (progressData) {
            /* 非必须 */
            console.log("--------onHashProgress--------");
            console.log(JSON.stringify(progressData));
          },
          onProgress: function (progressData) {
            /* 非必须 */
            console.log("--------onProgress--------");
            WlLoading({
              type: "changePercent",
              percent: progressData.percent * 100,
            });
          },
        },
        (err, data) => {
          err ? reject(err) : resolve(data);
        },
      );
    });
  };

  //获取当前第一帧视频图片
  const getVideoScreen = (videoUrl: string) => {
    return `${videoUrl}?ci-process=snapshot&time=0&format=jpg`;
  };

  //获取带播放按钮的图片
  const getThumbnailLogo = (screen_url, screen_name) => {
    return new Promise((resolve) => {
      getVideoThumbnailLogo({
        screen_url,
        screen_name,
      }).then((res) => {
        resolve(res);
      });
    });
  };

  //处理cos返回的参数
  const handleParams = (location: string, file: File) => {
    //将location数据进行替换
    const cos_file_name = file.name;
    const cos_file_size = file.size;
    const cos_file_type = file.type;
    const cos_url = `https://${location?.replace(
      "1304040775.cos.ap-shanghai.myqcloud.com",
      "cos.weiling.cn",
    )}`;

    return {
      cos_file_name,
      cos_file_size,
      cos_file_type,
      cos_url,
    };
  };

  //开始cos上传
  const onStartUpload = async (file: File) => {
    return new Promise((resolve, reject) => {
      getSDKToken(file).then(
        (sdkParams) => {
          configSDK(sdkParams as TCosInitParams).then(
            () => {
              onUpload(file).then(
                (data: TCosUploadResponse) => {
                  const params = handleParams(data.Location, file);
                  const { cos_url, cos_file_name } = params;
                  //如果是视频的话需要额外传视频首祯图和视频封面
                  if (judgeFileType(cos_url) === "video") {
                    const screen = getVideoScreen(cos_url);
                    getThumbnailLogo(screen, cos_file_name).then(
                      (res: TResponse) => {
                        const { screen: logo } =
                          (res.data as TGetThumbnailLogoResponse) ?? {};
                        WlLoading({
                          type: "hide",
                        });
                        resolve({
                          ...params,
                          cos_video_file_screen: screen,
                          cos_video_thumbnail_logo: logo,
                        });
                      },
                    );
                  } else {
                    WlLoading({
                      type: "hide",
                    });
                    resolve(params);
                  }
                },
                (error) => {
                  reject(error);
                },
              );
            },
            (error) => {
              reject(error);
            },
          );
        },
        (error) => {
          reject(error);
        },
      );
    });
  };

  return {
    onStartUpload,
  };
};

export default onCosUpload;
