'use strict'
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const { merge } = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ESLintPlugin = require('eslint-webpack-plugin')
const portfinder = require('portfinder')
const CopyWebpackPlugin = require('copy-webpack-plugin')
function resolve(dir) {
  return path.join(__dirname, '..', dir)
}


const devWebpackConfig = merge(baseWebpackConfig, {
  mode: 'development',
  stats: 'errors-warnings',
  infrastructureLogging: {
    level: 'warn'
  },
  devtool: 'eval-cheap-module-source-map',
  cache: {
    type: 'memory'
  },
  devServer: {
    https: true,
    historyApiFallback: true,
    hot: true,
    compress: true,
    host: process.env.HOST || config.dev.host,
    port: process.env.PORT || config.dev.port,
    open: config.dev.autoOpenBrowser,
    static: {
      publicPath: config.dev.assetsPublicPath,
      watch: true
    },
    client: {
      logging: 'warn',
      overlay: config.dev.errorOverlay ? { errors: true, warnings: false } : false
    },
    proxy: config.dev.proxyTable
  },
  plugins: [
    new webpack.ProgressPlugin({
      activeModules: true, // 设置为 true 会显示当前正在处理的模块，但可能会影响性能
      entries: true, // 显示条目计数
      handler: (percentage, message, ...args) => {
        // 一个简单的自定义处理函数，输出到控制台
        console.log(`构建进度: ${(percentage * 100).toFixed(2)}% ${message}`);
      }
    }),
    new webpack.DefinePlugin({
      'process.env': require('../config/dev.env')
    }),
    new webpack.HotModuleReplacementPlugin(),
    new CopyWebpackPlugin({
      patterns: [
        {
          from: path.resolve(__dirname, '../static'),
          to: config.build.assetsSubDirectory,
          globOptions: {
            ignore: ['.*']
          }
        }
      ]
    }),
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
      inject: true,
      favicon: resolve('favicon.ico'),
      title: '数据分析处理平台',
      BASE_URL: 'static'
    }),
    ...(config.dev.useEslint ? [new ESLintPlugin({
      extensions: ['js', 'vue'],
      formatter: require('eslint-friendly-formatter'),
      emitWarning: !config.dev.showEslintErrorsInOverlay
    })] : [])
  ],
  optimization: {
    removeAvailableModules: false,
    removeEmptyChunks: false,
    splitChunks: false,
    minimize: false
  }
})

module.exports = new Promise((resolve, reject) => {
  portfinder.basePort = process.env.PORT || config.dev.port
  portfinder.getPort((err, port) => {
    if (err) {
      reject(err)
    } else {
      devWebpackConfig.devServer.port = port
      process.env.PORT = port

      console.log(`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`)
      resolve(devWebpackConfig)
    }
  })
})
