const path = require("path");
let webpack = require("webpack");

process.traceDeprecation = false;
process.noDeprecation = true;

var pages = require("./plugins/entryFile").getEntryFile().pages;

const babelOptions = {
  cacheDirectory: true,
  presets: [require("babel-preset-env"), require("babel-preset-stage-0")],
  plugins: [
    // [
    //   require("babel-plugin-transform-runtime"),
    //   {
    //     helpers: false,
    //     regenerator: true,
    //     polyfill: false,
    //   },
    // ],
    require("babel-plugin-syntax-dynamic-import"),
    require("babel-plugin-transform-class-properties"),
    //	lighting支持jsx编译
    require("babel-plugin-syntax-jsx"),
    require("babel-plugin-transform-vue-jsx"),
  ],
  compact: "auto",
  //73460 light工程中lib目录中存在node_modules目录中的ethjs-util模块时编译不报错,打包报错的问题处理
  babelrc: false,
  //94259 lighting中编译支持缓存，提高编译效率
  // cacheDirectory:require("path").join(require("os").tmpdir(),'LIGHTING_WEBPACK_CACHE')
};
/**
 * 编译时需要删除的文件名列表
 * 支持配置文件格式和文件名
 * less 文件
 * vue 文件
 * */ 

 const extraFiles = [
  '.less',
  '.vue'
]
// 91743 多页工程
var entryArr = {};
if (pages && pages.length > 0) {
  // 通过配置关闭polyfill
  const usePolyfill = !(light.config.buildExConfig && light.config.buildExConfig.polyfill === false);
  pages.forEach(function (page) {
    //105231 指定多页工程的入口文件
    let entry = {};
    let key =
      pages.length == 1 && pages[0] == "index" && light.options.page != "index"
        ? "app"
        : page;
    let mainjs = page == "index" ? "app" : page;
    const installEntry = path.join(light.config.dist, 'view', page + '.js');
    entry[key] = usePolyfill ? ['@babel/polyfill', installEntry] : [installEntry];

    //118407 lighting支持当light工程不存在app.js时的打包
    const appFile = `${light.config.src}/${mainjs}.js`;
    if (light.util.existsSync(appFile)) {
      entry[key].push(appFile);
    }
    entryArr = Object.assign(entryArr, entry);
  });
}
//bug94269 缓存时图片不添加时间戳后缀
let imghash =
  light.config.plugins &&
  light.config.plugins.toString().indexOf("cachemanifest") > -1;
// 用于eslint检测，loader和eslint都要安装，若eslint安装在用户项目里会导致loader找不到依赖
// 默认不开启eslint检测，在project.json配置eslint: true或使用命令行--eslint才开启
let eslintLoader = [];
if (light.options.eslint || light.config.eslint) {
  eslintLoader = [{
    enforce: 'pre',
    test: /\.(js|vue)$/,
    exclude: /node_modules/,
    loader: 'eslint-loader'
  }];
}

let config = {
  entry: entryArr,
  module: {
    rules: [
      ...eslintLoader,
      {
        test: /\.(less|css)$/,
        use: [
          {
            loader: "style-loader", // creates style nodes from JS strings
          },
          {
            loader: "css-loader", // translates CSS into CommonJS
          },
          {
            loader: "less-loader", // compiles Less to CSS
          },
        ],
      },
      {
        test: /\.js$/,
        //去除node_modules目录的es6转es5流程，加快编译速度
        exclude:
          light.options.watch
            ? [
                function (file) {
                  // 过滤${__dirname}/..绝对路径下的任意目录下的 lighting-frame
                  return /(node_modules\/(?!.*lighting\-frame)|bower_components)/gi.test(
                    file
                  );
                },
              ]
            : undefined,
        rules: [
          {
            test: /\.js$/,
            loader: "babel-loader",
            options: babelOptions
          }
        ]
      },
      {
        test: /\.(png|jpg|gif|svg|ttf|woff|eot|otf)$/,
        loader: "file-loader",
        options: {
          name: imghash
            ? "[path][name].[ext]"
            : "[path][name].[ext]?[hash]",
        },
      },
    ],
  },
  resolve: {
    extensions: [".js", ".vue", ".json"],
    //S2103120133【lighting】修复指定dist目录的情况下同时编译和打包报错的问题
    modules: [
      `${__dirname}/node_modules`,
      "lib/node_modules",
      "lib",
      "node_modules",
      `${light.config.projectPath}/node_modules`,
      `${__dirname}/..`,
    ],
    alias: {
      // light: `olight`,
      light: path.resolve(__dirname,'./lighting-frame/light.js'),
      vue: "vue/dist/vue.esm",
      "@": light.config.src,
    },
  },
  plugins: [
    new require("progress-bar-webpack-plugin")({
      format:
        "  编译中 [:bar] " +
        require("chalk").green.bold(":percent") +
        " (:elapsed 秒)",
      clear: false,
    }),
    new webpack.NoEmitOnErrorsPlugin(),
    new (require("./plugins/loader"))({
      babel: babelOptions,
    }),
  ],
  resolveLoader: {
    //S2103120133【lighting】修复指定dist目录的情况下同时编译和打包报错的问题
    modules: [
      `${__dirname}/node_modules`,
      "lib/node_modules",
      "lib",
      "node_modules",
      `${light.config.projectPath}/node_modules`,
      `${__dirname}/..`,
    ],
  },
  stats: {
    chunks: false,
    colors: true
  }
};

//102711 vue代码中有错误，比如import写错，使用light release -p 打包，无法报错
//227597 开发阶段报错提示
if(!light.options.watch || !(light.options.eslint || light.config.eslint)){
  config.plugins.push(function () {
    this.plugin("done", function (stats) {
      if (stats.hasWarnings() || stats.hasErrors()) {
        // 格式化输出错误和警告
        let webpackOutputConfig = {
          warnings: false,
          colors: true
        };
        if (light.config.webpackOutputConfig) {
          Object.prototype.hasOwnProperty.call(light.config.webpackOutputConfig, 'warnings')
            && (webpackOutputConfig.warnings = !!light.config.webpackOutputConfig.warnings);
        }
        console.log(stats.toString(webpackOutputConfig));
      }
    });
  });
}

// 删除light.config.dist目录下已处理的文件
if (!light.options.watch) {
  config.plugins.push(function () {
    this.plugin("done", function (stats) {
      const shell = light.util.require('shelljs');
      const fileDependencies = stats.compilation.fileDependencies || [];
      for (const dependence of fileDependencies) {
        const filename = path.basename(dependence)
        const extname = path.extname(filename).toLowerCase()
        // 判断 dependence 在 light.config.src 目录下才要删除
        if (dependence.replace(/\\/g, '/').startsWith(light.config.src.replace(/\\/g, '/')) &&
          dependence.indexOf('node_modules') < 0 &&
          (extraFiles.includes(filename) || extraFiles.includes(extname))) {
          shell.rm("-fr", dependence.replace(light.config.src, light.config.dist));
        }
      }
    });
  });
}
if (light.options.uglify) {
  // 【TS:202103010432-财富经纪业务群_潘腾-【业务产品名称(或简称)】：【场景说明】：分析了light打】
  let UglifyJsPlugin = require("uglifyjs-webpack-plugin");
  config = require("webpack-merge")(
    {
      plugins: [
        new UglifyJsPlugin({
          test: /\.js($|\?)/i,
          parallel: light.options.uglify, // 增加进程数配置，防止在限制资源的docker等环境会压缩失败
          uglifyOptions: {
            warnings: false,
          },
        }),
      ],
    },
    config
  );
}

module.exports = config;
