const fs = require('fs')
const path = require('path')
const webpack = require('webpack')
const createThemeColorReplacerPlugin = require('./config/plugin.config')
// gzip 压缩
const compressionWebpackPlugin = require('compression-webpack-plugin')
// js,css 压缩
const TerserPlugin = require('terser-webpack-plugin')
// 版本自动生成
const WebpackVersionPlugin = require('webpack-version-plugin')
const versionConfig = require(resolve('public/version.json'))

function resolve (dir) {
  return path.join(__dirname, dir)
}

/**
 * check production or preview(pro.loacg.com only)
 * @returns {boolean}
 */
function isProd () {
  return process.env.NODE_ENV === 'production'
}

// 项目部署基础
// 默认情况下,我们假设你的应用将被部署在域的根目录丄1�7
// 例如:https://www.my-app.com/
// 默认$1�7/'
// 如果您的应用程序部署在子路径中,则需要在这指定子路径
// 例如:https://www.foobar.com/my-app/
// 霄1�7要将它改丄1�7/my-app/'
const BASE_URL = isProd ? '/' : '/'
const assetsCDN = {
  css: [],
  // https://unpkg.com/browse/vue@2.6.10/
  js: [
    BASE_URL + 'js/vue.min.js',
    BASE_URL + 'js/vue-router.min.js',
    BASE_URL + 'js/vuex.min.js',
    BASE_URL + 'js/axios.min.js',
    BASE_URL + 'js/echarts.min.js'
  ]
}

// webpack build externals
const prodExternals = {
  vue: 'Vue',
  'vue-router': 'VueRouter',
  vuex: 'Vuex',
  axios: 'axios',
  echarts: 'echarts',
  // lodash : {
  //   commonjs: "lodash",
  //   amd: "lodash",
  //   root: "_" // indicates global variable
  // },
  'mockjs2': 'Mock'
}

