import {getOssPolicyInfo} from "@/api";
import {useUserStore} from "@/store/modules/user";
import OSS from "ali-oss";


type Options = {
  width: number,
  height: number,
  // type null(不传就是默认尺寸全等) | ratio (尺寸比例相等即可)
  type?: string,
  file: File,
  callBack?: Function
}


type Policy = {
  bucket: string,
  key: string,
  keyId: string,
  keySecret: string,
  region: string,
  token: string,
}

/**
 * 上传文件
 * @returns
 */
export function useUpload() {

  const userStore = useUserStore();

  // header
  let header = {
    accessToken: userStore.getToken,
  };

  let policy: Policy = {
    bucket: "",
    key: "",
    keyId: "",
    keySecret: "",
    region: "",
    token: ""
  };

  const init = () => {

  };

  /**
   * 获取oss配置
   */
  const getOssPolicy = async () => {
    policy = await getOssPolicyInfo();
    return policy;
  };

  /**
   * 获取header
   */
  const getHeader = () => {
    header = {
      accessToken: userStore.getToken,
    };
    return header;
  };

  /**
   * 自定义上传
   * @param customRequestOptions
   * @param callback
   */
  // const customRequest = async (customRequestOptions, callback?: (arg0: string | undefined) => any) => {
  //   await getOssPolicy();
  //   const { file, withCredentials, onFinish, onError, onProgress } = customRequestOptions;
  //   // 生成随机文件名
  //   const getRandomFileName = () => {
  //     const randomNum = Math.floor(Math.random() * 10000);
  //     const timestamp = new Date().format('yyyyMMddhhmmss');
  //     const extension = file.name.split(".").pop();
  //     return `${timestamp}-${randomNum}.${extension}`;
  //   }
  //   const key: string = policy.dir + getRandomFileName();
  //
  //   return new Promise((resolve, reject) => {
  //     http.uploadFile({
  //         url: policy.uploadHost,
  //         method: RequestEnum.POST,
  //         timeout: 1000 * 60 * 10,
  //         withCredentials: withCredentials,
  //         onUploadProgress: (obj) => {
  //           onProgress && onProgress({ percent: Math.ceil((obj.progress || 0) * 100) });
  //         }
  //       },
  //       {
  //         data: {
  //           OSSAccessKeyId: policy.accessKeyId,
  //           signature: policy.signature,
  //           policy: policy.policy,
  //           key: key,
  //           success_action_status: 200
  //         },
  //         file: file.file as File
  //       })
  //       .then(res => {
  //         console.log("res", res);
  //         onFinish && onFinish();
  //         callback && callback(`${policy.host}/${key}`);
  //         resolve(`${policy.host}/${key}`);
  //       })
  //       .catch((error) => {
  //         callback && callback(undefined);
  //         onError && onError();
  //         reject(error);
  //       });
  //   });
  // };

  const aliOssUpload = async (customRequestOptions: { file: File; }, callback?: (arg0: string | undefined) => any) => {
    await getOssPolicy();
    const { file } = customRequestOptions;
    // 生成随机文件名
    const getRandomFileName = () => {
      const randomNum = Math.floor(Math.random() * 10000);
      const timestamp = new Date().format('yyyyMMddhhmmss');
      const extension = file.name.split(".").pop();
      return `${policy.key}/${timestamp}-${randomNum}.${extension}`;
    }

    const client = new OSS({
      // yourRegion填写Bucket所在地域。以华东1（杭州）为例，yourRegion填写为oss-cn-hangzhou。
      region: policy.region,
      // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
      accessKeyId: policy.keyId,
      accessKeySecret: policy.keySecret,
      // 从STS服务获取的安全令牌（SecurityToken）。
      stsToken: policy.token,
      // 填写Bucket名称。
      bucket: policy.bucket,
    });
    try {
      // 填写Object完整路径。Object完整路径中不能包含Bucket名称。
      // 您可以通过自定义文件名（例如exampleobject.txt）或文件完整路径（例如exampledir/exampleobject.txt）的形式实现将数据上传到当前Bucket或Bucket中的指定目录。
      // data对象可以自定义为file对象、Blob数据或者OSS Buffer。
      const options = {
        meta: { temp: "demo" },
        mime: "json",
        headers: { "Content-Type": "text/plain" },
      };
      const result = await client.put(getRandomFileName(), file, options);
      callback && callback(result?.url);
      return Promise.resolve()
    } catch (e) {
      console.log(e);
    }

    return Promise.resolve()
  }

  /**
   * 图片校验
   * @param options
   */
  const uploadImgBefore = (options: Options): Promise<boolean> => {
    const callBack = (flag: boolean) => {
      if (options.callBack) {
        options.callBack(flag);
      }
    };
    const getPercent = (num: number, total: number) => {
      num = parseFloat(num);
      total = parseFloat(total);
      if (isNaN(num) || isNaN(total)) {
        return "-";
      }
      return total <= 0 ? "0%" : (Math.round(num / total * 10000) / 100.00) + "%";
    };

    return new Promise((resolve, reject) => {
      try {
        const reader = new FileReader();  //通过FileReader类型读取文件中的数据（异步文件读取）
        reader.onload = (e) => {
          const data = e.target?.result;  //返回文件框内上传的对象
          //加载图片获取图片真实宽度和高度
          const image = new Image();
          image.onload = () => {
            const width = image.width;
            const height = image.height;
            const flag: boolean =
              (options.type === "ratio" && getPercent(options.width, options.height) === getPercent(width, height))
              ||
              (width === options.width && height === options.height);
            callBack(flag);
            return resolve(flag);
          };
          //img.src 应该是放在 onload 方法后边的, 因为当image的src发生改变，浏览器就会跑去加载这个src里的资源,先告诉浏览器图片加载完要怎么处理，再让它去加载图片
          image.src = data as string;
        };
        //读取文件并将文件数据以URL形式保存到result属性中。 读取图像常用
        reader.readAsDataURL(options.file);
      } catch (e) {
        console.error(e);
        reject(e);
      }
    });
  };


  init();
  return { uploadImgBefore, getOssPolicy, getHeader, aliOssUpload };
}
