var fsextra = require('fs-extra');
const path = require("path");
const glob = require('glob')
// const fs = require("fs");
// const {Chalk} = require('chalk')
const merge = require('webpack-merge');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const baseWebpackConfig = require('./webpack.base.conf');

const packageConfig = require('../package.json');
const projectName = packageConfig.name == 'hi-vui-template' ? 'project' : packageConfig.name
// console.log('---------------------webpack.get-list.js------------', process.env.NODE_ENV)
function repeat(array) {
  let map = new Map();
  let array1 = []; // 数组用于返回结果                    
  for (let i = 0, leng = array.length; i < leng; i++) {
    if (map.has(array[i])) {
      // 判断是否存在key                            
      map.set(array[i], true);
    } else {
      map.set(array[i], false);
      array1.push(array[i]);
    }
  }
  return array1;
}

// 用来记录当前打包的模块路径列表，判断进程参数
let argvs = (process.argv[2] || "").replace(/\s*$/g, "")
let moduleList = [];
let isBuildAll = true;
if (argvs) {
  isBuildAll = false;
  moduleList = [];
  let list = argvs.split(',');
  for (let i = 0, l = list.length; i < l; i++) {
    // let checkPath = fs.existsSync(list[i]+'/package.json');
    //如果目录存在 返回 true ，如果目录不存在 返回false
    // if (checkPath == false) continue;
    let modulePath = list[i].replace(/:空格:/gi,' ');//特别处理资源文件有空格的文件名
    
    let pathList = glob.sync(modulePath + '/package.json'); // 这个执行比较快 114.811ms
    if (pathList.length == 0) {
      // 查找modulePath目录
      // let ls = glob.sync(`${modulePath}/!(dist|node_modules|build)/**/package.json`)
      // for (let k = 0, l = ls.length; k < l; k++) {
      //   moduleList.push(ls[k].replace('/package.json', ''));
      // }
      if (modulePath == './assets_platform' || modulePath == './error') {
        let res = modulePath.replace('./', '');
        var isexist = fsextra.existsSync(path.resolve(__dirname, '../', res));
        isexist && fsextra.copySync(path.resolve(__dirname, '../', res), path.resolve(__dirname, '../dist/', res), {
          overwrite: false,
          // errorOnExist:false
        }) //拷贝模块资源目录  
      } else if (/\/deploy\/desktop\/[\w,\/,\.]*\/dpdst\/[\w,\/,\.]*(\.dpdst)$/.test(modulePath)) { //服务部署环境配置的.json
        let buildSchemePath = path.resolve(__dirname, '../', modulePath.replace('.dpdst', '.json'));
        let buildScheme = fsextra.readJsonSync(buildSchemePath);
        let buildSchemeDir = path.dirname(buildSchemePath);
        // 拷贝部署环境配置文件
        let sourceEnvPath = path.resolve(buildSchemeDir,'../', 'env/env.js');
        let envPath = path.resolve(__dirname, '../dist/', projectName + '/env.js');
        fsextra.copySync(sourceEnvPath, envPath, {
          // overwrite: false
        })
        let settingPath = path.resolve(__dirname, '../dist/', projectName + '/setting/desktop/appsetting.js');
        if (buildScheme.appSetting == null) {
          console.log('build_error:部署环境文件没有绑定，无法同步appSetting！');
          break;
        }
        fsextra.copySync(path.resolve(__dirname, '../', buildScheme.appSetting), settingPath, {
          overwrite: false,
          // errorOnExist:false
        }) //拷贝模块资源目录  

        if (buildScheme.menuPcIconDir) {//拷贝px图标目录
          let menuPcIconDir = path.resolve(__dirname, '../dist/', projectName + '/iconfonts/desktop');
          fsextra.copySync(path.resolve(__dirname, '../', buildScheme.menuPcIconDir), menuPcIconDir, {
            // overwrite: false
          })
        }
        if (buildScheme.menuMbIconDir) {//拷贝mobile图标目录
          let menuMbIconDir = path.resolve(__dirname, '../dist/', projectName + '/iconfonts/mobile');
          fsextra.copySync(path.resolve(__dirname, '../', buildScheme.menuMbIconDir), menuMbIconDir, {
            // overwrite: false
          })
        }

      } else { // if(/(\/res)$/.test(modulePath))
        let res = modulePath.replace('./', '');
        var isexist = fsextra.existsSync(path.resolve(__dirname, '../', res));
        isexist && fsextra.copySync(path.resolve(__dirname, '../', res), path.resolve(__dirname, '../dist/', res), {
          overwrite: false,
          // errorOnExist:false
        }) //拷贝模块资源目录  
      }
      continue
    } else {
      moduleList.push(modulePath);
    }
  }
} else {
  //编译所有，找出模块
  moduleList = require('./webpack.get-module').moduleList || [];
  
  
  //拷贝模块资源目录  
  let res = './assets_platform'.replace('./', '');
  let isexist = fsextra.existsSync(path.resolve(__dirname, '../', res));
  isexist && fsextra.copySync(path.resolve(__dirname, '../', res), path.resolve(__dirname, '../dist/', res), {
    overwrite: false,
    // errorOnExist:false
  }) 

  res = `./${projectName}/lang`.replace('./', '');
  isexist = fsextra.existsSync(path.resolve(__dirname, '../', res));
  isexist && fsextra.copySync(path.resolve(__dirname, '../', res), path.resolve(__dirname, '../dist/', res), {
    overwrite: false,
    // errorOnExist:false
  }) 


}
moduleList = repeat(moduleList); //去重

