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

const hmacSHA256 = require('crypto-js/hmac-sha256')
const Base64 = require('crypto-js/enc-base64')

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,
          selfHandleResponse: true,
          secure: false,
          changeOrigin: true,
          followRedirects: true,
          logLevel: 'info',
          headers: {
            'Referer': $GLOBAL.webConf.devDomain
          },
          pathRewrite: {
            '^/api': ''
          },
          onProxyRes: function (proxyRes, req, res) {
            let base64strArr = []
            let base64strsize = 0
            proxyRes.on('data', function (data) {
              base64strArr.push(data)
              base64strsize += data.length
            })
            proxyRes.on('end', function () {
              let buf = Buffer.concat(base64strArr, base64strsize)
              let _data = JSON.parse(buf.toString())
              if (/tenant\/user\/login/gi.test(proxyRes.responseUrl) || /tenant\/user\/code-login/gi.test(proxyRes.responseUrl)) {
                const salt = '0ZSGxuBkSJS5'
                let sup = _data.ticket.split('').reverse().join('')
                let rad = Math.random()
                let token = salt + sup + rad
                sup = Buffer.from(token).toString('base64')
                let serialize = `a:2:{i:0;s:4:"_SUP";i:1;s:${sup.length}:"${sup}";}`
                let hamc = Base64.stringify(hmacSHA256(serialize, 'VzpR5JMDNqUsOZ0IFQARNLU9_0KLr9UC'))
                sup = hamc + serialize

                let opts = { path: '/', domain: '.ezijing.com', maxAge: 30 * 24 * 60 * 60 * 1000, httpOnly: true }

                res.cookie('_SUP', sup, opts)
              } else if (/v3\/sso\/logout/gi.test(proxyRes.responseUrl)) {
                res.cookie('_SUP', '', { path: '/', domain: '.ezijing.com', maxAge: 1, httpOnly: true })
              }
              res.send(_data)
            })
          },
          onProxyReq: function (proxyReq, req, res) {
            let _cookieStr = proxyReq._options.headers['cookie'] || ''
            let _cookieArr = _cookieStr.split(';')
            let _SUP = ''
            for (let i = 0; i < _cookieArr.length; i++) {
              if (/_SUP=/gi.test(_cookieArr[i])) {
                _SUP = _cookieArr[i].split('=')[1]
                break
              }
            }
            let s = decodeURIComponent(_SUP || '')
            let ticket = ''
            s = s.match(/"([\d\w=]+)";\}$/)
            if (s && s.length === 2) {
              s = Buffer.from(s[1], 'base64').toString()
              s = s.slice(12, s.search('-TGT') + 4)
              ticket = s.split('').reverse().join('')
            }
            proxyReq.setHeader('token', ticket)
          }
        }
      },
      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
