import Taro from "@tarojs/taro";
// 多端上传文件，我们得引入 PostData 和 FileData 两个类
import { getToken, removeToken } from "./index";
import { bluebookAiAgent } from "@/xiaolanbenlib/api/index";
import { APP_VERSION, TARO_APP_ID } from "@/config/index";
// import { TaroAdapter } from "axios-taro-adapter";
import { useAppStore } from '@/store/appStore'
import { EUploadFileScene, EUploadFileBucketName } from '@/consts/enum'
import { getSimpleHeader } from "@/xiaolanbenlib/module/axios.js";
import {OSS_PUBLIC_BUCKET_NAME_KEY} from '@/xiaolanbenlib/constant'


const _uploadFile = (
  tmpPath: string,
  fileName: string = "file",
  scene=EUploadFileScene.OTHER, 
  callback: (
    data: {
      publicUrl: string;
      file: string;
    } | null
  ) => 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.log(e);
        callback(null);
      }
    },
    fail(err) {
      console.log(err);
      callback(null);
    },
  });
};

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