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";

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(),
    ],
    // 服务器配置
    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")) {
              return id
                .toString()
                .split("node_modules/")[1]
                .split("/")[0]
                .toString();
            }
          },
          chunkFileNames: "assets/[name]-[hash].js",
          assetFileNames: "assets/[name]-[hash].[ext]",
        },
      },
      terserOptions: {
        compress: {
          drop_console: true, // 生产环境移除console
          drop_debugger: true, // 生产环境移除debugger
        },
      },
    },
  });
};
