const path = require('path');
const webpack = require('webpack');
const API_CONFIG = require('./webpack.api.js');

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');
// const PrerenderSPAPlugin = require('prerender-spa-plugin');
// const Renderer = PrerenderSPAPlugin.PuppeteerRenderer

let otherPlugins = [];
if (process.env.npm_config_report) {
  otherPlugins.push(new BundleAnalyzerPlugin());
}
// if(process.env.npm_config_snap){
//   otherPlugins.pish(new PrerenderSPAPlugin({
//     //代码打包目录和以前配置的目录保持一致
//     staticDir: path.join(dirname, packageDist), 
//     outputDir: path.join(dirname, 'prerendered'),
//     //routes：要预渲染的页面访问路由
//     routes: ['/','/about' ],
//     renderer: new Renderer({
//       // renderAfterDocumentEvent: 'render-event',//等待页面发送render-event消息后开始渲染
//       renderAfterTime:2000,//页面加载后2000毫秒后开始渲染
//       injectProperty: '__PRERENDER_INJECTED',
//         inject: {
//           foo: 'bar'
//         },
//         // headless：渲染时显示浏览器窗口。对调试很有用。
//         headless: true
//     }),
//   }))
// }
const dirname = __dirname;
const webpackPath=__webpackPath;
console.log(`=====================env=========================`);
console.log(`__dirname:${__dirname}`);
console.log(`dirname:${dirname}`);
console.log(`webpackPath:${webpackPath}`);
console.log(`build_env:${process.env.build_env}`);
console.log(`mock:${process.env.mock}`);
console.log(`noSkipNpmInstall:${process.env.noSkipNpmInstall}`);

console.log(`=====================env end=========================`);
const devMode = process.env.build_env !== 'prod';
const hashMode = process.env.build_env != 'localdebug';

const resource_path_relative='';

if (!devMode) {
  otherPlugins.push(new webpack.optimize.ModuleConcatenationPlugin());
}

let Alias = {};
// if(devMode){
//   Alias = {
//     'react-dom$': 'react-dom/profiling',
//     'scheduler/tracing': 'scheduler/tracing-profiling'
//   }
// }


let apiKeys = Object.keys(API_CONFIG.API_HOSTS);
let API_HOST={};
apiKeys.map(key=>{
  API_HOST[key] = JSON.stringify(API_CONFIG.API_HOSTS[key])
});

