/**
 * 商品图片压缩和上传服务
 * 批量压缩和上传商品图片
 */
import { ElMessage } from "element-plus";
import { compressImageSafe, ImageQuality } from "./imageCompressor";
import { getGoodsListApi, updateGoodsApi, GoodsDTO } from "@/api/shop/goods";
import { useWxStore } from "@/store/modules/wx";

const { VITE_APP_BASE_API } = import.meta.env;

export interface CompressProgress {
  total: number; // 总数
  current: number; // 当前处理数
  success: number; // 成功数
  failed: number; // 失败数
  skipped: number; // 跳过数
}

export interface CompressResult {
  goodsId: number;
  goodsName: string;
  success: boolean;
  oldImageUrl: string;
  newImageUrl?: string;
  error?: string;
}

/**
 * 将网络图片转换为File对象
 * @param url 图片URL
 * @param filename 文件名
 * @returns Promise<File>
 */
const urlToFile = async (url: string, filename: string): Promise<File> => {
  const response = await fetch(url);
  const blob = await response.blob();
  return new File([blob], filename, { type: blob.type });
};

/**
 * 上传图片到服务器
 * @param file 文件对象
 * @returns Promise<string> 图片URL
 */
const uploadImage = async (file: File): Promise<string> => {
  const formData = new FormData();
  formData.append("file", file);

  const response = await fetch(`${VITE_APP_BASE_API}/file/upload`, {
    method: "POST",
    body: formData,
    credentials: "include"
  });

  if (!response.ok) {
    throw new Error(`上传失败: ${response.statusText}`);
  }

  const result = await response.json();
  console.log('上传图片结果', result);
  if (result.code !== 0) {
    throw new Error(result.msg || "上传失败");
  }

  return result.data.url;
};

/**
 * 压缩单个商品的图片
 * @param goods 商品信息
 * @param quality 压缩质量
 * @param maxWidth 最大宽度
 * @param maxHeight 最大高度
 * @returns Promise<CompressResult>
 */
const compressGoodsImage = async (
  goods: GoodsDTO,
  quality: ImageQuality = ImageQuality.MEDIUM,
  maxWidth: number = 980,
  maxHeight: number = 980
): Promise<CompressResult> => {
  try {
    // 如果没有封面图，跳过
    if (!goods.coverImg) {
      return {
        goodsId: goods.goodsId!,
        goodsName: goods.goodsName,
        success: false,
        oldImageUrl: "",
        error: "无封面图"
      };
    }

    // 转换为File对象
    const imageFileName = `goods_${goods.goodsId}_${Date.now()}.jpg`;
    const file = await urlToFile(goods.coverImg, imageFileName);

    // 压缩图片
    const { file: compressedFile, compressed } = await compressImageSafe(file, {
      quality,
      maxWidth,
      maxHeight
    });

    // 上传压缩后的图片
    console.log('压缩图片名称', compressedFile.name);
    console.log('压缩前图片大小', file.size);
    console.log('压缩后图片大小', compressedFile.size);
    const newImageUrl = await uploadImage(compressedFile);

    // 更新商品信息
    const updateData = {
      ...goods,
      coverImg: newImageUrl
    };
    delete (updateData as any).goodsId;
    delete (updateData as any).createTime;
    delete (updateData as any).updateTime;

    console.log('压缩图片信息', compressed);

    await updateGoodsApi(goods.goodsId!, updateData);

    return {
      goodsId: goods.goodsId!,
      goodsName: goods.goodsName,
      success: true,
      oldImageUrl: goods.coverImg,
      newImageUrl
    };
  } catch (error) {
    console.error('压缩商品图片失败', error);
    return {
      goodsId: goods.goodsId!,
      goodsName: goods.goodsName,
      success: false,
      oldImageUrl: goods.coverImg,
      error: error instanceof Error ? error.message : "未知错误"
    };
  }
};

/**
 * 获取所有商品列表（分页获取）
 * @param corpid 企业微信ID
 * @returns Promise<GoodsDTO[]>
 */
