const { defineConfig } = require('@vue/cli-service');
const path = require('path');
const fs = require('fs');

/* config 配置读取 */
const { downloadConfigFile } = require('@gdyfe/config');

const assetsDirMap = {
  test: 'test',
  preview: 'pre',
  production: 'prod',
};
const assetsDir = assetsDirMap[process.env.mode] || 'prod';
const BASE_URL = '/lottery/';

const assetsDirPath = path.join(__dirname, './public', assetsDir);

if (!fs.existsSync(assetsDirPath)) {
  fs.mkdirSync(assetsDirPath);
}
// 下载配置文件到指定目录
downloadConfigFile({
  server: process.env.mode,
  ic: 'ZmUtZ5WNp%XBzDw=',
  path: path.resolve(__dirname, `${assetsDirPath}/config.js`),
})
  .then(() => {
    console.log('$$ config file downloaded $$');
  })
  .catch((err) => {
    console.log('$$ config file download failed $$', err);
  });

module.exports = defineConfig({
  publicPath: BASE_URL,
  assetsDir,
  transpileDependencies: true,
  chainWebpack: (config) => {
    // 别名
    config.resolve.alias
      .set('@', path.join(__dirname, 'src'))
      .set('assets', path.resolve('src/assets'))
      .set('public', path.resolve(__dirname, 'public'));
    // DefinePlugin
    config.plugin('define').tap((args) => {
      args[0]['process.env'] = {
        ...args[0]['process.env'],
        mode: JSON.stringify(process.env.mode),
        BASE_URL: JSON.stringify(BASE_URL),
        VUE_APP_ASSETS_DIR: JSON.stringify(assetsDir),
      };
      return args;
    });
    // terser
    if (process.env.NODE_ENV === 'production') {
      config.optimization.minimizer('terser').tap((args) => {
        args[0].terserOptions.compress.drop_console = true;
        args[0].terserOptions.compress.drop_debugger = true;
        return args;
      });
    }
  },
});
