import type { UserConfig, ConfigEnv } from 'vite';
import { loadEnv } from 'vite';
import path, { resolve } from 'path';
import { codeInspectorPlugin } from 'code-inspector-plugin';
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
import { wrapperEnv } from './build/utils';
import { createVitePlugins } from './build/vite/plugin';
import { OUTPUT_DIR } from './build/constant';
import devProxy from './utils/devProxy';
import pkg from './package.json';
import { formatToDateTime } from './src/utils/dateUtil';
// @ts-ignore
import postcssPxToViewport from 'postcss-px-to-viewport';

const svg = createSvgIconsPlugin({
  // 要缓存的图标文件夹
  iconDirs: [path.resolve(__dirname, 'src/assets/svg')],
  // 执行 icon name 的格式
  symbolId: 'icon-[name]',
});

const { dependencies, devDependencies, name, version } = pkg;

const __APP_INFO__ = {
  pkg: { dependencies, devDependencies, name, version },
  lastBuildTime: formatToDateTime(new Date()),
};

export default ({ command, mode }: ConfigEnv): UserConfig => {
  const root = process.cwd();
  const env = loadEnv(mode, root);
  const viteEnv = wrapperEnv(env);
  const { VITE_PORT, VITE_GLOB_PROD_MOCK } = viteEnv;
  const prodMock = VITE_GLOB_PROD_MOCK;
  const isBuild = command === 'build';
  return {
    base: './',
    publicDir: 'public',
    esbuild: {},
    resolve: {
      alias: {
        '@': resolve(__dirname, './src'),
        assets: resolve(__dirname, './src/assets'),
        views: resolve(__dirname, './src/views'),
        components: resolve(__dirname, './src/components'),
      },
      extensions: ['.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
    },
    plugins: [
      createVitePlugins(viteEnv, isBuild, prodMock),
      svg,
      codeInspectorPlugin({
        bundler: 'vite',
        openIn: 'reuse',
      }),
    ],
    define: {
      __APP_INFO__: JSON.stringify(__APP_INFO__),
    },
    css: {
      devSourcemap: true,
      preprocessorOptions: {
        scss: {
          additionalData: `@use "@/styles/variables.scss" as *;`,
        },
      },
      postcss: {
        plugins: [
          postcssPxToViewport({
            unitToConvert: 'cpx', //自定义单位
            viewportWidth: 1920, //设计稿尺寸
            unitPrecision: 6, //单位转换后保留的精度
            propList: ['*'], //需要转换的属性列表
            viewportUnit: 'vw', //转换后的单位
            fontViewportUnit: 'vw', //字体转换后的单位
            selectorBlackList: ['ignore-'], //不需要转换的类名
            minPixelValue: 1, //最小转换的像素值
            mediaQuery: false, //是否在媒体查询中转换
            replace: true, //是否转换后直接更换属性值
            exclude: [/node_modules/], //忽略的文件
          }),
        ],
      },
    },
    server: {
      host: true,
      port: VITE_PORT,
      proxy: devProxy,
    },
    optimizeDeps: {
      include: ['dayjs', '@vicons/ionicons5', '@vicons/antd', '@element-plus/icons-vue'],
      exclude: [],
    },
    build: {
      target: 'es2015',
      outDir: OUTPUT_DIR,
      minify: 'terser',
      /**
       * 当 minify 为 minify 或 terser 打开注释
       */
      terserOptions: {
        compress: {
          keep_infinity: true,
          drop_console: true,
          drop_debugger: true,
        },
      },
      reportCompressedSize: false,
      chunkSizeWarningLimit: 2000,
    },
  };
};
