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

// import { checkPermission, showAuthModal } from "@/utils/auth";

const MAX_IMAGE_SIZE = 10;
export const getNewAvatarPic = async (cb: (result: string|null)=> void)=> {
  // const authed = await checkPermission("scope.writePhotosAlbum");
  //   if (!authed) {
  //     showAuthModal("需要您相册权限");
  //     return;
  //   }
  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",
        });
        cb(null)
        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)
            return 
          }
          cb(null)
        },
        fail(){
          cb(null)
        }
      });
    },
    fail(){
      cb(null)
    },
  });
}

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