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

const DEFAULT_BUILD_BASE = '/bxztpc/'

const normalizeBasePath = (value) => {
  if (!value || value === '/') {
    return '/'
  }
  let base = value.trim()
  if (!base.startsWith('/')) {
    base = `/${base}`
  }
  if (!base.endsWith('/')) {
    base = `${base}/`
  }
  return base
}

const resolveCliBase = () => {
  const argv = process.argv || []
  const directFlagIndex = argv.indexOf('--base')
  if (directFlagIndex !== -1 && argv[directFlagIndex + 1]) {
    return argv[directFlagIndex + 1]
  }
  const customFlagIndex = argv.indexOf('--basePath')
  if (customFlagIndex !== -1 && argv[customFlagIndex + 1]) {
    return argv[customFlagIndex + 1]
  }
  const equalArg = argv.find(arg => arg.startsWith('--base='))
  if (equalArg) {
    return equalArg.split('=')[1]
  }
  const equalCustomArg = argv.find(arg => arg.startsWith('--basePath='))
  if (equalCustomArg) {
    return equalCustomArg.split('=')[1]
  }
  return undefined
}

export default defineConfig(({ command, mode }) => {
  const env = loadEnv(mode, resolve(__dirname, '../..'), '')
  const baseCandidate =
    command === 'build'
      ? resolveCliBase() ??
        env.VITE_BASE_PATH ??
        env.BASE_PATH ??
        process.env.BASE_PATH ??
        DEFAULT_BUILD_BASE
      : '/'
  const resolvedBase =
    command === 'build' ? normalizeBasePath(baseCandidate) : '/'
  const cesiumBaseUrl = resolvedBase === '/' ? '/cesium' : `/cesium`

  return {
    envDir: resolve(__dirname, '../..'),
    base: resolvedBase,
    plugins: [
      vue(),
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
      createSvgIconsPlugin({
        iconDirs: [
          resolve(__dirname, 'src/assets/icons/svg'),
          resolve(__dirname, 'src/map/assets/icons')
        ],
        symbolId: 'icon-[dir]-[name]',
      }),
      cesium(),
    ],
    define: {
      CESIUM_BASE_URL: JSON.stringify(cesiumBaseUrl),
    },
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src'),
        '@shared': resolve(__dirname, '../shared')
      }
    },
    server: {
      port: 3000,
      open: true,
      cors: true,
      proxy: {
        '/snow-ops-platform': {
          // target: 'http://192.168.110.16:8661/',
          target: 'http://8.137.54.85:8661/', //测试环境
          // target: 'http://192.168.110.36:8661/', //张启生本地环境
          changeOrigin: true,
        },
      }
    },
    build: {
      outDir: 'dist',
      assetsDir: 'assets',
      sourcemap: false,
      rollupOptions: {
        output: {
          chunkFileNames: 'js/[name]-[hash].js',
          entryFileNames: 'js/[name]-[hash].js',
          assetFileNames: '[ext]/[name]-[hash].[ext]'
        }
      }
    },
  }
})
