import { resolve } from 'path'
import Vue from '@vitejs/plugin-vue'
import VueJsx from '@vitejs/plugin-vue-jsx'
import progress from 'vite-plugin-progress'
import EslintPlugin from 'vite-plugin-eslint'
import PurgeIcons from 'vite-plugin-purge-icons'
import { ViteEjsPlugin } from 'vite-plugin-ejs'
// @ts-ignore
import ElementPlus from 'unplugin-element-plus/vite'
import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import viteCompression from 'vite-plugin-compression'
import topLevelAwait from 'vite-plugin-top-level-await'
import VueI18nPlugin from '@intlify/unplugin-vue-i18n/vite'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons-ng'
import UnoCSS from 'unocss/vite'

// vs code 编辑器配置
import monacoEditorPlugin from 'vite-plugin-monaco-editor'
import MEditor from '../monacoEditor'

// import { visualizer } from 'rollup-plugin-visualizer'
import externalGlobals from 'rollup-plugin-external-globals'
import { createHtmlPlugin } from 'vite-plugin-html'

export function createVitePlugins() {
  const root = process.cwd()
  const CDN_VERSIONS = {
    vue: '3.4.29',
    vueDemi: '0.14.7',
    avue: '3.7.1',
    vxePcUi: '4.0.17',
    vxeTable: '4.7.17',
    echarts: '5.4.3',
    echartsWordcloud: '2.1.0',
    sass: '1.69.5',
  }

  // 路径查找
  function pathResolve(dir: string) {
    return resolve(root, '.', dir)
  }

  return [
    Vue(),
    VueJsx(),
    UnoCSS(),
    progress(),
    PurgeIcons(),
    ElementPlus({}),
    AutoImport({
      include: [
        /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
        /\.vue$/,
        /\.vue\?vue/, // .vue
        /\.md$/ // .md
      ],
      imports: [
        'vue',
        'vue-router',
        // 可额外添加需要 autoImport 的组件
        {
          '@/hooks/web/useI18n': ['useI18n'],
          '@/hooks/web/useMessage': ['useMessage'],
          '@/utils/formRules': ['required'],
          '@/utils/dict': ['DICT_TYPE'],
          '@/hooks/design/useCrudHeight': ['useCrudHeight'],
          '@/hooks/design/useCrudPermi': ['useCrudPermi']
        }
      ],
      dts: 'src/types/auto-imports.d.ts',
      resolvers: [ElementPlusResolver(), IconsResolver({ prefix: 'Icon' })],
      eslintrc: {
        enabled: false, // Default `false`
        filepath: './.eslintrc-auto-import.json', // Default `./.eslintrc-auto-import.json`
        globalsPropValue: true // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
      }
    }),
    Components({
      // 生成自定义 `auto-components.d.ts` 全局声明
      dts: 'src/types/auto-components.d.ts',
      // 自定义组件的解析器
      resolvers: [ElementPlusResolver(), IconsResolver({ enabledCollections: ['ep'] })],
      globs: [
        'src/components/**/**.{vue, md}',
        '!src/components/DiyEditor/components/mobile/**',
        '!src/components/LowFormDesign/components'
      ]
    }),
    Icons({
      autoInstall: true
    }),
    EslintPlugin({
      cache: false,
      include: ['src/**/*.vue', 'src/**/*.ts', 'src/**/*.tsx'] // 检查的文件
    }),
    VueI18nPlugin({
      runtimeOnly: true,
      compositionOnly: true,
      include: [resolve(__dirname, 'src/locales/**')]
    }),
    createSvgIconsPlugin({
      iconDirs: [pathResolve('src/assets/svgs')],
      symbolId: 'icon-[dir]-[name]',
    }),
    viteCompression({
      verbose: true, // 是否在控制台输出压缩结果
      disable: false, // 是否禁用
      threshold: 10240, // 体积大于 threshold 才会被压缩,单位 b
      algorithm: 'gzip', // 压缩算法,可选 [ 'gzip' , 'brotliCompress' ,'deflate' , 'deflateRaw']
      ext: '.gz', // 生成的压缩包后缀
      deleteOriginFile: false //压缩后是否删除源文件
    }),
    ViteEjsPlugin(),
    topLevelAwait({
      // https://juejin.cn/post/7152191742513512485
      // The export name of top-level await promise for each chunk module
      promiseExportName: '__tla',
      // The function to generate import names of top-level await promise in each chunk module
      promiseImportName: (i) => `__tla_${i}`
    }),
    monacoEditorPlugin({
      languageWorkers: ['editorWorkerService', 'typescript', 'json', 'css'],
      customWorkers: [
        {
          label: 'java',
          entry: 'monaco-editor/esm/vs/basic-languages/java/java.contribution'
        },
        {
          label: 'mysql',
          entry: 'monaco-editor/esm/vs/basic-languages/sql/sql.contribution'
        }
      ],
    }),
    MEditor.nlsPlugin({
      //monacoEditor汉化
      locale: MEditor.Languages.zh_hans,
      localeData: MEditor.i18n
    }),
    // visualizer({
    //   open: true // 构建完成后自动打开浏览器
    // }),
    createHtmlPlugin({
      inject: {
        data: {
          isProd: process.env.NODE_ENV === 'production',
          cdnJs: [
            `/plugins/vue/${CDN_VERSIONS.vue}/vue.global.prod.js`,
            `/plugins/vueDemi/${CDN_VERSIONS.vueDemi}/index.iife.js`,
            `/plugins/avue/${CDN_VERSIONS.avue}/avue.min.js`,
            '/plugins/vxe/xe-utils.umd.min.js',
            `/plugins/vxe/vxe-pc-ui_${CDN_VERSIONS.vxePcUi}/index.umd.min.js`,
            `/plugins/vxe/vxe-table_${CDN_VERSIONS.vxeTable}/index.umd.min.js`,
            `/plugins/echarts/${CDN_VERSIONS.echarts}/echarts.min.js`,
            `/plugins/echartsWordcloud/${CDN_VERSIONS.echartsWordcloud}/echarts-wordcloud.min.js`,
            `/plugins/sass/${CDN_VERSIONS.sass}/sass.dart.js`,
            `/plugins/sass/${CDN_VERSIONS.sass}/sass.default.js`,
            '/plugins/other/highlight.min.js'
          ],
          cdnCss: [
            `/plugins/avue/${CDN_VERSIONS.avue}/index.css`,
            `/plugins/vxe/vxe-pc-ui_${CDN_VERSIONS.vxePcUi}/style.min.css`,
            `/plugins/vxe/vxe-table_${CDN_VERSIONS.vxeTable}/style.min.css`
          ]
        }
      }
    }),
    {
      ...externalGlobals({
        vue: 'Vue',
        'vue-demi': 'VueDemi',
        '@smallwei/avue': 'AVUE',
        'xe-utils': 'XEUtils',
        'vxe-pc-ui': 'VxeUI',
        'vxe-table': 'VXETable',
        echarts: 'echarts',
        'echarts-wordcloud': 'echarts',
        sass: 'sass',
        'highlight.js': 'hljs'
      }),
      enforce: 'post',
      apply: 'build'
    }
  ]
}
