import Taro from "@tarojs/taro";
// 多端上传文件，我们得引入 PostData 和 FileData 两个类
import { bluebookAiAgent } from "@/xiaolanbenlib/api/index";
import { EUploadFileScene } from '@/consts/enum'
import { getSimpleHeader } from "@/xiaolanbenlib/module/axios.js";
import {OSS_PUBLIC_BUCKET_NAME_KEY} from '@/xiaolanbenlib/constant'

export type TUploadResult = {
  publicUrl: string;
  file: string;
} |{trackingId:string, errors: {code:number, message: string}[]} | null

const _uploadFile = (
  tmpPath: string,
  fileName: string = "file",
  scene=EUploadFileScene.OTHER, 
  callback: (
    data: TUploadResult
  ) => void
) => {
  const bucketName = Taro.getStorageSync(OSS_PUBLIC_BUCKET_NAME_KEY)
  return Taro.uploadFile({
    url: `${bluebookAiAgent}api/v1/my/upload?bucketName=${bucketName}&scene=${scene}`,
    filePath: tmpPath,
    name: fileName,
    formData: {
      file: fileName,
    },
    header: {
      ...getSimpleHeader(),
    },
    success(res) {
      console.log(res)
      try {
        const r = JSON.parse(res.data);
        callback && callback(r);
      } catch (e) {
        console.error(e);
        callback(null);
      }
    },
    fail(err) {
      console.error(err);
      callback(null);
    },
  });
};

export async function uploadImage(tmpPath: string, scene: EUploadFileScene = EUploadFileScene.OTHER): Promise<TUploadResult> {
  return new Promise((resolve) => {
    _uploadFile(tmpPath, "file", scene, (r) => {
      resolve(r);
    });
  });
}
export async function uploadFile(
  tmpPath: string,
  scene: EUploadFileScene = EUploadFileScene.OTHER
): Promise<TUploadResult> {
  return new Promise((resolve, reject) => {
    _uploadFile(tmpPath, "file", scene, (data) => {
      resolve(data);
    });
  });
}
