import { fileURLToPath, URL } from 'node:url'

import { defineConfig,loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueRouter from 'unplugin-vue-router/vite'
import vueLayouts from 'vite-plugin-vue-layouts'
import vueComponents from 'unplugin-vue-components/vite'
import autoImports from 'unplugin-auto-import/vite'
import Unocss from 'unocss/vite'
import { NaiveUiResolver } from 'unplugin-vue-components/resolvers'
import Components from 'unplugin-vue-components/vite'
import Pages from 'vite-plugin-pages'

export default defineConfig(({ mode }) => {

  const viteEnv = loadEnv(mode, process.cwd())
  const { VITE_PUBLIC_PATH, VITE_PROXY_TARGET } = viteEnv

  return {
    base: VITE_PUBLIC_PATH || '/',
    plugins: [
      vueRouter(),
      vue(),
      Unocss(),
      Pages({
        dirs: 'src/pages',  // 需要生成路由的文件目录
        exclude: ['**/components/*.vue']  // 排除在外的目录，即不将所有 components 目录下的 .vue 文件生成路由
      }),
      vueLayouts(),
      vueComponents(),
      autoImports({
        imports: ['vue', 'vue-router', 'vue-i18n', {
          'naive-ui': [
            'useDialog',
            'useMessage',
            'useNotification',
            'useLoadingBar'
          ]
        }],
      }),
      Components({
        resolvers: [NaiveUiResolver()]
      })
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    server: {
      host: '0.0.0.0',
      port: 3300,
      open: false,
      proxy: {
        '/api': {
          target: VITE_PROXY_TARGET,
          changeOrigin: true,
          rewrite: path => path.replace(/^\/api/, ''),
          secure: false,
          // configure: (proxy, options) => {
          //   // 配置此项可在响应头中看到请求的真实地址
          //   proxy.on('proxyRes', (proxyRes, req) => {
          //     proxyRes.headers['x-real-url'] = new URL(req.url || '', options.target)?.href || ''
          //   })
          // },
        },
      },
    },
  }
})

