import path from 'path';
import { UserConfigExport, ConfigEnv, loadEnv } from 'vite';
import vueJsx from '@vitejs/plugin-vue-jsx';
import vue from '@vitejs/plugin-vue';
import svgLoader from 'vite-svg-loader';
import imageLoader from '@rollup/plugin-image';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
import ElementPlus from 'unplugin-element-plus/vite';
import { createHtmlPlugin } from 'vite-plugin-html';


const getEnvFn = (mode, target) => {
  return loadEnv(mode, process.cwd())[target];
};


/**
 * @type {import('vite').UserConfig}
 * @link {https://vitejs.cn/config/}
 */
export default ({ command, mode }: ConfigEnv): UserConfigExport => {
  console.log(command);
  return {
    root: process.cwd(),
    base: './',
    server: {
      host: '0.0.0.0',
      open: true,
      port: 8001,
      // strictPort: true,
      https: false,
      force: true,
      proxy: {
        '/api': {
          target: 'http://61.147.254.211:30876/YJZH-SQ/',
          // target: 'http://sqpcbg.xt.wenhq.top:8083/',
          changeOrigin: true,
          // rewrite: (path) => path.replace(/^\/api/, ''),
        },
      },
    },
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
        '@assets': path.resolve(__dirname, './src/assets'),
      },
    },

    css: {
      modules: {
        localsConvention: 'camelCase', // 默认只支持驼峰，修改为同事支持横线和驼峰
      },
      preprocessorOptions: {
        scss: {
          /**
           * TODO:// 目前按需加载时修改主题色会报错
           * 官方修复后在进行按需加载
           * @link {https://github.com/element-plus/element-plus/issues/2724}
           *
           *  */
          // additionalData: `@use "@/styles/element/index.scss" as *;`,
        },
        // scss: { additionalData: `@import "@/styles/vars.scss";` },
        // less: {
        //   javascriptEnabled: true,
        //   additionalData: `@import "@/styles/default.less";`,
        // },
      },
    },
    plugins: [
      vue(),
      vueJsx({
        // options are passed on to @vue/babel-plugin-jsx
      }),
      imageLoader(),
      createHtmlPlugin({
        inject: {
          data: {
            mapurl: getEnvFn(mode, 'VITE_MAP_SERVER'),
          },
        },
      }),
      // svgLoader(),
      // ElementPlus({ useSource: true }),
    ],
  };
};
