import Taro from "@tarojs/taro";
import { uploadImage } from "@/utils/http";
import { EUploadFileScene } from "@/consts/enum";


const MAX_IMAGE_SIZE = 10;

export const getNewAvatarPic = (cb: (result: string)=> void)=> {
  Taro.chooseMedia({
    count: 1,
    mediaType: ["image"],
    sourceType: ["album", "camera"],
    async success(r) {
      const tempFile = r.tempFiles[0];
      if (MAX_IMAGE_SIZE && tempFile.size > MAX_IMAGE_SIZE * 1024 * 1024) {
        Taro.showToast({
          title: `文件不能超过${MAX_IMAGE_SIZE}MB`,
          icon: "none",
        });
        return;
      }

      Taro.cropImage({
        src: tempFile.tempFilePath,
        cropScale: "9:16",
        success: async (cropRes) => {
          const path = cropRes.tempFilePath;
          Taro.showLoading();

          const response = await uploadImage(path, EUploadFileScene.AVATAR);
          Taro.hideLoading();
          if (response?.publicUrl) {
            cb(response?.publicUrl)
          }
        },
      });
    },
  });
}

// 上传新形象，成功后跳转至 ai 生成页
export const uploadAndNavToGenNewAvatar = () => {
  getNewAvatarPic((picUrl)=> {
    Taro.navigateTo({
      url: `/pages/agent-gen/index?avatarUrl=${picUrl}`,
    });
  })
};
