const path = require('path')
const rm = require('rimraf')
// 监听打包完成
const FileManagerPlugin = require('filemanager-webpack-plugin')
const date = new Date()
const y = date.getFullYear()
const m = (date.getMonth() + 1).toString().padStart(2, '0')
const d = date.getDate().toString().padStart(2, '0')
const h = date.getHours().toString().padStart(2, '0')
const timestamp = `?${y}${m}${d}${h}`
const env = ['develop', undefined].includes(process.env.BUILD_ENV) ? require('./config/dev.env') : (process.env.BUILD_ENV === 'release' ? require('./config/release.env') : require('./config/prod.env'))
const resolve = (dir) => {
  return path.join(__dirname, dir)
}

const addStyleResource = (rule) => {
  rule.use('style-resource')
    .loader('style-resources-loader')
    .options({
      patterns: [
        path.resolve(__dirname, './src/assets/styles/variable.scss')
      ]
    })
}

if (process.env.NODE_ENV !== 'development') {
  rm(resolve('./dist'), err => {
    if (err) throw err
  })
}

module.exports = {
  publicPath: '/',
  outputDir: './dist', // 构建文件目录,默认dist
  filenameHashing: false,
  productionSourceMap: process.env.BUILD_ENV === 'develop',
  devServer: {
    hot: true,
    hotOnly: true,
    host: '0.0.0.0',
    port: 8080,
    open: true,
    clientLogLevel: 'warning',
    // proxy: {
    //   '/': {
    //     target: 'https://ttyf-api.tbafhouse.com',
    //     ws: true,
    //     changeOrigin: true
    //   }
    // },
    overlay: {
      warnings: true,
      errors: false
    },
    before (app) {
    }
  },
  configureWebpack: {
    resolve: {
      alias: {
        '@': resolve('src')
      }
    },
    output: {
      filename: 'js/[name].[hash].js' + timestamp,
      chunkFilename: 'js/[name].[hash].js' + timestamp
    },
    plugins: process.env.NODE_ENV !== 'development' ? [
      new FileManagerPlugin({
        onEnd: [
          {
            delete: ['./dist/*/favicon.ico', './dist/*/index.html']
          }
        ]
      })
    ] : [],
    performance: {
      hints: 'warning',
      // 入口起点的最大体积 整数类型(以字节为单位)
      maxEntrypointSize: 5000000,
      // 生成文件的最大体积 整数类型(以字节为单位 300k)
      maxAssetSize: 3000000,
      // 只给出 js 文件的性能提示
      assetFilter: function (assetFilename) {
        return assetFilename.endsWith('.js')
      }
    }
  },
  chainWebpack: config => {
    const types = ['vue-modules', 'vue', 'normal-modules', 'normal']
    types.forEach(type => addStyleResource(config.module.rule('scss').oneOf(type)))

    config.plugin('define').tap(args => {
      args[0]['process.env'] = Object.assign({}, args[0]['process.env'], env)
      return args
    })

    config.plugins.delete('preload')
    config.plugins.delete('prefetch')
  },
  css: process.env.NODE_ENV !== 'development' ? {
    extract: {
      filename: 'css/[name].[hash].css' + timestamp,
      chunkFilename: 'css/[name].[hash].css' + timestamp,
      ignoreOrder: true
    },
    sourceMap: false
  } : {}
}