module.exports = {
  mode: devMode ? 'development' : 'production',
  devServer: {
    disableHostCheck: true,
    contentBase: "dist",
    host: '0.0.0.0',
    open: true,
    // port: 8080,
    // useLocalIp:true,
    // https:true,//注意开了https就不能使用本地ip访问，只能使用0.0.0.0
    proxy: API_CONFIG.API_PROXY
    // hot: true,
  },
  // 如果哪天不需要兼容ie11了，把这里@babel/polyfill去掉就行了
  entry: {
    index: [
      // '@babel/polyfill',
      path.resolve(dirname, 'src/index'),
    ],
  },
  output: {
    // devtoolModuleFilenameTemplate:'webpack:///dist/[resource-path]',
    filename: `[name]${hashMode ? '-[chunkhash]' : ''}.js`,
    // chunkFilename: 'js/[name]-[hash].chunk.js', // ./js/[name]-[hash].chunk.js
    path: path.join(dirname, 'dist/'),
    publicPath: resource_path_relative,
  },
  resolve: {
    modules: ['node_modules', path.resolve(webpackPath, 'node_modules'), path.join(dirname, 'src')],
    extensions: ['.jsx', '.js', '.json'],
    alias: {
      '@': path.resolve(dirname, 'src/'),
      ...Alias,
    },
  },
  module: {
    rules: [
      {
        test: /\.js[x]?$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              presets: [
                '@babel/preset-react',
                [
                  '@babel/preset-env',
                  {
                    targets: devMode
                      ? { chrome: '90' }
                      : {
                          chrome: '40',
                          ie: '11',
                        },
                  },
                ],
              ],
              plugins: [
                ['@babel/plugin-transform-runtime', { corejs: 3 }],
                '@babel/plugin-proposal-optional-chaining',
                '@babel/plugin-proposal-nullish-coalescing-operator',
                ['@babel/plugin-proposal-decorators', { legacy: true }],
                ['@babel/plugin-proposal-private-methods', { loose: true }],
                ['@babel/plugin-proposal-class-properties', { loose: true }],
                // ["import", {
                //   style: false,//"css",
                //   libraryName: "kn-hooks" ,
                //   libraryDirectory:"src",
                //   camel2DashComponentName:false,
                // }],
                // ["import", {
                //   style: true,//"css",
                //   libraryDirectory:"",
                //   libraryName: "antd" ,
                // }]
              ],
            },
          },
        ],
      },
      // {
      //   test: /\.json$/,
      //   use: 'json-loader'
      // },
      {
        test: /\.js[x]?$/,
        include: /kn-hooks/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              presets: [
                '@babel/preset-react',
                [
                  '@babel/preset-env',
                  {
                    targets: devMode
                      ? { chrome: '80' }
                      : {
                          chrome: '40',
                          ie: '11',
                        },
                  },
                ],
              ],
              plugins: [
                ['@babel/plugin-transform-runtime', { corejs: 3 }],
                '@babel/plugin-proposal-optional-chaining',
                '@babel/plugin-proposal-nullish-coalescing-operator',
                ['@babel/plugin-proposal-decorators', { legacy: true }],
                ['@babel/plugin-proposal-private-methods', { loose: true }],
                ['@babel/plugin-proposal-class-properties', { loose: true }],
              ],
            },
          },
        ],
      },
      {
        test: /\.(jpg|png|gif|svg)$/,
        loader: 'url-loader',
        options: {
          limit: 1024 * 5,
          name: `assets/[name].[hash:8].[ext]`,
        },
      },
      {
        test: /\.(ttf|eot|woff|woff2)$/,
        loader: 'file-loader',
        options: {
          name: `assets/font/[name].[hash:8].[ext]`,
        },
      },
      {
        test: /\.less$/i,
        exclude: /node_modules/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
          },
          {
            loader: 'css-loader',
            options: {
              importLoaders: 2,
              modules: { localIdentName: '[local]--[hash:base64:5]' },
            },
          },
          'postcss-loader',
          'less-loader',
        ],
      },
      // {
      //   test: /\.scss$/i,
      //   exclude: /node_modules/,
      //   use: [
      //     {
      //       loader: MiniCssExtractPlugin.loader,
      //       options: {
      //         publicPath: '../',
      //       },
      //     },
      //     {
      //       loader: 'css-loader',
      //       options: { importLoaders: 2, sourceMap:false, modules: { localIdentName: '[local]--[hash:base64:5]' } },
      //     },
      //     ...cssLoader,
      //     'sass-loader',
      //   ],
      // },
      {
        test: /\.css$/i,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
          },
          'css-loader',
          'postcss-loader'
        ],
      },
    ],
  },
  optimization: {
    minimize: devMode ? false : true, // 是否压缩js
    minimizer: [
      new TerserPlugin({
        parallel: true,
        sourceMap:true
        // terserOptions:{
        //   compress:false,
        //   mangle:false
        // }
      }),
      new OptimizeCssAssetsPlugin({}), //压缩css,配合MiniCssExtractPlugin使用
    ],
    runtimeChunk: {
      name: 'runtime', // 所有入口有自己的runtime.js
    },
    splitChunks: {
      cacheGroups: {
        react: {
          test: /(react)/,
          priority: 20,
          name: 'react-bundle',
          chunks: 'all',
          enforce: true,
        },
        styles: {
          priority: 1000,
          name: 'styles-bundle',
          test: /\.(le|sc|c)ss$/,
          chunks: 'all',
          enforce: true,
        },
        modules: {
          test: /(node_modules)/,
          priority: 2,
          name: 'modules-bundle',
          chunks: 'all',
          enforce: true,
        },
        default: {
          name: 'default-bundle',
          minChunks: 2,
          priority: 50,
          chunks: 'all',
          enforce: true,
        },
      },
    },
  },
  plugins: [
    new webpack.DefinePlugin({
      VERSION_HASH: JSON.stringify(`${Date.now()}-${new Date().toLocaleString()}`),
      BUILD_ENV: JSON.stringify(process.env.build_env),
      MOCK: process.env.mock == 1 ? '1' : false, //JSON.stringify(process.env.mock)
      ...API_HOST,
      PM_TYPE: JSON.stringify(process.env.pm_type),
    }),
    // new CleanWebpackPlugin(),
    new MiniCssExtractPlugin({ filename: `[name]${hashMode ? '-[chunkhash:8]' : ''}.css` }),
    new HtmlWebpackPlugin({
      chunks: ['index', 'runtime', 'react-bundle', 'modules-bundle', 'default-bundle', 'styles-bundle'],
      template: path.join(dirname, 'index.html'),
      filename: 'index.html',
      inject: true,
      isProd: process.env.build_env == 'prod',
    }),

    ...otherPlugins,
    new CopyPlugin({
      patterns: [
        { from: dirname + '/static', to: dirname + '/dist/static' },
        { from: dirname + '/pluginjs', to: dirname + '/dist/pluginjs' }
    ],
    }),
    new webpack.SourceMapDevToolPlugin({
      filename: 'sourcemap/[file].map',
      // publicPath: resource_path_relative,
      // fileContext: 'js',
    })
  ],
};
