import path from 'node:path'
import { defineConfig, splitVendorChunk } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import vueSetupExtend from 'unplugin-vue-setup-extend-plus/vite'
import ElementPlus from 'unplugin-element-plus/vite'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import eslint from 'vite-plugin-eslint'
import useElectronPlugin from './electron-plugin'
import server from './server.config'

const resolvePath = (...args: string[]) => {
  return path.resolve(__dirname, ...args)
}

export default defineConfig({
  base: '/',
  plugins: [
    vue(),
    vueJsx(),
    ElementPlus({ useSource: true }),
    createSvgIconsPlugin({
      iconDirs: [resolvePath('src/assets/icons')],
      symbolId: 'icon-[dir]-[name]',
      customDomId: '__svg__icons__dom__',
    }),
    vueSetupExtend(),
    eslint(),
    useElectronPlugin(),
  ],
  resolve: {
    extensions: ['.js', '.ts', '.jsx', '.tsx', '.vue', '.json'],
    alias: [
      { find: '@', replacement: resolvePath('src') },
      { find: '@img', replacement: resolvePath('src/assets/images') },
      { find: '@style', replacement: resolvePath('src/assets/styles') },
    ],
  },
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@use "@style/element/index.scss" as *; \n @use "@style/var.scss" as *;`,
      },
    },
  },
  build: {
    outDir: 'dist/web',
    emptyOutDir: true,
    rollupOptions: {
      output: {
        assetFileNames(assetInfo) {
          return `${getExtName(assetInfo.name)}/[name].[hash][extname]`
        },
        chunkFileNames: 'js/[name].[hash].js',
        entryFileNames: 'js/[name].[hash].js',
        manualChunks(id, mode) {
          const m = manualChunks.find((m) => id.includes(`node_modules/${m}`))
          return m ? `third/${m}` : splitVendorChunk()(id, mode)
        },
      },
    },
  },
  server,
})

const manualChunks = [
  // 'echarts',
  // "lodash-es",
  // "dayjs",
  // "vue-echarts",
  // 'element-plus',
  // "zrender",
]

const IMAGE_EXT = /\.(png|jpg|jpeg|gif|webp)$/
const SVG_EXT = /\.(svg)$/
const FONT_EXT = /\.(ttf|otf|woff|woff2)$/

const getExtName = (name: string) => {
  if (IMAGE_EXT.test(name)) {
    return 'image'
  } else if (SVG_EXT.test(name)) {
    return 'icons'
  } else if (FONT_EXT.test(name)) {
    return 'fonts'
  } else {
    return '[ext]'
  }
}
