import { defineConfig, loadEnv } from 'vite'
import eslint from 'vite-plugin-eslint'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import tsconfigPaths from 'vite-tsconfig-paths'
import { vanillaExtractPlugin } from '@vanilla-extract/vite-plugin'
import react from '@vitejs/plugin-react'
import path from 'path'
import { visualizer } from 'rollup-plugin-visualizer'

export default defineConfig(({ mode }) => {
  // const env = loadEnv(mode, process.cwd(), '')
  // const base = env.VITE_APP_BASE_PATH || '/'
  const isProduction = mode === 'production'

  return {
    base: '/',
    plugins: [
      react({
        // 添加 React 插件的优化配置
        babel: {
          parserOpts: {
            plugins: ['decorators-legacy', 'classProperties']
          }
        }
      }),
      eslint({
        // 配置选项
        fix: true, // 自动修复 ESLint 错误
        include: ['src/**/*.js', 'src/**/*.jsx', 'src/**/*.ts', 'src/**/*.tsx'], // 检查的文件范围
        exclude: ['node_modules'], // 排除的文件
        cache: false, // 是否启用缓存
        emitError: true, // 是否将 ESLint 错误输出到控制台
        emitWarning: true // 是否将 ESLint 警告输出到控制台
      }),
      vanillaExtractPlugin({
        identifiers: ({ debugId }) => `${debugId}`
      }),
      tsconfigPaths(),
      createSvgIconsPlugin({
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
        symbolId: 'icon-[dir]-[name]'
      }),
      isProduction &&
        visualizer({
          open: true,
          gzipSize: true,
          brotliSize: true,
          template: 'treemap' // 使用树形图更直观
        })
    ].filter(Boolean),

    server: {
      open: true,
      host: true,
      port: 5657,
      proxy: {
        '/api': {
          target: 'https://pre.yaoeasier.com/',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ''),
          secure: false
        }
      }
    },

    build: {
      target: 'esnext',
      minify: 'esbuild',
      sourcemap: !isProduction,
      cssCodeSplit: true,
      chunkSizeWarningLimit: 1500,
      rollupOptions: {
        output: {
          manualChunks: {
            'vendor-core': ['react', 'react-dom', 'react-router'],
            'vendor-ui': [
              'antd',
              '@ant-design/icons',
              '@ant-design/cssinjs',
              'framer-motion',
              'styled-components'
            ],
            'vendor-utils': ['axios', 'dayjs', 'i18next', 'zustand', '@iconify/react'],
            'vendor-charts': ['apexcharts', 'react-apexcharts']
          }
        }
      }
    },
    resolve: {
      alias: {
        '@': path.join(__dirname, './src'),
        '#': path.join(__dirname, './types')
      }
    },
    // 优化依赖预构建
    optimizeDeps: {
      include: [
        'react',
        'react-dom',
        'react-router',
        'antd',
        '@ant-design/icons',
        'axios',
        'dayjs'
      ],
      exclude: ['@iconify/react'] // 排除不需要预构建的依赖
    },

    // esbuild 优化配置
    esbuild: {
      drop: isProduction ? ['console', 'debugger'] : [],
      legalComments: 'none',
      target: 'esnext'
    }
  }
})
