'use strict'
const { defineConfig } = require('@vue/cli-service')
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')
const WebpackAliyunOss = require('webpack-aliyun-oss')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')
const CopyPlugin = require('copy-webpack-plugin')
// const TerserWebpackPlugin = require('terser-webpack-plugin')
const { resolve } = require('path')
const webpack = require('webpack')
const defaultSettings = require('./src/settings.js')
const moment = require('moment')
var distDate = moment(new Date()).format('YYYY-MM-DD')
const name = process.env.NODE_ENV === 'usa' ? 'Imaging Trial Management System' : defaultSettings.title || 'EIC lmaging Trial Management System' // page title
// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
// eslint-disable-next-line no-undef
module.exports = defineConfig({
  // lintOnSave: false,
  transpileDependencies: false,
  publicPath: process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'prod' || process.env.NODE_ENV === 'production' || process.env.VUE_APP_OSS_CONFIG_BUCKET === 'zyypacs-usa' ? process.env.VUE_APP_BASE_PATH : `${process.env.VUE_FILE_PATH}${process.env.VUE_APP_OSS_PATH}${distDate}/`,
  // publicPath: '/',
  outputDir: 'dist',
  assetsDir: 'static',
  productionSourceMap: false,
  devServer: {
    port: '8080',
    // headers: {
    //   'Cross-Origin-Opener-Policy': 'same-origin',
    //   'Cross-Origin-Embedder-Policy': 'require-corp'
    // },
    // open: true,
    client: {
      overlay: {
        warnings: true,
        errors: true
      }
    },
    proxy: {
      '/UploadHub': {
        target: 'http://123.56.94.154:7000', // 国内测试环境2
        changeOrigin: true,
        secure: false,
        pathRewrite: {
          '^/api': ''
        }
      },
      '/IRaCISData': {
        target: 'http://123.56.94.154:8060/', // 国内测试环境2
        changeOrigin: true,
        pathRewrite: {
        }
      },

      '/api': {
        target: 'http://106.14.89.110:30000',
        // target: 'http://101.132.253.119:7010', // uat
        changeOrigin: true,
        secure: false,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  },
  configureWebpack: {
    name: name,
    output: {
      filename: `static/js/[name].[contenthash:8].js`,
      chunkFilename: `static/js/[name].[chunkhash:8].js`,
      assetModuleFilename: 'static/wasm/[name].[contenthash:8][ext]'
    },
    resolve: {
      fallback: {
        'path': require.resolve('path-browserify')
      },
      alias: {
        '@': resolve('src'),
        'modules': resolve('node_modules'),
        'utils': resolve('src/utils')
      }
    },

    experiments: {
      // 基于异步模块的 WebAssembly 实验性特性
      // syncWebAssembly: true,
      asyncWebAssembly: true
    },
    plugins: [
      new CopyPlugin({
        patterns: [
          {
            from: resolve(__dirname, './static'),
            to: resolve(__dirname, './dist/static'),
            globOptions: {
              ignore: ['.*']
            }

          }
        ]
      }),
      // new BundleAnalyzerPlugin(),
      process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'production' || process.env.VUE_APP_OSS_CONFIG_BUCKET === 'zyypacs-usa' ? function() { }
        : new WebpackAliyunOss({
          from: ['./dist/**'],
          dist: process.env.VUE_APP_OSS_PATH + distDate,
          region: process.env.OSS_REGION,
          accessKeyId: process.env.OSS_ACCESS_KEY_ID,
          accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
          bucket: process.env.OSS_BUCKET,
          overwrite: true,
          setOssPath: filePath => {
            const index = filePath.lastIndexOf('dist')
            const Path = filePath.substring(index + 4, filePath.length)
            return Path.replace(/\\/g, '/')
          },
          setHeaders: filePath => {
            return {
              'Cache-Control': 'max-age=31536000'
            }
          }
        }),
      new MiniCssExtractPlugin({
        filename: 'static/css/[name].[contenthash:8].css'
      }),
      new NodePolyfillPlugin(),
      new webpack.ProvidePlugin({
        process: 'process/browser'
      })
      // new OfflinePlugin({})
    ],
    // 如果需要对 .wasm 文件进行特殊处理，可以添加 module.rules 配置
    module: {
      rules: [
        {
          test: /\.wasm$/,
          type: 'asset/resource'
        }
      ],
      exprContextCritical: false,
    },
    optimization: {
      splitChunks: {
        chunks: 'all',
        cacheGroups: {
          libs: { // 第三方库
            name: 'chunk-libs',
            test: /[\V/]node_modules[\\/]/,
            priority: 10,
            chunks: 'initial' // 只打包初始时依赖的第三方
          },
          elementUI: { // elementuI 单独拆包
            name: 'chunk-elementUI',
            test: /[\V/]node_modules[\V]element-ui[\/]/,
            priority: 20 // 权重要大于 libs
          },
          commons: { // 公共模块包
            name: `chunk-commons`,
            test: /[\\/]src[\\/]/, // can customize your rules
            minSize: 1024,
            chunks: 'initial',
            priority: 5
          },
          default: {
            minChunks: 2,
            priority: -20,
            reuseExistingChunk: true
          }
        }
      },
      minimize: process.env.NODE_ENV !== 'development',
      minimizer: process.env.NODE_ENV === 'development' ? [] : [
        new CssMinimizerPlugin()
      ]
      // minimizer: process.env.NODE_ENV === 'development' ? [] : [
      //   // 配置生产环境的压缩方案：js和css
      //   // new TerserWebpackPlugin({
      //   //   // 开启多进程打包
      //   //   parallel: true
      //   // }),
      //   new CssMinimizerPlugin()
      // ]
    },
    performance: {
      hints: false,
      // 入口起点的最大体积
      maxEntrypointSize: 5000000000,
      // 生成文件的最大体积
      maxAssetSize: 3000000000,
      // 只给出js的性能提示
      assetFilter: function(assetFileName) {
        return assetFileName.endsWith('.js')
      }
    }
  },
  chainWebpack: (config) => {
    config.module.rule('svg').exclude.add(resolve('src/icons')).end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()
  }
})
