// composables/useWeatherExport.ts
import { ref, nextTick, type Ref } from "vue";
import { ElMessage, ElLoading } from "element-plus";

export interface ExportOptions {
  /** 导出前需要展开表格？ */
  expandTable: Ref<boolean>;
  /** 导出前需要收起筛选面板？ */
  collapseFilter: Ref<boolean>;
  /** 月/日锚点 */
  anchorMonth: Ref<number> | number;
  /** pad 后的日期字符串 */
  padDay: Ref<string> | string;
}

/**
 * 导出为 PNG 或 PDF。
 * html2canvas + jspdf 均为动态 import，不生成为首屏包体积。
 */
export function useWeatherExport(rootRef: Ref<HTMLElement | null>, opts: ExportOptions) {
  const exporting = ref(false);

  const resolveDay = () => {
    const m = typeof opts.anchorMonth === "number" ? opts.anchorMonth : opts.anchorMonth.value;
    const d = typeof opts.padDay === "string" ? opts.padDay : opts.padDay.value;
    return `${m}月${d}日`;
  };

  async function doExport(type: "png" | "pdf") {
    const el = rootRef.value;
    if (!el || exporting.value) return;

    exporting.value = true;

    // 全屏 loading（大页面渲染可能需要数秒）
    const loadingInstance = ElLoading.service({
      fullscreen: true,
      text: "正在渲染导出内容…",
      background: "rgba(255,255,255,0.7)"
    });

    try {
      // 保存并临时修改 UI 状态
      const prevTableExp = opts.expandTable.value;
      const prevFilterOpen = opts.collapseFilter.value;
      opts.expandTable.value = true;
      opts.collapseFilter.value = false;

      await nextTick();
      // 等待两帧确保 DOM 完全渲染
      await new Promise<void>((r) => requestAnimationFrame(() => requestAnimationFrame(() => r())));

      // 动态 import 重型库
      const [{ default: html2canvas }, { default: jsPDF }] = await Promise.all([
        import("html2canvas"),
        import("jspdf")
      ]);

      const canvas = await html2canvas(el, {
        useCORS: true,
        scale: 2,
        backgroundColor: "#f1f5f9",
        logging: false,
        allowTaint: true,
        ignoreElements: (e: Element) => {
          if (e.classList?.contains("el-popper") || e.classList?.contains("el-popover"))
            return true;
          if (e.tagName === "STYLE" && e.textContent?.includes("v-popper")) return true;
          return false;
        },
        onclone: (clonedDoc: Document) => {
          // 修复 Element Plus 图标在 canvas 中的显示
          clonedDoc.querySelectorAll(".el-icon").forEach((icon) => {
            if (!(icon as HTMLElement).querySelector("svg")) return;
            (icon as HTMLElement).style.display = "inline-block";
            (icon as HTMLElement).style.width = "14px";
            (icon as HTMLElement).style.height = "14px";
          });
          // 确保 canvas 图表可见
          clonedDoc.querySelectorAll("canvas").forEach((c) => {
            (c as HTMLElement).style.display = "block";
          });
          // 表格内容不裁剪
          clonedDoc.querySelectorAll(".el-table__body-wrapper").forEach((w) => {
            (w as HTMLElement).style.overflow = "visible";
          });
        }
      });

      // 恢复 UI 状态
      opts.expandTable.value = prevTableExp;
      opts.collapseFilter.value = prevFilterOpen;

      const dateStr = resolveDay();
      const ext = type === "png" ? "png" : "pdf";
      const label = type === "png" ? "PNG 图片" : "PDF 文档";

      if (type === "png") {
        const a = document.createElement("a");
        a.href = canvas.toDataURL("image/png");
        a.download = `气象回溯_${dateStr}.png`;
        a.click();
      } else {
        const imgData = canvas.toDataURL("image/png");
        const pdf = new jsPDF("p", "mm", "a4");
        const w = pdf.internal.pageSize.getWidth();
        const h = (canvas.height * w) / canvas.width;
        const pageH = pdf.internal.pageSize.getHeight();

        if (h <= pageH) {
          pdf.addImage(imgData, "PNG", 0, 0, w, h);
        } else {
          let remaining = h;
          let yOffset = 0;
          while (remaining > 0) {
            if (yOffset > 0) pdf.addPage();
            pdf.addImage(imgData, "PNG", 0, -yOffset, w, h);
            yOffset += pageH;
            remaining -= pageH;
          }
        }
        pdf.save(`气象回溯_${dateStr}.pdf`);
      }

      ElMessage.success(`${label}已导出 — 气象回溯_${dateStr}.${ext}`);
    } catch (err) {
      console.error("导出失败:", err);
      ElMessage.error("导出失败，请重试");
    } finally {
      loadingInstance.close();
      exporting.value = false;
    }
  }

  return { doExport, exporting };
}
