import { PointTypeEnum } from "@/lib/board/4dmap";
import { round, toDegrees } from "./";
import { saveAs } from "./file-serve";
import * as URL from "@/request/URL";
import { basePath, gHeaders } from "@/request/state";

// const genXLSLByTemp = (data: ArrayBuffer, tabs: any[][], name: string) => {
//   const workbook = XLSX.read(data, {
//     type: "binary",
//     cellStyles: true,

//     cellNF: true,
//     cellDates: true,
//     sheetStubs: true,
//     raw: true,
//     bookDeps: true,
//     bookVBA: true,
//     // bookProps: true,
//     // bookSheets: true,
//     WTF: true,
//     PRN: true,
//     xlfn: true,
//   });
//   const sheetName = workbook.SheetNames[0];
//   const worksheet = workbook.Sheets[sheetName];

//   XLSX.utils.sheet_add_aoa(worksheet, tabs, { origin: "A2" });
//   const wbout = XLSX.writeFile(workbook, `${name}.xlsx`);
//   return saveAs(wbout, `${name}.xlsx`);
// };

export const downloadPointsXLSL1 = async (
  points: number[][],
  desc: { title: string; desc: string }[] = [],
  name: string
) => {
  const tabs = points.map((point, i) => {
    const des = desc[i] || { title: "无", desc: "无" };
    return {
      fid: i.toString(),
      name: des.title,
      latitude: toDegrees(point[1], 4),
      longitude: toDegrees(point[0], 4),
    };
  });

  const data = await fetch(basePath + URL.exportVectorData, {
    headers: gHeaders,
    method: "post",
    body: JSON.stringify(tabs),
  }).then((res) => res.blob());

  return saveAs(data, `${name}.xls`);
};

export const downloadPointsXLSL2 = async (
  points: number[][],
  desc: { title: string; desc: string; type: string }[] = [],
  name: string,
  version: string
) => {
  const tabs = points.map((point, i) => {
    const des = desc[i] || {
      title: "无",
      desc: "无",
      type: "其他",
      remark: "无",
    };
    return {
      latitude: toDegrees(point[1], 4),
      longitude: toDegrees(point[0], 4),
      altitude: round(point[2], 4),
      description: des.title,
      remark: des.desc,
      type: des.type,
    };
  });

  const data = await fetch(
    basePath + URL.exportCoordinateData + "/" + version,
    {
      headers: gHeaders,
      method: "post",
      body: JSON.stringify(tabs),
    }
  ).then((res) => res.blob());

  return saveAs(data, `${name}.xls`);
};

export const downloadPointsXLSL = async (
  points: number[][],
  desc: { title: string; desc: string }[] = [],
  name: string
) => {
  downloadPointsXLSL1(points, desc, name);
  downloadPointsXLSL2(
    points,
    desc.map((t) => ({ ...t, type: PointTypeEnum.other })),
    name + "本体边界坐标",
    "V1"
  );
};
