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,customize 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.183:8503/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