import { resolve } from "path";
import { defineConfig, loadEnv } from "vite";
import Components from "unplugin-vue-components/vite";
import { AntDesignVueResolver } from "unplugin-vue-components/resolvers";
import vue from "@vitejs/plugin-vue";
import vueSetupExtend from "unplugin-vue-setup-extend-plus/vite";
import vueJsx from "@vitejs/plugin-vue-jsx";
import UnoCSS from "unocss/vite";
import antdvNames from "./antdvNames";
const root = resolve(__dirname, "src/render");
const outDir = resolve(__dirname, "dist/");

export default defineConfig((configEnv) => {
  const viteEnv = loadEnv(configEnv.mode, process.cwd());
  const processEnvValues = {
    "process.env": Object.entries(viteEnv).reduce((prev, [key, val]) => {
      return {
        ...prev,
        [key]: val,
      };
    }, {}),
  };
  return {
    root,
    base: "./",
    // publicDir: outDir,
    build: {
      outDir,
    },
    resolve: {
      alias: {
        "@": root,
        qs: "rollup-plugin-node-polyfills/polyfills/qs",
      },
      extensions: [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json", ".vue"],
    },
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
          additionalData: `@import "${resolve(root, "styles/color.less")}";`,
        },
      },
    },
    define: { ...processEnvValues },
    plugins: [
      vue(),
      vueJsx(),
      vueSetupExtend(),
      UnoCSS(),
      Components({
        resolvers: [
          (componentName) => {
            if (componentName?.startsWith("Qm"))
              return { name: componentName.slice(0), from: "@qmth/ui" };
          },
          // AntDesignVueResolver({
          //   importStyle: false,
          // }),

          (componentName) => {
            if (componentName?.startsWith("A")) {
              if (antdvNames.includes(componentName.slice(1))) {
                return {
                  name: componentName.slice(1),
                  from: "@qmth/ui",
                };
              }
            }
          },
        ],
      }),
    ],
    server: {
      host: "0.0.0.0",
      port: 8090,
      proxy: {
        "/api": {
          target: viteEnv.VITE_APP_PROXY_URL,
          changeOrigin: true,
        },
      },
    },
  };
});
