import { openImageCompressModal } from '@/common/js/image-compress-modal.js';

export const IMAGE_COMPRESS_THRESHOLD = 1 * 1024 * 1024;

export function formatFileSize(bytes) {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  const value = bytes / k ** i;
  return `${Number.parseFloat(value.toFixed(2))} ${sizes[i]}`;
}

/** 压缩节省比例文案，如「（约节省 42%）」 */
export function formatSavingsPercent(originalBytes, compressedBytes) {
  if (originalBytes <= 0 || compressedBytes >= originalBytes) {
    return '';
  }
  const percent = Math.round(
    ((originalBytes - compressedBytes) / originalBytes) * 100,
  );
  return percent > 0 ? `（约节省 ${percent}%）` : '';
}

function getFileInfo(filePath) {
  return new Promise((resolve, reject) => {
    uni.getFileInfo({
      filePath,
      success: resolve,
      fail: reject,
    });
  });
}

export function compressImagePath(src, quality) {
  return new Promise((resolve, reject) => {
    uni.compressImage({
      src,
      quality,
      success: async (res) => {
        try {
          const info = await getFileInfo(res.tempFilePath);
          resolve({
            path: res.tempFilePath,
            size: info.size,
          });
        } catch (error) {
          reject(error);
        }
      },
      fail: reject,
    });
  });
}

export async function tryCompressImage(
  src,
  qualities = [80, 60, 40],
  onProgress,
) {
  let result = null;
  for (const quality of qualities) {
    onProgress && onProgress(quality);
    result = await compressImagePath(src, quality);
    if (result.size <= IMAGE_COMPRESS_THRESHOLD) {
      break;
    }
  }
  return result;
}

export function isGifPath(path) {
  return /\.gif$/i.test(path || '');
}

export async function prepareImagePath({ path, size }) {
  if (size <= IMAGE_COMPRESS_THRESHOLD) {
    return {
      path,
      size,
      usedCompress: false,
    };
  }

  const result = await openImageCompressModal({ path, size });
  if (!result) {
    return null;
  }

  return {
    path: result.path,
    size: result.size,
    usedCompress: !!result.usedCompress,
  };
}