let evnConfig = require('./getEnvVar')

let webpackList = [],
  resList = [];
//构建webpack 配置

for (let i = 0, l = moduleList.length; i < l; i++) {
  let MODULE = moduleList[i];
  // console.log('---------------模块-------------',MODULE)
  if (isBuildAll) {
    //全部编译时拷资源文件res
    let res = MODULE.indexOf('/view') > -1 ? MODULE.split('view')[0] + 'res' : '';
    // console.log('=========================',res)
    if (res) {
      res = res.replace('./', '');
      var isexist = fsextra.existsSync(path.resolve(__dirname, '..', res));
      if (isexist) {
        // console.log('拷贝模块资源目录====',path.resolve(__dirname, '..', res))
        fsextra.copySync(path.resolve(__dirname, '..', res), path.resolve(__dirname, '../dist', res), {
          overwrite: false,
          // errorOnExist:false
        }) //拷贝模块资源目录    
      }

    }
  }
  // continue;
  //添加每个模块的webpack 配置
  let MODULE_NAME = MODULE.split('/').pop();
  let entry = {};
  let outputPath = path.resolve(__dirname, '../dist', MODULE)
  entry[MODULE_NAME] = ['babel-polyfill', `${MODULE}/index.js`]; // @babel/polyfill
  let wpk = merge({
    mode: 'production',
    // mode: 'development',
    // devtool: 'source-map',
  }, baseWebpackConfig, {
    entry: entry,
    output: {
      path: outputPath,
      filename: `static/js/[name].js`,
      // publicPath:'./'
      // publicPath: `/${evnConfig.VITE_APP_SERVER.replace(/"/gi,"")}/render/${packageConfig.author}/${MODULE.replace('./', '')}/`
      publicPath: `${evnConfig.VITE_APP_USERPATH.replace(/"/gi,"")}/${MODULE.replace('./', '')}/`
    }
  });
  let htmlTemplate = `${MODULE}/index.html`

  // var checkPath = fs.existsSync(htmlTemplate);
  // //如果目录存在 返回 true ，如果目录不存在 返回false
  // if (checkPath == false) {
  //   htmlTemplate = path.resolve(__dirname, './template.html')
  // }
  let pathList = glob.sync(htmlTemplate); // 这个执行比较快 114.811ms
  if (pathList.length == 0) htmlTemplate = path.resolve(__dirname, './template.html');

  wpk.plugins.push(new CleanWebpackPlugin([outputPath], {
    root: path.resolve(__dirname, '../'), //根目录
    //其他配置按需求添加
    verbose: false, //不提示删除
  }));
  wpk.plugins.push(
    new MiniCssExtractPlugin({
      filename: 'static/css/[name].[contenthash].css',
      chunkFilename: `static/css/[name].[contenthash].css`
    })
  );
  wpk.plugins.push(
    new HtmlWebpackPlugin({
      filename: path.resolve(__dirname, '../dist', MODULE, 'index.html'),
      template: htmlTemplate, //如果html 不存在考虑用全局根目录下
      inject: true,
      minify: {
        removeComments: true, //去除注释
        collapseWhitespace: true, //是否去除空格
        removeAttributeQuotes: true //去除空属性
      },
      compile: true
    }))

  var isexist = fsextra.existsSync(path.resolve(__dirname, '../', MODULE, 'lang'));
  if (isexist) {
    wpk.plugins.push(
      new CopyWebpackPlugin([{
        from: path.resolve(__dirname, '../', MODULE, 'lang'),
        to: path.resolve(__dirname, '../dist/', MODULE, 'lang'),
      }])
    )
  }
  webpackList.push(wpk);
}


module.exports = webpackList; // [webpackList[4]] ////[webpackList[3]];//27
