import { fileURLToPath, URL } from "node:url";
import { loadEnv, defineConfig } from "vite";
import pkg from "./package.json";
import dayjs from "dayjs";
import AutoImport from "unplugin-auto-import/vite";
import AutoComponents from "unplugin-vue-components/vite";
import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";
import legacy from "@vitejs/plugin-legacy";
import { createHtmlPlugin } from "vite-plugin-html";

// 当前执行node命令时文件夹的地址（工作目录）
const root = process.cwd();

// 打包后静态资源的存放路径
const assetsDir = "assets";

// __APP_INFO__
const { dependencies, devDependencies, name, version } = pkg;
const appVersion = dayjs().format("YYYYMMDDHHmm");
const lastBuildTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
const __APP_INFO__ = {
  pkg: { dependencies, devDependencies, name, version },
  version: appVersion,
  lastBuildTime,
};

/**
 * Configuring Vite
 *
 * @see https://vitejs.dev/config/
 */
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, root);

  return {
    base: "./",
    plugins: [
      vue(),
      vueJsx(),
      AutoImport({
        imports: ["vue", "vue-router"],
        // dirs: ['./src/hooks/**'],
        dts: "./src/auto-imports.d.ts",
        eslintrc: {
          enabled: true,
        },
      }),
      AutoComponents({
        dirs: ["./src/components"],
        extensions: ["vue", "jsx", "tsx"],
        dts: "./src/auto-components.d.ts",
      }),
      createHtmlPlugin({
        inject: {
          data: {
            title: env.VITE_APP_TITLE,
          },
        },
        minify: true,
      }),
      env.VITE_LEGACY === "true" ? legacy() : null,
    ],
    server: {
      port: Number(env.VITE_PORT),
      proxy: {
        "/super_cloud": {
          target: `https://wx.palmnest.com`, // https://wx.palmnest.com/super_cloud
          changeOrigin: true,
          secure: false,
          // followRedirects: true,
          // cookieDomainRewrite: '', // 使用 cookieDomainRewrite 或者是 设置cookie 那行都可以
          configure: (proxy, options) => {
            proxy.on("proxyReq", (proxyReq, req, res) => {
              proxyReq.removeHeader("referer");
              proxyReq.removeHeader("origin");
            });

            proxy.on("proxyRes", (proxyRes, req, res) => {
              // 设置cookie
              if (proxyRes.headers["set-cookie"]) {
                proxyRes.headers["set-cookie"] = replaceDomain(
                  Array.isArray(proxyRes.headers["set-cookie"])
                    ? proxyRes.headers["set-cookie"][0]
                    : proxyRes.headers["set-cookie"]
                );
              }
              function replaceDomain(value) {
                return value
                  .replace(/Domain=[a-z.]*;/, "")
                  .replace(/secure=.*;/, "");
              }
            });
          },
        },
      },
    },
    build: {
      assetsDir: assetsDir,
      sourcemap: false,
      chunkSizeWarningLimit: 1500,
      rollupOptions: {
        output: {
          entryFileNames: `${assetsDir}/[name].${appVersion}.js`,
          chunkFileNames: `${assetsDir}/[name].${appVersion}.js`,
          assetFileNames: `${assetsDir}/[ext]/[name].${appVersion}.[ext]`,
        },
      },
    },

    resolve: {
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url)),
      },
    },
    define: {
      __APP_INFO__: JSON.stringify(__APP_INFO__),
    },
    css: {
      modules: {
        localsConvention: "camelCaseOnly",
      },
      preprocessorOptions: {
        less: {
          modifyVars: {
            hack: `true; @import './src/styles/variable.less';`,
          },
          javascriptEnabled: true,
        },
      },
    },
  };
});
