import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import { mockDevServerPlugin } from 'vite-plugin-mock-dev-server'
import envConfig from './env.config.js'

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '')
  const currentEnv = envConfig[mode] || envConfig.development
  
  return {
  plugins: [
    vue(),
    createSvgIconsPlugin({
      iconDirs: [resolve(process.cwd(), 'src/icons')],
      symbolId: 'icon-[dir]-[name]',
    }),
    mockDevServerPlugin({
      logLevel: 'info',
    }),
  ],
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src'),
    },
    extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
  },
  assetsInclude: ['**/*.png', '**/*.jpg', '**/*.jpeg', '**/*.gif', '**/*.svg'],
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `
          $main-bg-color: #f5f5f5;
          $base-color: #409EFF;
          $nav-height: 80px;
          $side-close-width: 65px;
          $side-open-width: 160px;
          $sideBgColor: #121213;
          $sideTextColor: #fff;
          $sideActiveTextColor: #ffd04b;
        `,
      },
    },
  },
  server: {
    host: '0.0.0.0',
    port: 3000,
    open: false,
    proxy: {
      '/ws': {
        target: 'https://apis.map.qq.com',
        changeOrigin: true,
        ws: false,
      }
    }
  },
  build: {
    target: 'es2020',
    outDir: 'dist',
    assetsDir: 'assets',
    sourcemap: false,
    minify: 'terser',
    rollupOptions: {
      output: {
        chunkFileNames: 'js/[name]-[hash].js',
        entryFileNames: 'js/[name]-[hash].js',
        assetFileNames: '[ext]/[name]-[hash].[ext]',
        manualChunks: {
          vue: ['vue', 'vue-router', 'vuex'],
          elementPlus: ['element-plus'],
          echarts: ['echarts'],
        },
      },
    },
    terserOptions: {
      compress: {
        drop_console: false,
        drop_debugger: true,
      },
    },
  },
  define: {
    VE_ENV: {
      MODE: currentEnv.NODE_ENV,
      SERVER: currentEnv.SERVER,
      PYSERVER: currentEnv.PYSERVER,
      MOCK: currentEnv.MOCK
    },
  },
  optimizeDeps: {
    include: [
      'vue',
      'vue-router',
      'vuex',
      'element-plus',
      'axios',
      'echarts',
      'dayjs',
      'xe-utils',
    ],
  },
  esbuild: {
    loader: 'jsx',
    include: /src\/.*\.js$/,
    exclude: [],
  },
  }
})