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'
}

// 项目部署基础
// 默认情况下，我们假设你的应用将被部署在域的根目录下,
// 例如：https://www.my-app.com/
// 默认：'/'
// 如果您的应用程序部署在子路径中，则需要在这指定子路径
// 例如：https://www.foobar.com/my-app/
// 需要将它改为'/my-app/'
const BASE_URL = isProd ? '/' : '/'

const assetsCDN = {
  css: [],
  // https://unpkg.com/browse/vue@2.6.10/
  js: [
    '//vuepkg.oss-cn-beijing.aliyuncs.com/vue.min.js',
    '//vuepkg.oss-cn-beijing.aliyuncs.com/vue-router.min.js',
    '//vuepkg.oss-cn-beijing.aliyuncs.com/vuex.min.js',
    '//vuepkg.oss-cn-beijing.aliyuncs.com/axios.min.js',
    // '//vuepkg.oss-cn-beijing.aliyuncs.com/lodash.min.js',
    '//vuepkg.oss-cn-beijing.aliyuncs.com/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, // 动态编译组件
  publicPath: BASE_URL,
  configureWebpack: {
    optimization: isProd() ? {
          minimize: true,
          minimizer: [new TerserPlugin({
              test: /\.js(\?.*)?$/i,    //匹配参与压缩的文件
              parallel: true,    //使用多进程并发运行
              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] 会被替换成原始资源。[path] 会被替换成原始资源的路径， [query] 会被替换成查询字符串。默认值是 "[path].gz[query]"。
          filename: '[path].gz[query]', // 提示compression-webpack-plugin@3.0.0的话asset改为filename
          //可以是 function(buf, callback) 或者字符串。对于字符串来说依照 zlib 的算法(或者 zopfli 的算法)。默认值是 "gzip"。
          algorithm: 'gzip',
          //所有匹配该正则的资源都会被处理。默认值是全部资源。
          test: new RegExp('\\.(' + ['js', 'css'].join('|') + ')$'),
          //只有大小大于该值的资源会被处理。单位是 bytes。默认值是 0。
          threshold: 10240,
          //只有压缩率小于这个值的资源才会被处理。默认值是 0.8。
          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', //三选一："initial" 初始化，"all"(默认就是all)，"async"（动态加载） 
        minSize: 30000, // 形成一个新代码块最小的体积,只有 >= minSize 的bundle会被拆分出来 30000
        maxSize: 0, //拆分之前最大的数值，默认为0，即不做限制
        minChunks: 1, //引入次数，如果为2 那么一个资源最少被引用两次才可以被拆分出来
        maxAsyncRequests: 5, // 按需加载的最大并行请求数
        maxInitialRequests: 4, // 一个入口最大并行请求数
        automaticNameDelimiter: '~', // 文件名的连接符
        name: true,
        cacheGroups: {
        // node_modules模块包
        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库单独拆包
        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, //拆分之前最大的数值，默认为0，即不做限制
          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.0.216:8076/qpls-md',
        target: 'http://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
