import vue from '@vitejs/plugin-vue';
import viteCompression from 'vite-plugin-compression'
import { resolve } from 'path';
import { defineConfig, loadEnv, ConfigEnv } from 'vite';

const pathResolve = (dir: string): any => {
	return resolve(__dirname, '.', dir);
};

const alias: Record<string, string> = {
	'/@': pathResolve('./src/'),
	'vue-i18n': 'vue-i18n/dist/vue-i18n.cjs.js',
};

const viteConfig = defineConfig((mode: ConfigEnv) => {
	const env = loadEnv(mode.mode, process.cwd());
	return {
		plugins: [
			vue(),
			viteCompression({
				threshold: 1024 * 20, // 对大于 20k 的文件进行压缩
				// filter: /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i, // 需要压缩的文件
				algorithm: 'gzip', // 压缩方式
				ext: 'gz', // 后缀名
				deleteOriginFile: false, // 压缩后是否删除压缩源文件
			})
		],
		root: process.cwd(),
		resolve: { alias },
		base: mode.command === 'serve' ? './' : env.VITE_PUBLIC_PATH,
		optimizeDeps: {
			include: ['element-plus/lib/locale/lang/zh-cn', 'element-plus/lib/locale/lang/en', 'element-plus/lib/locale/lang/zh-tw'],
		},
		server: {
			port: env.VITE_PORT as unknown as number,
			host: true,
			open: true,
			hmr: true,
			// proxy: {
			// 	[env.VITE_NGINX_PROXY ? env.VITE_NGINX_PROXY : '/xxxxxxxxxxxxx']: {
			// 		target: env.VITE_SERVER_ORIGIN,
			// 		ws: true,
			// 		changeOrigin: true,
			// 		// rewrite: (path) => path.replace(/^\/api/, ''),
			// 	},
			// },
		},
		build: {
			outDir: 'sagoo-iot',
			sourcemap: false,
			cssCodeSplit: false,
			chunkSizeWarningLimit: 1500,
			rollupOptions: {
				output: {
					entryFileNames: `assets/[name].${new Date().getTime()}.js`,
					chunkFileNames: `assets/[name].${new Date().getTime()}.js`,
					assetFileNames: `assets/[name].${new Date().getTime()}.[ext]`,
					compact: true,
					manualChunks: {
						vue: ['vue', 'vue-router', 'vuex'],
						echarts: ['echarts'],
					},
				},
			},
		},
		css: {
			postcss: {
				plugins: [
					{
						postcssPlugin: 'internal:charset-removal',
						AtRule: {
							charset: (atRule) => {
								if (atRule.name === 'charset') {
									atRule.remove();
								}
							},
						},
					},
				],
			},
		},
		define: {
			__VUE_I18N_LEGACY_API__: JSON.stringify(false),
			__VUE_I18N_FULL_INSTALL__: JSON.stringify(false),
			__INTLIFY_PROD_DEVTOOLS__: JSON.stringify(false),
		},
	};
});

export default viteConfig;
