import vue from "@vitejs/plugin-vue";
import { fileURLToPath, URL } from "node:url";
import { resolve } from "path";
import { defineConfig } from "vite";
import AutoImport from "unplugin-auto-import/vite";

export default defineConfig(({ command, mode, isSsrBuild, isPreview }) => {
  // 读取自定义环境变量
  const plugins = [
    vue(), // 构建时复制 public 中的资源到 dist 目录
    AutoImport({
      imports: [
        // 你可以直接定义一个自定义解析器，或者指定文件路径
        {
          // 这里假设你的文件在 src/ZYWLTools/ZYWLLog.js，导出的函数名叫 log
          // 格式：{ '文件路径': ['导出的函数名', '别名'] }
          "@/components/ZYWLTools/ZYWLLog.js": [
            "log",
            "warn",
            "info",
            "time",
            "timeEnd",
          ],
          "@turf/turf": [["*", "turf"]], // 三方空间计算工具
          radashi: [["*", "_"]], // 拷贝工具
          "maptalks-gl": [["*", "maptalks"]], // 二维引擎
          shpjs: [["default", "shp"]],
          "kml-geojson": [["*", "kgUtil"]],
          "@zumer/snapdom": ["snapdom"],
          earcut: [["default", "earcut"]],
          "@public/libs/measure.js": [["default", "MeasureTool"]],
          uuid: [["v4", "uuidv4"]],
          "maptalks.heatmap": ["HeatLayer"],
          "@public/libs/heatmap.js": [["default", "h337"]],
        },
        "vue", // 保持默认导入 vue 的 API (ref, reactive 等)
      ],
    }),
  ];
  const resolveConfig = {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
      "@public": fileURLToPath(new URL("./public", import.meta.url)),
      // "@ZYWLGISCOMPONENTS": fileURLToPath(
      //   new URL("./src/components", import.meta.url),
      // ),
    },
  };
  if (mode === "release") {
    return {
      plugins: plugins,
      resolve: resolveConfig,
      build: {
        outDir: "release",
        lib: {
          entry: resolve(__dirname, "src/index.js"),
          name: "ZYWLGIS",
          // formats: ["es", "umd"],
          formats: ["es"],
          fileName: (format) => `ZYWLGIS.${format}.js`,
        },
        rollupOptions: {
          external: [
            "@turf/turf",
            "@element-plus/icons-vue",
            "uuid",
            "pinia",
            "lodash",
            "element-plus",
            "jquery",
            "vue",
            "vue-router",
            "html2canvas",
          ], // 添加 peerDependencies中的依赖 到 external 列表
          output: {
            globals: {
              vue: "Vue",
              "vue-router": "VueRouter",
              pinia: "Pinia",
              lodash: "_",
              jquery: "$",
              "element-plus": "ElementPlus",
              "@element-plus/icons-vue": "ElementPlusIconsVue", // 注意：实际全局名需确认
              "@turf/turf": "turf",
              uuid: "uuid",
              html2canvas: "html2canvas",
            },
          },
        },
      },
    };
  } else {
    return {
      plugins: plugins,
      resolve: resolveConfig,
      build: {
        outDir: "preview",
      },
    };
  }
});
