import dayjs from 'dayjs';
import { resolve } from 'path';
import type { ConfigEnv, UserConfig } from 'vite';
import { loadEnv } from 'vite';
import { OUTPUT_DIR } from './build/constant';
import { generateModifyVars } from './build/generate/generateModifyVars';
import { wrapperEnv } from './build/utils';
import { createVitePlugins } from './build/vite/plugin';
import { createProxy } from './build/vite/proxy';
import pkg from './package.json';
import { setI18n } from './setIn8n';

function pathResolve(dir: string) {
  return resolve(process.cwd(), '.', dir);
}

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

export default ({ command, mode }: ConfigEnv): UserConfig => {
  const root = process.cwd();

  const env = loadEnv(mode, root);

  // The boolean type read by loadEnv is a string. This function can be converted to boolean type
  const viteEnv = wrapperEnv(env);

  const {
    VITE_DEV,
    VITE_PORT,
    VITE_PUBLIC_PATH,
    VITE_PROXY,
    VITE_DROP_CONSOLE,
    VITE_GLOB_API_URL,
  } = viteEnv;

  // 国际化设置
  setI18n(VITE_DEV ? VITE_PROXY[0][1] : VITE_GLOB_API_URL);

  const isBuild = command === 'build';

  return {
    base: VITE_PUBLIC_PATH,
    root,
    resolve: {
      alias: [
        {
          find: 'vue-i18n',
          replacement: 'vue-i18n/dist/vue-i18n.cjs.js',
        },
        {
          find: '@/',
          replacement: pathResolve('src') + '/',
        },
        {
          find: '@ma/',
          replacement: pathResolve('src') + '/mainApp/',
        },
        {
          find: '@mi/',
          replacement: pathResolve('src') + '/microApp/',
        },
        {
          find: '@g/',
          replacement: pathResolve('src') + '/global/',
        },
        {
          find: '@t/',
          replacement: pathResolve('types') + '/',
        },
      ],
    },
    server: {
      https: false,
      host: true,
      port: VITE_PORT,
      proxy: createProxy(VITE_PROXY),
      headers: {
        'Access-Control-Allow-Origin': '*',
      },
    },
    logLevel: 'info',
    esbuild: {
      pure: VITE_DROP_CONSOLE ? ['console.log', 'debugger'] : [],
    },
    build: {
      target: 'es2015',
      cssTarget: 'chrome80',
      outDir: OUTPUT_DIR,
      chunkSizeWarningLimit: 2000,
    },
    define: {
      __INTLIFY_PROD_DEVTOOLS__: false,
      __APP_INFO__: JSON.stringify(__APP_INFO__),
    },
    css: {
      preprocessorOptions: {
        less: {
          modifyVars: generateModifyVars(),
          javascriptEnabled: true,
        },
      },
    },
    // The vite plugin used by the project. The quantity is large, so it is separately extracted and managed
    plugins: [
      ...createVitePlugins(viteEnv, isBuild),
      {
        name: 'singleHMR',
        handleHotUpdate({ modules, file }) {
          if (file.match(/xml$/)) return [];
          // 清掉所有依赖注入
          modules.map((m) => {
            m.importedModules = new Set();
            m.importers = new Set();
          });
          return modules;
        },
      },
    ],
    optimizeDeps: {
      // @iconify/iconify: The dependency is dynamically and virtually loaded by @purge-icons/generated, so it needs to be specified explicitly
      include: [
        '@iconify/iconify',
        'ant-design-vue/es/locale/zh_CN',
        'ant-design-vue/es/locale/en_US',
      ],
      exclude: ['consolidate'],
    },
  };
};
