let webpack = require('webpack');
const path = require("path");
const config = require("./webpack.config");
const merge = require("webpack-merge");
var postcss = require('postcss');
let projectConfig; // 配置文件
try{
    projectConfig = require(path.join(light.config.src, 'project.json'));
}catch(err){
    console.warn(err)
}

//105231 多页工程下app更名为index
var pages = require('./plugins/entryFile').getEntryFile().pages;
function extend(pages, item) {
    let entryObj = { entry: {} };
    for (var key in config.entry) {
        entryObj.entry[key] = item;
    }
    return entryObj;
}


let webpackconfig = {
    output: {
        path: light.config.dist,
        //75948 异步视图支持添加反缓存的后缀
        chunkFilename: 'lightdist/[name].js?[chunkhash]',
        filename: '[name].js'
    },
    module: {
        rules: [{
            test: /\.vue$/,
            loader: 'vue-loader',
            options: {
            }
        }],
    },
    plugins: [
        new webpack.DefinePlugin({
            'process.env.RUNTIME': JSON.stringify("web"),
            'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
            'process.env.ONLY_FOR': JSON.stringify(light.options.onlyFor),
            '__ENV__': require("./env")(light.options.env || 'default')
        }),
    ]
};


//97331 兼容带版本号的jsnative
//112979 移除 --native
if (!light.config.plugins || light.config.plugins.toString().indexOf("jsnative") < 0) {
    webpackconfig.module.rules[0].options.postcss = [
        require('autoprefixer')({
            browsers: ['> 0.1%', 'ios >= 8', 'not ie < 12']
        })
    ];

    //184573 对于miniapp工程，或者启用miniapp插件的工程，再编译为H5环境时处理页面的px为10rem 使用postcss
    require("./lib/utils").hasPlugin("miniapp") && webpackconfig.module.rules[0].options.postcss.push(require('postcss-plugin-px2rem')({
        rootValue: 75,
        minPixelValue: 1.01
    }))
} else {

    webpackconfig.module.rules[0].options.postcss = [
        // to convert weex exclusive styles.
        require('postcss-plugin-weex')(),
        require('autoprefixer')({
            browsers: ['> 0.1%', 'ios >= 8', 'not ie < 12']
        }),
        require('postcss-plugin-px2rem')({
            // base on 750px standard.
            rootValue: 75,
            // to leave 1px alone.
            minPixelValue: 1.01
        })
    ];
    webpackconfig.module.rules[0].options.compilerModules = [{
        postTransformNode: el => {
            // el.staticStyle = `$processStyle(${el.staticStyle})`
            // el.styleBinding = `$processStyle(${el.styleBinding})`
            require('weex-vue-precompiler')()(el)
        }
    }];
    //105231 给入口文件合并资源
    webpackconfig = merge(extend(pages, [`${__dirname}/weex.init.js`,]), webpackconfig);

}



if (light.options.watch) {
    // 扩展插件
    const plugins = [
        new webpack.HotModuleReplacementPlugin({
            multiStep: false,
        })
    ]
    // 扩展js
    const extraJsList = [`${__dirname}/plugins/qrcode.js`, 'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000'];
    if(projectConfig && projectConfig.pluginConfig && projectConfig.pluginConfig.analyze){
         //93779 lighting工程编译时如果是添加了-w选项则在控制台提示用户可以查看编译资源树及分析
         plugins.push(new (require('webpack-visualizer-plugin'))());
         extraJsList.push(`${__dirname}/plugins/analyzeLog.js`)
    }
    let sourceMap = 'source-map'
    if (projectConfig && projectConfig.pluginConfig) {
        if (Object.prototype.hasOwnProperty.call(projectConfig.pluginConfig, 'sourceMap')) {
            const sourceMapKey = projectConfig.pluginConfig.sourceMap
            if (typeof sourceMapKey === 'string' || sourceMapKey === false) {
                sourceMap = sourceMapKey
            }
        }
    }
    // 93781 lighting工程不管是jsn项目还是纯h5项目都在控制台显示二维码-qrcode必须在weex-init之后
    webpackconfig = merge(webpackconfig,{
        devtool: sourceMap, // 支持 sourceMap 可配置
        //105231 给入口文件合并资源
        entry: extend(pages, extraJsList).entry,
        plugins
    })
}

// 61306【lighting】再增加一个参数单独控制是否开启vConsole
if (light.options.console) {
    //105231 给入口文件合并资源
    webpackconfig = merge(extend(pages, [`${__dirname}/plugins/vconsole.js`]), webpackconfig)

}


module.exports = {
    build() {
        let distConfig = merge(webpackconfig, config);

        // 59972 【lighting】可以考虑在现有约定的基础上开放自定义配置接口（Webpack和Babel）
        let buildJS = require("path").join(light.config.src, "build.js");
        if (require("fs").existsSync(buildJS)) {
            distConfig = require(buildJS).build(distConfig, merge, webpack)
        }

        return distConfig;
    }
};
