import pptxgen from "pptxgenjs";

/**
 * 将任意图片 URL（含相对路径）转为 base64 data URL
 * pptxgenjs 在浏览器端必须使用 base64 或完整 http 地址才能嵌入图片
 */
const toBase64 = (src) => {
  return new Promise((resolve) => {
    if (!src) { resolve(null); return; }
    if (src.startsWith('data:')) { resolve(src); return; }

    // 优先用 fetch 获取 Blob → base64（支持同源相对路径 & 允许CORS的外链）
    const fullUrl = src.startsWith('http') ? src : (window.location.origin + (src.startsWith('/') ? src : '/' + src));
    fetch(fullUrl)
      .then(r => r.blob())
      .then(blob => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result);
        reader.onerror = () => resolve(null);
        reader.readAsDataURL(blob);
      })
      .catch(() => {
        // fetch 失败时降级用 canvas（跨域图片会被 taint，可能失败）
        const img = new Image();
        img.crossOrigin = 'anonymous';
        img.onload = () => {
          try {
            const c = document.createElement('canvas');
            c.width = img.width; c.height = img.height;
            c.getContext('2d').drawImage(img, 0, 0);
            resolve(c.toDataURL('image/png'));
          } catch { resolve(null); }
        };
        img.onerror = () => resolve(null);
        img.src = fullUrl;
      });
  });
};

/** 1×1 灰色像素，作为图片加载失败时的占位符 */
const PLACEHOLDER_B64 = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQI12NgYGBgAAAABQABpfZFQAAAAABJRU5ErkJggg==';

