'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: false, // 开发环境禁用 source map,大幅提升速度
  cache: {
    type: 'filesystem',
    buildDependencies: {
      config: [__filename]
    },
    // 限制缓存内存使用
    maxMemoryGenerations: 5,
    compression: 'gzip' // 压缩缓存,减少磁盘和内存占用
  },
  devServer: {
    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: {
        // 忽略 node_modules 等大目录,减少文件监听
        ignored: ['**/node_modules/**', '**/dist/**', '**/.git/**'],
        // 降低轮询间隔,减少 CPU 占用
        aggregateTimeout: 600
      }
    },
    client: {
      logging: 'warn',
      overlay: config.dev.errorOverlay ? { errors: true, warnings: false } : false
    },
    proxy: config.dev.proxyTable
  },
  plugins: [
    new webpack.ProgressPlugin((percentage, message, ...args) => {
      // 使用闭包保存上次的进度值
      const percent = Math.floor(percentage * 100)
      // 每 5% 或关键步骤时输出一次,减少控制台刷新
      if (percent % 5 === 0 || percent === 100 || message.includes('building') || message.includes('done')) {
        console.log(`构建进度: ${percent}% ${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: 'AMS信息管理系统',
      BASE_URL: 'static'
    })
    // ESLint 已在 webpack.base.conf.js 中配置,这里不需要重复添加
  ],
  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)
    }
  })
})
