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 CopyWebpackPlugin = require('copy-webpack-plugin')
const $GLOBAL = require('./webpack.base.conf')

const _conf = require('./config')

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: false,
      host: _conf.demain || 'localhost',
      https: _conf.isHttps,
      overlay: {
        errors: true
      },
      historyApiFallback: {
        index: '/index.html'
      },
      proxy: {
        '/api': {
          target: $GLOBAL.webConf.devDomain,
          selfHandleResponse: false,
          secure: false,
          changeOrigin: true,
          followRedirects: true,
          logLevel: 'info',
          headers: {
            'Referer': $GLOBAL.webConf.devDomain
          },
          pathRewrite: {
            '^/api': '/api'
          }
        }
      },
      open: true,
      hot: true
    },
    module: {
      rules: [{
        test: /\.(sa|sc|c)ss$/,
        use: [
          'style-loader',
          'css-loader',
          {
            loader: 'postcss-loader',
            options: {
              plugins: [
                AutoPrefixer({
                  'overrideBrowserslist': [
                    '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({
                  'overrideBrowserslist': [
                    'cover 99.5%',
                    'ie 6-8',
                    'since 2015',
                    'last 10 iOS versions'
                  ]
                })
              ]
            }
          },
          'sass-loader'
        ]
      }]
    },
    plugins: [
      new CleanWebpackPlugin(['**/*'], { root: $GLOBAL.OutputPath }),
      new MiniCssExtractPlugin({
        chunkFilename: $GLOBAL.cssName
      }),
      new VueLoaderPlugin(),
      new HtmlWebpackPlugin({
        template: $GLOBAL.templatePath,
        inject: true,
        favicon: $GLOBAL.icoPath,
        minify: {
          removeComments: true,
          collapseWhitespace: true
        }
      }),
      new CopyWebpackPlugin([
        {
          from: $GLOBAL.EntryStaticPath,
          to: $GLOBAL.OutputStaticPath,
          ignore: ['.*'],
          transform: function (content) {
            return content
          }
        }
      ])
    ],
    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
