import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { loadEnv } from "vite";
import { resolve } from "path";
//按需要加载
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import Icons from "unplugin-icons/vite";
import IconsResolver from "unplugin-icons/resolver";
import Inspect from "vite-plugin-inspect";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import vitePluginRemoveConsole from "vite-plugin-remove-console";

const pathSrc = resolve(__dirname, "src/types");

export default ({ command, mode }) => {
  return defineConfig({
    plugins: [
      vue(),
      createSvgIconsPlugin({
        iconDirs: [resolve(process.cwd(), "src/assets/icons")],
        symbolId: "icon-[dir]-[name]",
      }),

      AutoImport({
        imports: ["vue", "vuex", "vue-router"],

        resolvers: [
          ElementPlusResolver(),
          IconsResolver({
            prefix: "Icon",
          }),
        ],
        dts: resolve(pathSrc, "auto-imports.d.ts"),
      }),
      Components({
        resolvers: [
          // 自动注册图标组件
          IconsResolver({
            enabledCollections: ["ep"],
          }),
          // 自动导入 Element Plus 组件
          ElementPlusResolver(),
        ],

        dts: resolve(pathSrc, "components.d.ts"),
      }),
      Icons({
        autoInstall: true,
      }),
      Inspect(),
      vitePluginRemoveConsole(),
    ],
    // 服务器配置
    server: {
      host: "0.0.0.0",
      port: Number(loadEnv(mode, process.cwd()).VITE_APP_PORT),
      strictPort: false, // 端口被占用直接退出
      https: false, // 默认用http方式
      open: true, // 在开发服务器启动时自动在浏览器中打开应用程序
      proxy: {
        "/lic": {
          target: "http://192.168.1.252:8090",
        },
      },
      hmr: {
        overlay: true, // 屏蔽服务器报错
      },
    },
    resolve: {
      alias: {
        "@": "/src",
      },
    },
    css: {
      // css预处理器
      preprocessorOptions: {
        scss: {
          charset: false, //防止样式出现警告，中文
          additionalData: '@use "@/assets/styles/global.scss";',
          implementation: "sass-embedded",
          silenceDeprecations: ["legacy-js-api"],
        },
      },
    },
    build: {
      minify: "terser",
      chunkSizeWarningLimit: 1500,
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (id.includes("node_modules")) {
              const lib = id.split("node_modules/")[1].split("/")[0];
              if (lib === "vue" || lib.startsWith("@vue/")) {
                return "vue-bundle";
              }
              if (["lodash", "axios", "echarts"].includes(lib)) {
                return lib;
              }
              return "vendor";
            }
          },
          chunkFileNames: "assets/[name]-[hash:8].js",
          assetFileNames: "assets/[name]-[hash:8].[ext]",
        },
      },
    },
  });
};
