import Taro from '@tarojs/taro'
import { uploadFile } from './http'
import { EUploadFileScene } from "@/consts/enum";
const IMAGE_LIMIT = 50 * 1024 * 1024 // 50MB = 52428800 bytes
const VIDEO_LIMIT = 30 * 1024 * 1024 // 30MB
const FILE_LIMIT = 100 * 1024 * 1024 // 100MB

export async function pickAndUploadImage(
  sourceType: Array<'album' | 'camera'> = ['album', 'camera'],
  scene: EUploadFileScene,
  maxSize?: { maxWidth: number, maxHeight: number }
): Promise<{ url: string; size: number } | null> {
  try {
    const res = await Taro.chooseImage({
      count: 1,
      sizeType: ['compressed', 'original'],
      sourceType,
    })

    const file = res.tempFiles[0]

    if (file.size >= IMAGE_LIMIT) {
      Taro.showToast({
        title: '图片大小超限',
        icon: 'error',
        duration: 1500,
      })
      return null
    }

    if (maxSize) {
      const { width, height } = await new Promise<{ width: number, height: number }>((resolve) => {
        Taro.getImageInfo({
          src: file.path,
          success(result) {
            resolve({ width: result.width, height: result.height })
          },
          fail(res) {
            resolve({ width: 0, height: 0 })
          },
        })
      })
      if (width > maxSize.maxWidth || height > maxSize.maxHeight) {
        Taro.showToast({
          title: '图片宽高超限',
          icon: 'error',
          duration: 1500,
        })
        return null
      }
    }

    const result = await uploadFile(
      file.path,
      scene,
    );

    if (result && ('publicUrl' in result)) {
      Taro.showToast({
        title: '上传成功',
        icon: 'success',
        duration: 1500,
      })
      return {
        url: result.publicUrl,
        size: file.size,
      }
    }
    return null
  } catch (error) {
    throw new Error('Failed to pick or upload image')
  }
}

export const pickAndUploadImageWithCrop = async (
  sourceType: Array<'album' | 'camera'> = ['album', 'camera'],
  cropScale?: keyof Taro.cropImage.CropScale,
  scene?: EUploadFileScene,
): Promise<{ url: string; size: number } | null> => {

  const res = await Taro.chooseImage({
    count: 1,
    sizeType: ['compressed', 'original'],
    sourceType,
  })

  const file = res.tempFiles[0]
  return new Promise((resolve) => {
    Taro.cropImage({
      src: file.path,
      cropScale: cropScale ?? "1:1",
      success: async (cropRes) => {
        const path = cropRes.tempFilePath;
        Taro.showLoading();
        const _scene = scene ?? EUploadFileScene.OTHER
        const result = await uploadFile(
          path,
          _scene,
        );

        if (result && ('publicUrl' in result)) {
          Taro.showToast({
            title: '上传成功',
            icon: 'success',
            duration: 1500,
          })
          resolve({
            url: result.publicUrl,
            size: file.size,
          })
          return
        }
        resolve(null)
      },
      fail() {
        resolve(null)
      }
    });
  })
}

export const cropImage = (filePath: string, cropScale?: keyof Taro.cropImage.CropScale,): Promise<{ url: string } | null> => {
  return new Promise((resolve) => {
    Taro.cropImage({
      src: filePath,
      cropScale: cropScale ?? "1:1",
      success: async (cropRes) => {
        const path = cropRes.tempFilePath;
        const _scene = EUploadFileScene.OTHER
        const result = await uploadFile(
          path,
          _scene,
        );
        if (result && ('publicUrl' in result)) {
          resolve({
            url: result.publicUrl,
          })
          return
        }
        resolve(null)
      },
      fail() {
        resolve(null)
      },
    });
  })
}
