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';
  const title   = template.title || template.name || '商品展示方案';

  // ── 把所有图片提前并行转 base64 ──────────────────────────────────────
  const [coverB64, logoB64, ...productImgB64s] = await Promise.all([
    toBase64(template.cover),
    toBase64(template.logo),
    ...products.map(p => toBase64(p.image))
  ]);

  // ── 母版（内页底纹）─────────────────────────────────────────────────
  pres.defineSlideMaster({
    title: 'MASTER',
    background: { color: 'FFFFFF' },
    objects: [
      // 顶栏底色
      { shape: { type: pres.ShapeType.rect, x: 0, y: 0, w: '100%', h: 0.6, fill: { color: 'F8F9FA' } } },
      // 顶栏下面的细线
      { shape: { type: pres.ShapeType.rect, x: 0, y: 0.6, w: '100%', h: 0.04, fill: { color: MC } } },
      // 右下角极浅三角装饰
      { shape: { type: pres.ShapeType.rtTriangle, x: 8.6, y: 4.5, w: 1.4, h: 1.4, fill: { color: MC, transparency: 92 } } },
      // 底条
      { shape: { type: pres.ShapeType.rect, x: 0, y: 5.4, w: '100%', h: 0.1, fill: { color: MC, transparency: 70 } } }
    ]
  });

  // ══════════════════════════ 1. 封面 ══════════════════════════════════
  const cover = pres.addSlide();
  cover.background = { color: MC };

  if (coverB64) {
    cover.addImage({ data: coverB64, x: 0, y: 0, w: '100%', h: '100%', sizing: { type: 'cover' } });
    cover.addShape(pres.ShapeType.rect, { x: 0, y: 0, w: '100%', h: '100%', fill: { color: '000000', transparency: 50 } });
  } else {
    cover.addShape(pres.ShapeType.rightTriangle, { x: 0, y: 0, w: 5, h: 4, fill: { color: WHITE, transparency: 90 } });
    cover.addShape(pres.ShapeType.oval, { x: 7, y: 3, w: 4, h: 4, fill: { color: '000000', transparency: 82 } });
  }

  if (logoB64) {
    cover.addImage({ data: logoB64, x: 0.5, y: 0.4, w: 1.4, h: 0.7, sizing: { type: 'contain' } });
  }
  cover.addText(title, {
    x: 1, y: 2.0, w: 8, h: 1.6,
    fontSize: 48, bold: true, color: WHITE, align: 'center',
    shadow: { type: 'outer', opacity: 0.4 }
  });
  cover.addText('PRODUCT SHOWCASE · 优选商品展示方案', {
    x: 1, y: 3.5, w: 8, h: 0.5,
    fontSize: 14, color: 'EEEEEE', align: 'center', letterSpacing: 1.5
  });
  cover.addText(`发布日期：${new Date().toLocaleDateString()}`, {
    x: 0, y: 5.0, w: '100%', h: 0.4,
    fontSize: 11, color: WHITE, align: 'center'
  });

  // ══════════════════════════ 2. 商品内页 ══════════════════════════════
  const itemsPerPage = template.itemsPerPage || 1;
  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);

    // 内页顶栏
    if (logoB64) {
      slide.addImage({ data: logoB64, x: 0.2, y: 0.08, w: 1.1, h: 0.44, sizing: { type: 'contain' } });
    }
    slide.addText(title, {
      x: logoB64 ? 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 } });

    if (itemsPerPage === 1) {
      // ──── 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;
      // 商品名 - 自动换行，字号缩小到22确保60字也不溢出
      slide.addText(p.name, {
        x: sx, y: 0.9, w: 3.9, h: 1.4,
        fontSize: 20, bold: true, color: '222222',
        wrap: true, valign: 'top'
      });
      // 移除原硬编码装饰横线，直接放置下续属性使排版自然衔接
      slide.addText(`商品69码：${p.code}`, { x: sx, y: 2.3, w: 3.9, h: 0.35, fontSize: 13, color: '666666' });
      slide.addText(`商品规格：${p.spec}`,  { 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.price}`, {
        x: sx, y: 3.5, w: 2.8, h: 0.75,
        fontSize: 22, color: WHITE, align: 'center', bold: true
      });

    } else {
      // ──── 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.name, {
          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(`69码: ${p.code}  |  规格: ${p.spec}`, {
          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.price}`, { 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: '1A1A1A' };
  end.addShape(pres.ShapeType.rect, { x: 0, y: 0, w: '22%', h: '100%', fill: { color: MC } });
  end.addShape(pres.ShapeType.line, { x: 2.8, y: 1.4, w: 6, h: 0, line: { color: '444444', width: 1.5 } });
  end.addText('THANK YOU', { x: 2.8, y: 1.8, w: 7, h: 1.5, fontSize: 60, bold: true, color: MC });
  end.addText('感谢您的观看 · 期待与您携手共进', { x: 2.8, y: 3.3, w: 7, h: 0.5, fontSize: 18, color: 'BBBBBB', letterSpacing: 2 });
  if (logoB64) {
    end.addImage({ data: logoB64, x: 2.8, y: 4.3, w: 1.4, h: 0.7, sizing: { type: 'contain' } });
  }

  // 导出
  await pres.writeFile({ fileName: `${title}_${Date.now()}.pptx` });
};
