const webpack = require('webpack')
const WebpackMerge = require('webpack-merge')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const AutoPrefixer = require('autoprefixer')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const cssnano = require('cssnano')
const HtmlWebpackPlugin = require('html-webpack-plugin')

const $GLOBAL = require('./webpack.base.conf')

let config = null

if ($GLOBAL.isDev) {
  config = WebpackMerge($GLOBAL.BaseConfig, {
    mode: 'development',
    devtool: '#cheap-module-eval-source-map',
    output: {
      filename: '[name].js'
    },
    devServer: {
      port: $GLOBAL.serverPort,
      disableHostCheck: true,

      overlay: {
        errors: true
      },
      historyApiFallback: {
        index: '/index.html'
      },
      proxy: {
        '/api': {
          target: $GLOBAL.webConf.devDomain,
          secure: false,
          changeOrigin: true,
          followRedirects: true,
          logLevel: 'info',
          headers: {
            'Referer': $GLOBAL.webConf.devDomain
          },
          pathRewrite: {
            '^/api': ''
          },
          onProxyRes: function (proxyRes, req, res) {
            let _sCookie = proxyRes.headers['set-cookie'] || []
            for (let i = 0; i < _sCookie.length; i++) {
              if (/_SUP=/gi.test(_sCookie[i])) {
                _sCookie.splice(i, 1)
                console.log('目前暂时禁止 - 服务端设置_SUP')
                break
              }
            }
          },
          onProxyReq: function (proxyReq, req, res) {

          }
        }
      },
      open: true,
      hot: true
    },
    module: {
      rules: [{
        test: /\.(sa|sc|c)ss$/,
        use: [
          'style-loader',
          'css-loader',
          {
            loader: 'postcss-loader',
            options: {
              plugins: [
                AutoPrefixer({
                  'browsers': [
                    'cover 99.5%',
                    'ie 6-8',
                    'since 2015',
                    'last 10 iOS versions'
                  ]
                })
              ]
            }
          },
          'sass-loader'
        ]
      }]
    },
    plugins: [
      new VueLoaderPlugin(),
      new webpack.HotModuleReplacementPlugin(),
      new HtmlWebpackPlugin({
        template: $GLOBAL.templatePath,
        inject: true,
        favicon: $GLOBAL.icoPath
      })
    ]
  })
} else {
  config = WebpackMerge($GLOBAL.BaseConfig, {
    mode: 'production',
    entry: {
      app: $GLOBAL.EntryPath,
      vendor: ['vue']
    },
    module: {
      rules: [{
        test: /\.(sa|sc|c)ss$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {

            }
          },
          'css-loader',
          {
            loader: 'postcss-loader',
            options: {
              plugins: [
                AutoPrefixer({
                  'browsers': [
                    'cover 99.5%',
                    'ie 6-8',
                    'since 2015',
                    'last 10 iOS versions'
                  ]
                })
              ]
            }
          },
          'sass-loader'
        ]
      }]
    },
    plugins: [
      new CleanWebpackPlugin(['client-dist'], { root: $GLOBAL.RootPath }),
      new MiniCssExtractPlugin({
        chunkFilename: $GLOBAL.cssName
      }),
      new VueLoaderPlugin(),
      new HtmlWebpackPlugin({
        template: $GLOBAL.templatePath,
        inject: true,
        favicon: $GLOBAL.icoPath,
        minify: {
          removeComments: true,
          collapseWhitespace: true
        }
      })
    ],
    optimization: {
      runtimeChunk: {
        name: 'manifest'
      },
      minimizer: [
        new UglifyJsPlugin({
          cache: true,
          parallel: true,
          sourceMap: true
        }),
        new OptimizeCSSAssetsPlugin({
          cssProcessor: cssnano,
          cssProcessorOptions: { discardComments: { removeAll: true } },
          canPrint: true
        })
      ],
      splitChunks: {
        chunks: 'async',
        minSize: 30000,
        minChunks: 1,
        maxAsyncRequests: 5,
        maxInitialRequests: 3,
        name: false,
        cacheGroups: {
          vendor: {
            name: 'vendor',
            chunks: 'initial',
            priority: -10,
            reuseExistingChunk: false,
            test: /node_modules\/(.*)\.js/
          }

        }
      }
    }
  })
}

module.exports = config