export const generatePPT = async (template, products) => {
  if (!products || products.length === 0) return;

  const pres    = new pptxgen();
  const MC      = (template.themeColor || '#C00000').replace('#', '');
  const WHITE   = 'FFFFFF';

  // ── 把所有涉及到的资产图片提前并行转 base64 ──────────────────────────────────────
  const [coverB64, coverLogoB64, contentLogoB64, ...productImgB64s] = await Promise.all([
    toBase64(template.cover),
    toBase64(template.coverLogo),
    toBase64(template.contentLogo),
    ...products.map(p => toBase64(p.productImage))
  ]);

  // ── 0. 定义全局母版 (MASTER) ────────────────────────────────────────────────
  pres.defineSlideMaster({
    title: 'MASTER',
    background: { color: 'F5F7FA' }, // 浅灰背景，更有高级感
    objects: [
      // 底部装饰条
      { shape: pres.ShapeType.rect, options: { x: 0, y: 5.4, w: '100%', h: 0.2, fill: { color: MC } } }
    ]
  });

  // ══════════════════════════ 1. 封面页 ══════════════════════════════
  const coverSlide = pres.addSlide();
  // 背景图 (占据上方 75%)
  if (coverB64) coverSlide.addImage({ data: coverB64, x: 0, y: 0, w: '100%', h: 4.2, sizing: { type: 'cover' } });
  coverSlide.addShape(pres.ShapeType.rect, { x: 0, y: 0, w: '100%', h: 4.2, fill: { color: '000000', transparency: 50 } });

  // 封面文字
  coverSlide.addText(template.title || 'VIP客户生日礼方案', { x: 0.4, y: 2.2, w: 6.0, h: 0.8, fontSize: 32, color: WHITE, bold: true });
  coverSlide.addText(template.subTitle || '卓越品质，专属定制', { x: 0.4, y: 2.9, w: 6.0, h: 0.5, fontSize: 22, color: WHITE, opacity: 0.9 });
  coverSlide.addText(template.validity || '方案有效期：2026年12月31日', { x: 0.4, y: 3.4, w: 6.0, h: 0.3, fontSize: 11, color: 'EEEEEE' });

  // 底部白条 (Logo/品牌信息)
  coverSlide.addShape(pres.ShapeType.rect, { x: 0, y: 4.2, w: '100%', h: 1.4, fill: { color: WHITE } });
  if (coverLogoB64) coverSlide.addImage({ data: coverLogoB64, x: 0.4, y: 4.4, w: 1.0, h: 1.0, sizing: { type: 'contain' } });
  coverSlide.addShape(pres.ShapeType.line, { x: 1.5, y: 4.5, w: 0, h: 0.8, line: { color: 'DDDDDD', width: 1 } });
  
  coverSlide.addText(template.brandName || '优易365', { x: 1.6, y: 4.5, w: 3.0, h: 0.4, fontSize: 20, color: '000000', bold: true });
  coverSlide.addText(template.brandSlogan || '领先的企业级数字化采购及服务品牌', { x: 1.6, y: 4.9, w: 4.0, h: 0.3, fontSize: 10, color: '666666' });
  
  coverSlide.addText(template.website || 'www.yoe365.com', { x: 7.0, y: 4.5, w: 2.6, h: 0.3, fontSize: 12, color: '000000', align: 'right', bold: true });
  coverSlide.addText(template.phone || '400-000-0000', { x: 7.0, y: 4.8, w: 2.6, h: 0.3, fontSize: 12, color: '000000', align: 'right', bold: true });

  // ══════════════════════════ 2. 商品内页 ══════════════════════════════
  const layoutId = template.itemsPerPage || 1;
  // 特殊逻辑：itemsPerPage === 3 是“单品明细版”的标识符，逻辑上强制为 每页1个商品
  const itemsPerPage = layoutId === 3 ? 1 : layoutId;
  const totalPages   = Math.ceil(products.length / itemsPerPage);

  for (let i = 0; i < totalPages; i++) {
    const slide        = pres.addSlide({ masterName: 'MASTER' });
    const pageProducts = products.slice(i * itemsPerPage, (i + 1) * itemsPerPage);

    // 渲染定制化顶栏及背景覆盖
    const curTopTitle = template.contentTitle || '商品展示方案';

    if (layoutId !== 3) {
      if (contentLogoB64) slide.addImage({ data: contentLogoB64, x: 0.2, y: 0.08, w: 1.1, h: 0.44, sizing: { type: 'contain' } });
      slide.addText(curTopTitle, { x: contentLogoB64 ? 1.45 : 0.2, y: 0.1, w: 6.5, h: 0.42, fontSize: 16, color: MC, bold: true });
      slide.addText(`Page ${i + 1}`, { x: 8.5, y: 0.12, w: 1, h: 0.3, fontSize: 11, color: '999999', align: 'right' });
      slide.addShape(pres.ShapeType.rect, { x: 0, y: 0.64, w: 0.12, h: 4.8, fill: { color: MC } });
    } else {
      slide.addShape(pres.ShapeType.rect, { x: 0, y: 0, w: '100%', h: 0.6, fill: { color: 'FFFFFF' } }); // 标题背景区
      slide.addShape(pres.ShapeType.rect, { x: 0.4, y: 0.18, w: 0.05, h: 0.24, fill: { color: 'E3132D' } }); // 红色装饰条
      slide.addText(curTopTitle, { x: 0.55, y: 0.18, w: 6.0, h: 0.24, fontSize: 16, color: '1A1A1A', bold: true, valign: 'middle' });
      if (contentLogoB64) slide.addImage({ data: contentLogoB64, x: 8.4, y: 0.1, w: 1.2, h: 0.4, sizing: { type: 'contain' } });
      // 分割线：满宽，且正好在背景块底部 (y=0.6)
      slide.addShape(pres.ShapeType.line, { x: 0, y: 0.6, w: '100%', h: 0, line: { color: 'BDBDBD', width: 0.5, dashType: 'sysDash' } });
    }

    if (layoutId === 3) {
      // ──── [A] 1 商品 / 页图文详细版式 (明细版) ────────────────────────
      const p    = pageProducts[0];
      const imgB = productImgB64s[i] || PLACEHOLDER_B64;
      
      slide.addShape(pres.ShapeType.rect, { x: 0.5, y: 1.15, w: 3.8, h: 4.0, fill: { color: 'FFFFFF' } });
      if (imgB) slide.addImage({ data: imgB, x: 0.55, y: 1.2, w: 3.7, h: 3.9, sizing: { type: 'contain' } });

      const tx = 4.6;
      const rw = 5.0;
      slide.addText(p.itemName, { x: tx, y: 0.95, w: rw, h: 0.45, fontSize: 13, color: '1A1A1A', wrap: true });
      slide.addShape(pres.ShapeType.line, { x: tx, y: 1.45, w: rw, h: 0, line: { color: 'E3132D', width: 0.75 } });
      
      let cy = 1.6;
      slide.addText(`规格型号：${p.specificationsCode}`, { x: tx, y: cy, w: rw, h: 0.25, fontSize: 11, color: '111111', bold: true }); cy += 0.28;
      slide.addText(`产品编号：${p.productNo || p.barCoding}`, { x: tx, y: cy, w: rw, h: 0.25, fontSize: 11, color: '111111', bold: true }); cy += 0.28;
      slide.addText(`品牌名称：${p.brandName || '未知'}`, { x: tx, y: cy, w: rw, h: 0.25, fontSize: 11, color: '111111', bold: true }); cy += 0.28;
      slide.addText(`最低起订量：${p.minOrderQuantity || '1'}`, { x: tx, y: cy, w: rw, h: 0.25, fontSize: 11, color: '111111', bold: true }); cy += 0.28;
      
      cy += 0.05;
      slide.addText(`市场价：${p.marketPrice || p.marketPrice} 元`, { x: tx, y: cy, w: rw, h: 0.25, fontSize: 11, color: '666666', bold: true, strike: true }); cy += 0.28;
      slide.addText(`供应价：${p.marketPrice}元`, { x: tx, y: cy, w: rw, h: 0.3, fontSize: 13, color: 'E3132D', bold: true }); cy += 0.45;

      slide.addText(`产品属性`, { x: tx, y: cy, w: 2.3, h: 0.25, fontSize: 12, color: '111111', bold: true });
      slide.addText(`产品简介`, { x: tx+2.4, y: cy, w: 2.3, h: 0.25, fontSize: 12, color: '111111', bold: true });
      cy += 0.25;
      
      if (p.attributesList) {
        let attrText = '';
        if (Array.isArray(p.attributesList)) {
          // mock 数据：字符串数组
          attrText = p.attributesList.join('\n');
        } else if (typeof p.attributesList === 'string') {
          try {
            // 真实 API：JSON 字符串，格式如 {"1":["3kg","4kg"],"2":["红色"]}
            const attrObj = JSON.parse(p.attributesList);
            attrText = Object.entries(attrObj)
              .map(([key, vals]) => `${key}：${Array.isArray(vals) ? vals.join('、') : String(vals)}`)
              .join('\n');
          } catch (e) {
            attrText = p.attributesList;
          }
        }
        if (attrText) {
          slide.addText(attrText, { x: tx, y: cy, w: 2.3, h: 1.0, fontSize: 10, color: '666666', valign: 'top', lineSpacing: 14 });
        }
      }
      if (p.productDescription) {
        slide.addText(p.productDescription.join('\n'), { x: tx+2.4, y: cy, w: 2.4, h: 1.0, fontSize: 10, color: '666666', valign: 'top', lineSpacing: 14 });
      }

    } else if (itemsPerPage === 1) {
      // ──── [B] 基础 1 商品 / 页版式 ────────────────────────────────────────
      const p    = pageProducts[0];
      const imgB = productImgB64s[i] || PLACEHOLDER_B64;

      if (imgB) {
        slide.addImage({ data: imgB, x: 0.5, y: 0.9, w: 4.7, h: 3.8, sizing: { type: 'cover', w: 4.7, h: 3.8 } });
        slide.addShape(pres.ShapeType.rect, { x: 0.5, y: 0.9, w: 4.7, h: 3.8, fill: { type: 'none' }, line: { color: 'E0E0E0', width: 1 } });
      } else {
        slide.addShape(pres.ShapeType.rect, { x: 0.5, y: 0.9, w: 4.7, h: 3.8, fill: { type: 'solid', color: 'F0F0F0' }, line: { color: 'E0E0E0', width: 1 } });
      }

      const sx = 5.5;
      slide.addText(p.itemName, { x: sx, y: 0.9, w: 3.9, h: 1.4, fontSize: 20, bold: true, color: '222222', wrap: true, valign: 'top' });
      slide.addText(`产品编号：${p.productNo || p.barCoding}`, { x: sx, y: 2.3, w: 3.9, h: 0.35, fontSize: 13, color: '666666' });
      slide.addText(`规格型号：${p.specificationsCode}`,  { x: sx, y: 2.7, w: 3.9, h: 0.35, fontSize: 13, color: '666666' });

      slide.addShape(pres.ShapeType.roundRect, { x: sx, y: 3.5, w: 2.8, h: 0.75, fill: { color: MC }, rectRadius: 0.12 });
      slide.addText(`供应价: ¥${p.marketPrice}`, { x: sx, y: 3.5, w: 2.8, h: 0.75, fontSize: 22, color: WHITE, align: 'center', bold: true });

    } else if (itemsPerPage === 2) {
      // ──── [C] 2 商品 / 页交错版式 ─────────────────────────────────────────
      if (pageProducts.length === 2) {
        slide.addShape(pres.ShapeType.line, { x: 0.4, y: 3.0, w: 9.1, h: 0, line: { color: 'DDDDDD', width: 1, dashType: 'dash' } });
      }

      for (let j = 0; j < pageProducts.length; j++) {
        const p       = pageProducts[j];
        const imgIdx  = i * itemsPerPage + j;
        const imgB    = productImgB64s[imgIdx] || PLACEHOLDER_B64;
        const isUpper = j === 0;
        const yBase   = isUpper ? 0.75 : 3.1;
        const imgX  = isUpper ? 0.4  : 6.6;
        const txtX  = isUpper ? 3.4  : 0.4;
        const txtAl = isUpper ? 'left' : 'right';

        if (imgB) {
          slide.addImage({ data: imgB, x: imgX, y: yBase, w: 2.7, h: 2.05, sizing: { type: 'cover', w: 2.7, h: 2.05 } });
          slide.addShape(pres.ShapeType.rect, { x: imgX, y: yBase, w: 2.7, h: 2.05, fill: { type: 'none' }, line: { color: 'E0E0E0', width: 1 } });
        } else {
          slide.addShape(pres.ShapeType.rect, { x: imgX, y: yBase, w: 2.7, h: 2.05, fill: { type: 'solid', color: 'F5F5F5' }, line: { color: 'EEEEEE', width: 1 } });
        }

        slide.addText(p.itemName, { x: txtX, y: yBase + 0.05, w: 3.1, h: 0.95, fontSize: 15, bold: true, color: '222222', align: txtAl, wrap: true, valign: 'top' });
        slide.addText(`编号: ${p.productNo || p.barCoding} | 规格: ${p.specificationsCode}`, { x: txtX, y: yBase + 1.05, w: 3.1, h: 0.4, fontSize: 11, color: '888888', align: txtAl });

        const priceX = isUpper ? txtX : txtX + 1.1;
        slide.addShape(pres.ShapeType.roundRect, { x: priceX, y: yBase + 1.55, w: 2.0, h: 0.44, fill: { color: 'F5F5F5' }, rectRadius: 0.08, line: { color: MC, width: 1 } });
        slide.addText(`¥ ${p.marketPrice}`, { x: priceX, y: yBase + 1.55, w: 2.0, h: 0.44, fontSize: 16, bold: true, color: MC, align: 'center' });
      }
    }
  }

  // ══════════════════════════ 3. 尾页 (复刻预览设计的致谢页) ══════════════════════
  const end = pres.addSlide();
  end.background = { color: WHITE };

  // 主标题 THANKS
  end.addText('THANKS', {
    x: 3.0, y: 1.4, w: 6.6, h: 1.4,
    fontSize: 90, bold: true, color: MC, align: 'right'
  });

  // 品牌名称 - 宣传口号 (增加宽度 w: 7 避免长文案换行)
  const brandGroup = `${template.brandName || '优易365'} - ${template.brandSlogan || '领先的企业级数字化采购及服务品牌'}`;
  end.addText(brandGroup, {
    x: 2.6, y: 3.0, w: 7.0, h: 0.5,
    fontSize: 18, bold: true, color: '333333', align: 'right'
  });

  // 网址
  end.addText(template.website || 'www.yoe365.com', {
    x: 3.0, y: 3.5, w: 6.6, h: 0.3,
    fontSize: 14, bold: true, color: MC, align: 'right'
  });

  // 导出
  await pres.writeFile({ fileName: `${template.title || '商品展示方案'}_${Date.now()}.pptx` });
};
