import { defineConfig, loadEnv } from 'vite'
import { resolve } from 'path'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import vue from '@vitejs/plugin-vue'
import myPlugin from './public/js/zip'

export default ({ mode }) => {
  const env = loadEnv(mode, process.cwd())
  return defineConfig({
    base: env.VITE_BASE_URL, // 设置打包路径
    build: {
      outDir: env.VITE_BASE_NAME,
      chunkSizeWarningLimit: 10240,
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString()
            }
          },
        },
      },
    },
    plugins: [
      vue(),
      myPlugin(env.VITE_BASE_NAME, env.VITE_BASE_URL),
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
      createSvgIconsPlugin({
        iconDirs: [resolve(process.cwd(), 'public/img/icons')],
        symbolId: 'icon-[name]',
      }),
    ],
    resolve: {
      extensions: ['.js', '.vue', '.json'], //可省略文件后缀
      alias: {
        vue: 'vue/dist/vue.esm-bundler.js',
        '@static': resolve('public'),
        '@': resolve(__dirname, 'src'), // 设置 `@` 指向 `src` 目录
        assets: resolve(__dirname, './src/assets'),
      },
    },

    server: {
      host: '0.0.0.0',
      port: 8080, // 设置服务启动端口号
      open: false, // 设置服务启动时是否自动打开浏览器
      cors: true, // 允许跨域
      hmr: {
        overlay: false, // 禁用服务器错误遮罩层
      },
      // 设置代理
      proxy: {

        [env.VITE_APP_REQUESTURL]: {
          target: env.VITE_APP_PROXYURL,
          // target: 'http://192.168.1.24:8081', //http://111.10.228.245:8088
          ws: true,
          changeOrigin: true,
          secure: false,
          rewrite: path => path.replace(env.VITE_APP_REQUESTURL, ''),
        },
        '/uri': {
          target: 'https://apis.map.qq.com',
          changeOrigin: true,
          secure: false,
        },
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          charset: false,
          javascriptEnabled: true,
          additionalData: `@import "./src/assets/styles/global.scss";`,
        },
      },
      postcss: {
        plugins: [
          {
            postcssPlugin: 'internal:charset-removal',
            AtRule: {
              charset: atRule => {
                if (atRule.name === 'charset') {
                  atRule.remove()
                }
              },
            },
          },
        ],
      },
    },
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false, // 允许使用define
    },
  })
}

