const path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin');//------------
const CleanWebpackPlugin = require('clean-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const webpack = require('webpack');
const packageConfig = require('../package.json');

const utils = require('./utils')
const vueLoaderConfig = require('./vue-loader.conf')
let evnConfig = require('./getEnvVar')


const os = require('os');
const cpus = os.cpus().length;
console.log(cpus, ' Math.floor(cpus/2)||1', Math.floor(cpus / 2) || 1)
let threadLoader = {
  loader: "thread-loader",
  // 有同样配置的 loader 会共享一个 worker 池(worker pool)
  options: {
    // 产生的 worker 的数量，默认是 cpu 的核心数
    workers: Math.floor(cpus / 2) || 1,
    // 一个 worker 进程中并行执行工作的数量
    // 默认为 20
    workerParallelJobs: 50,
    // 额外的 node.js 参数
    // workerNodeArgs: ['--max-old-space-size', '1024'],
    // 闲置时定时删除 worker 进程
    // 默认为 500ms
    // 可以设置为无穷大， 这样在监视模式(--watch)下可以保持 worker 持续存在
    poolTimeout: 2000,
    // 池(pool)分配给 worker 的工作数量
    // 默认为 200
    // 降低这个数值会降低总体的效率，但是会提升工作分布更均一
    poolParallelJobs: 50,
    // 池(pool)的名称
    // 可以修改名称来创建其余选项都一样的池(pool)
    // name: "my-pool"
  }
};

let projectName = packageConfig.name == 'hi-vui-template' ? 'project' : packageConfig.name;


module.exports = {
  // entry: {
  //   'login': ['babel-polyfill', './project/hivuiLogin/index.js'],
  //   'main': ['babel-polyfill','./project/hivuiMain/index.js']
  // },
  // output: {
  //   filename: '[name].[contenthash].js',
  //   chunkFilename: '[name].[contenthash].js',
  //   path: path.resolve(__dirname, 'dist')
  // },
  resolve: {
    extensions: ['.js', '.jsx', '.vue', '.json', '.dtvevt', '.dvue'],
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      'vuex$': 'vuex/dist/vuex.esm.js',
      '@': path.resolve(__dirname, `${projectName}`),
      '@main': path.resolve(__dirname, `../${projectName}/hivuiMain`),
      // '@': path.resolve(__dirname, 'src'),
      '@birt': path.resolve(__dirname, `../${projectName}/hivuiBirt`),
      '@sam': path.resolve(__dirname, `../${projectName}/hivuiSam`),
      'pinyin': 'js-pinyin',
    }
  },
  externals: {
    'vue': 'Vue',
    'vuex': 'Vuex',
    'vue-router': 'VueRouter',
    "element-ui": "ELEMENT",
  },
  module: {
    rules: [
      ...(utils.styleLoaders({
        sourceMap: false,
        extract: process.env.NODE_ENV === 'production',
        usePostCSS: true
      })),
      {
        test: /\.(js|jsx|dtvevt?|babel|es6)$/,
        // use: [
        //   // threadLoader,
        //   'thread-loader',
        //   'babel-loader'
        // ] 
        use: ['babel-loader']
        // loader: 'babel-loader',
        // exclude: [path.resolve(__dirname, 'node_modules')]//放开，里头有些也是 可选链操作符
      },
      {
        test: /\.(vue|dvue)$/,
        // use: [
        //   // threadLoader,
        //   'thread-loader',
        //   {
        //     loader: 'vue-loader',
        //     options: vueLoaderConfig
        //   }
        // ]
        use: [{
          loader: 'vue-loader',
          options: vueLoaderConfig
        }]
        // loader: 'vue-loader',
        // options: vueLoaderConfig
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: '[name].[hash:7].[ext]',
          publicPath: "../img/",	//替换CSS引用的图片路径 可以替换成爱拍云上的路径
          outputPath: "static/img/"		//生成之后存放的路径
        }
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: '[name].[hash:7].[ext]',
          publicPath: "../img/",	//替换CSS引用的图片路径 可以替换成爱拍云上的路径
          outputPath: "static/media/"		//生成之后存放的路径
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: '[name].[hash:7].[ext]',
          publicPath: "../fonts/",	//替换CSS引用的图片路径 可以替换成爱拍云上的路径
          outputPath: "static/fonts/"		//生成之后存放的路径
        }
      }
    ]
  },

  optimization: {
    minimizer: [
      new UglifyJsPlugin({
        cache: true,
        parallel: true,
        sourceMap: true
      }),
      new OptimizeCSSAssetsPlugin({
        cssProcessor: require('cssnano'),
        cssProcessorPluginOptions: {
          preset: ['default', { discardComments: { removeAll: true } }],
        },
        canPrint: false
      })
    ],
    runtimeChunk: {
      "name": "manifest"
    },
    splitChunks: {
      cacheGroups: {
        default: false,
        vendors: false,
        common: {
          test: /[\\/]node_modules[\\/](babel-runtime|lodash|@babel|core-js)/,
          name: 'commons',
          priority: -90,
          minSize: 0,
          chunks: "all",
          reuseExistingChunk: true
        },
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          priority: -100,
          reuseExistingChunk: true,
          chunks: 'all'
        }
      }
    }
  },
  plugins: [
    new VueLoaderPlugin(),
    // new HappyPack({
    //   id: 'happy_js_jsx',
    //   //共享进程池
    //   threadPool: happyThreadPool,
    //   loaders: ['babel-loader']
    // }),
    // new HappyPack({
    //   id: 'happy-vue-loader',
    //   loaders: [{
    //     loader: 'vue-loader',
    //     options:vueLoaderConfig 
    //   }],
    //   threadPool: happyThreadPool
    // }),
    new webpack.HashedModuleIdsPlugin(),
    new ProgressBarPlugin(),
    // new CleanWebpackPlugin(['dist']),
    //注入全局变量的插件,通常使用该插件来判别代码运行的环境变量
    new webpack.DefinePlugin({
      'process.env': evnConfig
    }),
    new webpack.DllReferencePlugin({
      context: path.resolve(__dirname),
      manifest: require('../assets_platform/vendor_dll/vendor-manifest.json')
    }),
    //这个主要是将生成的vendor.dll.js文件加上hash值插入到页面中。[也可以手动写到html这里不做处理]
    // new AddAssetHtmlPlugin([{
    //   filepath: path.resolve(__dirname, 'js_dll/comm_vendors.dll.js'),
    //   outputPath: 'js_dll/',
    //   publicPath: 'js_dll/',
    //   includeSourcemap: false,
    //   hash: true,
    // }]),
    // new CopyWebpackPlugin([
    //   {
    //     from: path.resolve(__dirname, 'assets_platform'),
    //     to: path.resolve(__dirname, 'dist/assets_platform')
    //   },
    //   // {
    //   //   from: path.resolve(__dirname, 'js_dll'),
    //   //   to: path.resolve(__dirname, 'dist')
    //   // }
    // ])
  ]

};