const getAllGoods = async (corpid: string): Promise<GoodsDTO[]> => {
  const allGoods: GoodsDTO[] = [];
  let pageNum = 1;
  const pageSize = 100; // 每页获取100条

  while (true) {
    const { data } = await getGoodsListApi({
      corpid,
      pageNum,
      pageSize
    });

    if (data.rows.length === 0) {
      break;
    }

    allGoods.push(...data.rows);

    // 如果当前页数据小于pageSize，说明已经获取完所有数据
    if (data.rows.length < pageSize) {
      break;
    }

    pageNum++;
  }

  return allGoods;
};

/**
 * 一键压缩全部商品图片
 * @param options 压缩配置
 * @param onProgress 进度回调
 * @returns Promise<CompressResult[]>
 */
export const compressAllGoodsImages = async (
  options: {
    quality?: ImageQuality;
    maxWidth?: number;
    maxHeight?: number;
    onProgress?: (progress: CompressProgress) => void;
  } = {}
): Promise<CompressResult[]> => {
  const wxStore = useWxStore();
  const corpid = wxStore.corpid || 'wpZ1ZrEgAA2QTxIRcB4cMtY7hQbTcPAw';

  if (!corpid) {
    throw new Error("未获取到企业微信ID");
  }

  // 获取所有商品
  ElMessage.info("正在获取商品列表...");
  const allGoods = await getAllGoods(corpid);

  if (allGoods.length === 0) {
    ElMessage.warning("没有找到商品数据");
    return [];
  }

  // 过滤出有封面图的商品
  const goodsWithImages = allGoods.filter(goods => goods.coverImg
    && goods.coverImg.trim() !== ''
    && goods.coverImg.indexOf('wxshop.ab98.cn') !== -1);

  if (goodsWithImages.length === 0) {
    ElMessage.warning("没有找到带封面图的商品");
    return [];
  }

  ElMessage.info(
    `找到 ${allGoods.length} 个商品，其中 ${goodsWithImages.length} 个有封面图`
  );

  // 配置参数
  const quality = options.quality || ImageQuality.MEDIUM;
  const maxWidth = options.maxWidth || 980;
  const maxHeight = options.maxHeight || 980;
  const onProgress = options.onProgress;

  // 初始化进度
  const progress: CompressProgress = {
    total: goodsWithImages.length,
    current: 0,
    success: 0,
    failed: 0,
    skipped: 0
  };

  const results: CompressResult[] = [];

  // 逐个处理商品
  for (const goods of goodsWithImages) {
    progress.current++;
    onProgress?.(progress);

    // 跳过没有图片的商品
    if (!goods.coverImg) {
      progress.skipped++;
      continue;
    }

    ElMessage.info(
      `正在处理 (${progress.current}/${progress.total}): ${goods.goodsName}`
    );

    const result = await compressGoodsImage(goods, quality, maxWidth, maxHeight);
    results.push(result);

    if (result.success) {
      progress.success++;
      ElMessage.success(`✓ ${goods.goodsName} - 压缩成功`);
    } else {
      progress.failed++;
      ElMessage.error(`✗ ${goods.goodsName} - ${result.error}`);
    }
  }

  onProgress?.(progress);

  return results;
};

/**
 * 预览压缩结果统计
 * @param results 压缩结果
 */
export const previewCompressResults = (results: CompressResult[]): void => {
  const success = results.filter(r => r.success).length;
  const failed = results.filter(r => !r.success).length;

  console.group("商品图片压缩结果统计");
  console.log(`总商品数: ${results.length}`);
  console.log(`成功: ${success}`);
  console.log(`失败: ${failed}`);
  console.log(`成功率: ${((success / results.length) * 100).toFixed(2)}%`);
  console.groupEnd();

  if (failed > 0) {
    console.group("失败的商品:");
    results
      .filter(r => !r.success)
      .forEach(r => {
        console.log(`- ${r.goodsName}: ${r.error}`);
      });
    console.groupEnd();
  }
};