// vue.config.js
const vueConfig = {
  runtimeCompiler: true, // 动�1�7�编译组仄1�7
  publicPath: BASE_URL,
  configureWebpack: {
    optimization: isProd() ? {
      minimize: true,
      minimizer: [new TerserPlugin({
        test: /\.js(\?.*)?$/i, // 匹配参与压缩的文仄1�7
        parallel: true, // 使用多进程并发运衄1�7
        terserOptions: { // Terser 压缩配置
          output: { comments: false },
          compress: {// console删除
            pure_funcs: ['console.log']
          }
        },
        extractComments: true // 将注释剥离到单独的文件中
      })]
    } : {},
    // webpack plugins
    plugins: [
      // Ignore all locale files of moment.js
      new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
      new compressionWebpackPlugin({
        // [file] 会被替换成原始资源�1�7�[path] 会被替换成原始资源的路径$1�7[query] 会被替换成查询字符串。默认�1�7�是 "[path].gz[query]"〄1�7
        filename: '[path].gz[query]', // 提示compression-webpack-plugin@3.0.0的话asset改为filename
        // 可以昄1�7function(buf, callback) 或�1�7�字符串。对于字符串来说依照 zlib 的算泄1�7或�1�7�1�7zopfli 的算泄1�7。默认�1�7�是 "gzip"〄1�7
        algorithm: 'gzip',
        // 扄1�7有匹配该正则的资源都会被处理。默认�1�7�是全部资源〄1�7
        test: new RegExp('\\.(' + ['js', 'css'].join('|') + ')$'),
        // 只有大小大于该�1�7�的资源会被处理。单位是 bytes。默认�1�7�是 0〄1�7
        threshold: 10240,
        // 只有压缩率小于这个�1�7�的资源才会被处理�1�7�默认�1�7�是 0.8〄1�7
        minRatio: 0.8
      }),
      new WebpackVersionPlugin({
        // You must set the cb option
        cb: function (hashMap) {
          if (!isProd()) {
            versionConfig.version = new Date().getTime()
            fs.writeFileSync(resolve('./public/version.json'), JSON.stringify(versionConfig, null, 2))
          }
        }
      })
    ],
    // if prod is on, add externals
    externals: isProd() ? prodExternals : {}
  },
  chainWebpack: (config) => {
    config.resolve.alias
      .set('@$', resolve('src'))

    const svgRule = config.module.rule('svg')
    svgRule.uses.clear()
    svgRule
      .oneOf('inline')
      .resourceQuery(/inline/)
      .use('vue-svg-icon-loader')
      .loader('vue-svg-icon-loader')
      .end()
      .end()
      .oneOf('external')
      .use('file-loader')
      .loader('file-loader')
      .options({
        name: 'assets/[name].[hash:8].[ext]'
      })

    // if prod is on
    // assets require on cdn
    if (isProd()) {
      config.plugin('html').tap(args => {
        args[0].cdn = assetsCDN
        return args
      })
    }

    config.optimization && config.optimization.splitChunks({
      // 拆包配置
      chunks: 'all', // 三�1�7�一$1�7initial" 初始化,"all"(默认就是all)$1�7async"(动态加载)
      minSize: 30000, // 形成丄1�7个新代码块最小的体积,只有 >= minSize 的bundle会被拆分出来 30000
      maxSize: 0, // 拆分之前朄1�7大的数�1�7�,默认丄1�7�即不做限制
      minChunks: 1, // 引入次数,如果为2 那么丄1�7个资源最少被引用两次才可以被拆分出来
      maxAsyncRequests: 5, // 按需加载的最大并行请求数
      maxInitialRequests: 4, // 丄1�7个入口最大并行请求数
      automaticNameDelimiter: '~', // 文件名的连接笄1�7
      name: true,
      cacheGroups: {
        // node_modules模块匄1�7
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          name: 'chunk-vendors',
          // name(module) {
          //   const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
          //   return `chunk.${packageName.replace('@', '')}`;
          // },
          chunks: 'all',
          priority: -10
        },
        // UI库单独拆匄1�7
        antDesign: {
          name: 'chunk-antDesign',
          priority: 19, //  the weight needs to be larger than libs and app or it will be packaged into libs or app
          test: /[\\/]node_modules[\\/]_?@ant-design(.*)/
        },
        antDesignVue: {
          name: 'chunk-antDesignVue',
          priority: 20, //  the weight needs to be larger than libs and app or it will be packaged into libs or app
          test: /[\\/]node_modules[\\/]_?ant-design-vue(.*)/
        },
        // 共享模块
        common: {
          name: 'chunk-common',
          minChunks: 2,
          maxSize: 1024, // 拆分之前朄1�7大的数�1�7�,默认丄1�7�即不做限制
          priority: -20,
          reuseExistingChunk: true
        }
      }
    })

    // 分析打包大小
    if (process.env.npm_config_report) {
      config.plugin('webpack-bundle-analyzer')
        .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
        .end()
    }
  },

  css: {
    sourceMap: false,
    loaderOptions: {
      less: {
        modifyVars: {
          // less vars锛宑ustomize ant design theme
          'primary-color': process.env.VUE_APP_THEME_COLOR,
          'link-color': process.env.VUE_APP_THEME_COLOR
          // 'border-radius-base': '4px'
        },
        // do not remove this line
        javascriptEnabled: true
      }
    }
  },

  devServer: {
    // development server port 8000
    port: 8000,
    disableHostCheck: true,
    // If you want to turn on the proxy, please remove the mockjs /src/main.jsL11
    proxy: {
      '/api': {
        // target: 'http://192.168.2.103/qpls-md',
        target: 'https://p.iscm.360arrow.com/qpls-md',
        // ws: false,
        ws: true,
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    },
    watchOptions: {
      ignored: [/node_modules/, /public/]
    }
  },

  // disable source map in production
  productionSourceMap: false,
  assetsDir: 'static',
  lintOnSave: undefined,
  // babel-loader no-ignore node_modules/*
  transpileDependencies: []
}

// preview.pro.loacg.com only do not use in your production;
if (process.env.VUE_APP_PREVIEW === 'true') {
  console.log('VUE_APP_PREVIEW', true)
  // add `ThemeColorReplacer` plugin to webpack plugins
  vueConfig.configureWebpack.plugins.push(createThemeColorReplacerPlugin())
}

module.exports = vueConfig