import { ScenePoint, getPointPano } from "@/store/scene";
import JSZip from "jszip";
import saveAs from "@/util/file-serve";
import { openLoading, closeLoading } from "@/helper/loading";
import { dateFormat } from "@/util";
import { ElMessage } from "element-plus";
import {
  downloadPointsXLSL,
  downloadPointsXLSL1,
  downloadPointsXLSL2,
} from "@/util/pc4xlsl";

export const exportFile = async (points: ScenePoint[], type: number) => {
  if (!points.length) {
    ElMessage.error("请选择要导出的点位");
    return;
  }
  points = points.filter((point) => !!point.pos);

  if (points.length === 0) {
    ElMessage.error("当前选择点位没有gis信息");
    return;
  }
  if (type === 1) {
    await downloadPointsXLSL1(
      points.map((point) => point.pos),
      points.map((point) => ({ title: point.name, desc: point.name })),
      "绘制矢量数据"
    );
  } else if (type === 2) {
    await downloadPointsXLSL2(
      points.map((point) => point.pos),
      points.map((point) => ({ title: point.name, desc: "无" })),
      "本体边界坐标"
    );
  } else {
    await downloadPointsXLSL(
      points.map((point) => point.pos),
      points.map((point) => ({ title: point.name, desc: point.name })),
      "test"
    );
  }
  ElMessage.success("文件导出成功");
};

export const exportImage = async (points: ScenePoint[], name?: string) => {
  if (!points.length) {
    ElMessage.error("请选择要导出的点位");
    return;
  }

  openLoading();
  const zip = new JSZip();
  const imgFolder = zip.folder(name || "images")!;

  const downloadImages = Promise.all(
    points.map((point) => {
      const url = getPointPano(point);
      return fetch(url as string)
        .then((res) => res.blob())
        .then((blob) => {
          imgFolder.file(`${point.sceneCode}-${point.uuid}.jpg`, blob);
        })
        .catch((e) => {
          ElMessage.error(url + "图片下载失败！");
          throw e;
        });
    })
  );
  await downloadImages;

  const content = await zip.generateAsync({ type: "blob" });
  await saveAs(content, `${name || "images"}.zip`);
  closeLoading();
};

export const exposeExsl = async (pointsGroup: ScenePoint[][]) => {
  const timeStr = dateFormat(new Date(), "yyyy-MM-ddThh:mm:ssZ");
  const rets: string[] = pointsGroup.map((points, i) => {
    const name = `Rt${(i + 1).toString().padStart(4, "0")}`;
    const rtepts = points.map((point, j) => {
      return `
          <rtept lat="${point.pos[1]}" lon="${point.pos[0]}">
              <ele>${point.pos[2]}</ele>
              <time>${timeStr}</time>
              <name>${name}_pt${(j + 1).toString().padStart(4, "0")}</name>
          </rtept>
        `;
    });
    return `
    <rte>
          <name>${name}</name>
          ${rtepts.join("")}
    </rte>
    `;
  });

  for (let i = 0; i < rets.length; i++) {
    const name = `Rt${(i + 1).toString().padStart(4, "0")}`;
    const text = `\
<?xml version="1.0" encoding="UTF-8" ?>
<gpx version="1.1" creator="BHCNAV" xmlns="http://www.topografix.com/GPX/1/1">
  ${rets[i]}
</gpx>
  `;
    await saveAs(new Blob([text], { type: "text/plain" }), `${name}.gpx`);
  }
};
