import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import alias from '@rollup/plugin-alias';
import vueJsx from '@vitejs/plugin-vue-jsx';
import path from 'path';
import Icons from 'unplugin-icons/vite';
import IconsResolver from 'unplugin-icons/resolver';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { createHtmlPlugin } from 'vite-plugin-html';
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
  const env = loadEnv(mode, process.cwd(), '');
  return {
    plugins: [
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
        // 指定symbolId格式
        symbolId: 'icon-[dir]-[name]'
      }),
      vue(),
      vueJsx(),
      createHtmlPlugin({
        minify: true,
        template: 'index.html',
        inject: {
          data: {
            title: env.APP_NAME
          }
        }
      }),
      alias({
        entries: [
          {
            find: '@',
            replacement: path.resolve(__dirname, '.', 'src')
          }
        ]
      }),
      AutoImport({
        // 目标文件
        include: [
          /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
          /\.vue$/,
          /\.vue\?vue/, // .vue
          /\.md$/ // .md
        ],
        // 生成配置文件，如果是ts项目，通常我们会把声明文件放在根目录/types中，注意，这个文件夹需要先建好，否则可能导致等下无法往里生成auto-imports.d.ts文件
        // dts: 'types/auto-imports.d.ts',
        vueTemplate: true,
        dts: path.resolve(__dirname, 'types', 'auto-imports.d.ts'), // 配置文件生成位置，默认是根目录 /auto-imports.d.ts
        imports: ['vue', 'vue-router', 'pinia', '@vueuse/core'],
        // eslint报错解决
        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')
        },
        resolvers: [
          // 自动导入 Element Plus 相关函数，如：ElMessage, ElMessageBox... (带样式)
          ElementPlusResolver(),
          // 自动导入图标组件
          IconsResolver({
            prefix: 'Icon'
          })
        ]
      }),
      Components({
        resolvers: [
          // 自动注册图标组件
          IconsResolver({
            enabledCollections: ['ep'] //@iconify-json/ep 是 Element Plus 的图标库
          }),
          // 自动导入 Element Plus 组件//dev环境会特别慢加上,build的时候可以放开
          ElementPlusResolver()
        ],
        dirs: ['src/components/', 'src/layout/'],

        extensions: ['vue'],

        deep: true,

        // dts: true,
        dts: path.resolve(__dirname, 'types', 'components.d.ts'), // 配置文件生成位置，默认是根目录 /components.d.ts

        include: [/\.vue$/, /\.vue\?vue/],

        exclude: [
          /[\\/]node_modules[\\/]/,
          /[\\/]\.git[\\/]/,
          /[\\/]\.nuxt[\\/]/
        ]
      }),
      Icons({
        compiler: 'vue3',
        autoInstall: true
      })
    ],
    optimizeDeps: {
      include: [
        'vue',
        'vue-router',
        'element-plus/es/locale/lang/zh-cn',
        'element-plus/es/locale/lang/en',
        'pinia',
        '@vueuse/core',
        'axios',
        '@wangeditor/editor',
        '@wangeditor/editor-for-vue'
      ]
    },
    publicDir: false,
    define: {
      BASE_URL: env.BASE_URL
    },
    css: {
      preprocessorOptions: {
        // 全局样式引入
        scss: {
          javascriptEnabled: true,
          additionalData: `
          @use "src/styles/var.scss" as *;
          `
        }
      }
    },
    preprocessorOptions: {
      scss: {
        // additionalData: `@use "@/assets/styles/element.scss" as *;`,
      }
    },
    server: {
      host: '0.0.0.0',
      port: 8000,
      open: true, // 自动打开浏览器
      cors: true, // 允许跨域
      strictPort: false, // 端口占用直接退出
      hmr: true,
      proxy: {
        [env.VITE_BASE_URL]: {
          // 线上API地址
          target: 'http://m.test.duanju.dududus.com/api',
          // 本地API地址
          // target: 'http://localhost:8989',
          changeOrigin: true,
          rewrite: path => path.replace(new RegExp('^' + env.VITE_BASE_URL), '')
        }
      },
      fs: {
        allow: ['./']
      }
    },
    build: {
      sourcemap: false,
      // 消除打包大小超出警告
      chunkSizeWarningLimit: 2000,
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: false,
          pure_funcs: ['console.log', 'console.info'],
          drop_debugger: true
        }
      },
      // emptyOutDir: false,
      outDir: 'dist',
      assetsDir: 'assets',
      rollupOptions: {
        input: path.resolve(__dirname, 'index.html'),
        output: {
          chunkFileNames: 'assets/js/[name]-[hash].js',

          entryFileNames: 'assets/js/[name]-[hash].js',

          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]'
        }
      }
    }
  };
});
