import type { ConfigEnv, UserConfig } from 'vite';
import { loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import path, { resolve } from 'path';
import legacy from '@vitejs/plugin-legacy';
import Pages from 'vite-plugin-pages';
import { getLocalApiProxy } from './apiMap.config';
import { spaFallbackWithDot } from './plugins/vitePluginDotFallback';
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
import { viteExternalsPlugin } from 'vite-plugin-externals';

// 引入模块联邦
import federation from '@originjs/vite-plugin-federation';

export default ({ mode }: ConfigEnv): UserConfig => {
  const root = process.cwd();
  const env = loadEnv(mode, root);
  return {
    base: env.VITE_APP_PUBLIC_PATH,
    // 兼容 Cli
    define: {
      'process.env.VUE_APP_API_BASE_URL': JSON.stringify(env.VITE_APP_API_BASE_URL),
      'process.env.VUE_APP_PUBLIC_PATH': JSON.stringify(env.VITE_APP_PUBLIC_PATH),
    },
    plugins: [
      // 模块联邦：打包出错，先注释掉
      // spaFallbackWithDot(),
      // legacy({
      //   targets: ['defaults', 'not IE 11'],
      // }),
      vue(),
      vueJsx(),
      Pages({
        pagesDir: 'src/views',
        extensions: ['vue'],
      }),
      createSvgIconsPlugin({
        iconDirs: [path.resolve(__dirname, './src/assets/ICP')],
        symbolId: 'icon-[dir]-[name]',
        customDomId: '__svg__icons__icp__dom__',
      }),

      federation({
        name: '@remote/icpx-platform', // 远程模块名称
        filename: 'remoteEntry.js', // 远程模块入口文件，与本地模块中`remotes`配置相对应
        exposes: {
          // 公共页面
          './Create': './src/views/platform/components/Create.vue',
          './View': './src/views/platform/components/Detail.vue',
          './Edit': './src/views/platform/components/Edit.vue',
          './Encoder': './src/views/platform/components/Encoder.vue',
          './NoAuthPage': './src/views/platform/components/NoAuthPage.vue',
          './ObjectViewer': './src/views/platform/components/ObjectViewer.vue',
          './ResetPass': './src/views/platform/components/ResetPass.vue',
          './UserAvatar': './src/views/platform/components/UserAvatar.vue',
          './MemberTransfer': './src/views/platform/components/MemberManagement/MemberTransfer.vue',
          './PeopleSelector': './src/views/platform/components/PeopleSelector/Index.vue',
          // 公共方法
          './commonApi': './src/api/commonApi/index.ts',
          './utils': './src/utils/index.ts',
          // 多语言
          // './lang/zh-CN': './src/locales/lang/zh-CN.ts',
          // './lang/en-US': './src/locales/lang/en-US.ts',
          './lang': './src/locales/lang/index.ts',
        },
        // 对外提供的组件所依赖的第三方依赖
        shared: [
          'vue-router',
          'vue',
          'vue-i18n',
          'vuex',
          'vuex-persistedstate',
          '@crami/ui',
          '@crami/locale',
          '@crami/http',
          'mitt',
          // '@crami/bui',
          // '@crami/bui-platform',
          // '@crami/bui-types',
          // '@crami/compiler',
          // '@crami/icons',
          // '@crami/ui-types',
        ],
      }),
    ],
    build: {
      cssCodeSplit: false,
      chunkSizeWarningLimit: 2048,
      rollupOptions: {
        // 模块联邦：打包出错，先注释掉
        // input: {
        //   main: resolve(__dirname, 'index.html'),
        //   subpage: resolve(__dirname, 'pages/index.html'),
        // },
        // external: ['@alifd/next'],
        output: {
          manualChunks: {
            // 将vue-router的合并打包去掉，要不useRoute会报错
            // vue: ['vue', 'vuex', 'vue-router'],
            vue: ['vue', 'vuex'],
            antdv: ['ant-design-vue', '@ant-design/icons-vue'],
            dayjs: ['dayjs'],
          },
        },
      },
      target: ['edge90', 'chrome90', 'firefox90', 'safari15'],
    },
    resolve: {
      alias: [
        { find: 'dayjs/locale', replacement: 'dayjs/esm/locale' },
        { find: '~@', replacement: path.join(__dirname, './src') },
        { find: '@', replacement: path.join(__dirname, './src') },
        { find: '~', replacement: path.join(__dirname, './src/assets') },
        { find: 'lodash', replacement: 'lodash-es' },
        { find: 'ant-design-vue/lib', replacement: 'ant-design-vue/es' },
        { find: '@crami/ui/lib', replacement: '@crami/ui/es' },
        { find: '@crami/bui/lib', replacement: '@crami/bui/es' },
      ],
    },
    optimizeDeps: {
      include: [
        'ant-design-vue/es/locale/en_US',
        'ant-design-vue/es/locale/zh_CN',
        'store/plugins/expire',
        'ant-design-vue/es/form',
        'dayjs',
        'dayjs/locale/en',
        'dayjs/locale/zh-cn',
        '@ant-design/icons-vue',
        'lodash-es',
      ],
    },
    css: {
      preprocessorOptions: {
        less: {
          modifyVars: {
            hack: 'true; @import "~/styles/variables.less";@import "@crami/ui/es/style/themes/default";',
            'root-entry-name': 'variable',
          },
          // DO NOT REMOVE THIS LINE
          javascriptEnabled: true,
        },
      },
    },
    server: {
      host: true,
      port: 4001,
      proxy: {
        // '/api/studio-admin': {
        //   target: 'http://10.0.88.243:59151',
        //   ws: true,
        //   changeOrigin: true,
        //   rewrite: path => path.replace(/^\/api\/studio-admin/, '/studio-admin'),
        // },
        ...getLocalApiProxy(),
        '/api': {
          // target: 'http://10.0.88.243:59151', //统一服务
          target: 'http://10.0.88.239:51001/', //统一服务
          ws: true,
          changeOrigin: true,
          rewrite: path => path.replace(/^\/api/, ''),
        },
      },
    },
  };
};
