const {join, resolve} = require('path');
const webpack = require('webpack');
const glob = require('glob');
const vuxLoader = require('vux-loader');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const packagejson = require('./package.json');

// 频道(undefined/debug)
let channel = undefined;

let entries = {
    vendor: ["@antv/f2","qrcode","vue","vux"]
    // vendor: Object.keys(packagejson.dependencies)
};
if (process.env.NODE_ENV === 'development') {
    // channel = 'debug'
}
let chunks = [];
let winMap = {};
getEntriesAndChunks();

let config = {
    entry: entries,
    output: {
        path: resolve(__dirname, './dist'),
        filename: '[name].js',
        publicPath: process.env.NODE_ENV === 'production' ? undefined : '/'
    },
    resolve: {
        //配置别名，在项目中可缩减引用路径
        extensions: ['.js', '.vue'],
        alias: {
            assets: join(__dirname, '/src/assets'),
            components: join(__dirname, '/src/components'),
            public: join(__dirname, '/src/public'),
            root: join(__dirname, 'node_modules')
        }
    },
    externals: [
        {api: "window.api"}
    ],
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: 'vue-loader'
            },
            {
                test: /\.js$/,
                use: 'babel-loader',
                exclude: /node_modules/
            },
            {
                test: /\.(less|css)$/,
                use: ['style-loader', 'css-loader', 'less-loader'],
            },
            {
                test: /\.html$/,
                use: [{
                    loader: 'html-loader',
                    options: {
                        root: resolve(__dirname, 'src'),
                        attrs: ['img:src', 'link:href']
                    }
                }]
            },
            {
                test: /\.(png|jpe?g|gif|svg|svgz)(\?.+)?$/,
                exclude: /iconfont\.svg/,
                use: [{
                    loader: 'url-loader',
                    options: {
                        limit: 10000,
                        name: 'assets/img/[name].[ext]'
                    }
                }]
            },
            {
                test: /\.(eot|woff|woff2|svg|ttf)([?]?.*)$/,
                use: 'file-loader'
            },
            {
                test: /muse-ui.src.*?js$/,
                use: 'babel-loader'
            }
        ]
    },
    plugins: [
        // new BundleAnalyzerPlugin(),
        new webpack.optimize.CommonsChunkPlugin({
            name: ["vendor", 'runtime'],
            filename: '[name].js',
            // minChunks: Infinity
        }),
        // new webpack.optimize.CommonsChunkPlugin({
        //     children: true,
        //     async: 'children-async'
        // }),
        new ExtractTextPlugin({
            filename: '[name].css',
            allChunks: true
        }),
        new webpack.DefinePlugin({
            "webpackConfigParams": JSON.stringify({
                winMap: winMap,
                channel: channel
            })
        })
    ],
    devServer: {
        host: '192.168.31.103',
        port: 8400,
        historyApiFallback: false,
        noInfo: true,
        proxy: {
            '/api': {
                target: 'http://127.0.0.1:8400',
                changeOrigin: true,
                pathRewrite: {'^/api': ''}
            }
        },
    },
    devtool: '#eval-source-map'
};

const pages = getHtmls();

pages.forEach(function (pathname) {
    // filename 用文件夹名字
    let firstSlashIndex = pathname.indexOf('/');
    let lastSlashIndex = pathname.lastIndexOf("/");
    let fileBasename = pathname.substring(firstSlashIndex + 1, lastSlashIndex);
    var conf = {
        filename: fileBasename + '.html', //生成的html存放路径，相对于path
        template: 'src/' + pathname + '.html', //html模板路径
    };
    var chunk = fileBasename;
    if (chunks.indexOf(chunk) > -1) {
        conf.inject = 'body';
        conf.chunks = ['vendor', 'runtime', chunk];
    }
    if (process.env.NODE_ENV === 'production') {
        conf.hash = true;
    }
    config.plugins.push(new HtmlWebpackPlugin(conf));
});

module.exports = vuxLoader.merge(config, {
    plugins: [
        {
            name: 'vux-ui'
        },
        {
            name: 'duplicate-style'
        },
        {
            name: 'less-theme',
            path: 'src/assets/css/vux-style-variable.less'
        }
    ]
});
function getPackRange(ext) {
    let result = [];
    if (channel === 'debug') {
        result = result.concat(glob.sync("./src/pages/html/testdemo/*" + ext));
        result = result.concat(glob.sync("./src/pages/html/main/*" + ext));
        result = result.concat(glob.sync("./src/pages/html/login/*" + ext));
        result = result.concat(glob.sync("./src/pages/html/sctask-finish/*" + ext));
        result = result.concat(glob.sync("./src/pages/html/selection/**/*" + ext));
        result = result.concat(glob.sync("./src/pages/html/wrkgrp-baditem/**/*" + ext));
    } else {
        result = result.concat(glob.sync("./src/pages/**/*"+ext));
    }
    return result;
}
function getEntriesAndChunks() {
    getPackRange('.js').forEach(function (name) {
        let lastSlashIndex = name.lastIndexOf("/");
        var n = name.slice(name.lastIndexOf('src/') + 10, lastSlashIndex);
        entries[n] = [name];
        var winName = n.slice(n.lastIndexOf('/') + 1, n.length);
        if (!winMap[winName]) {
            winMap[winName] = n;
        }
        else {
            throw "页面名称重复：" + winName;
        }
        chunks.push(n);
    });
}

function getHtmls() {
    var htmls = [];
    getPackRange('.html').forEach(function (name) {
        var n = name.slice(name.lastIndexOf('src/') + 4, name.length - 5);
        htmls.push(n);
    });
    return htmls;
}
if (process.env.NODE_ENV === 'production') {
    module.exports.devtool = false;
    module.exports.plugins = (module.exports.plugins || []).concat([
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"production"'
            }
        }),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        })
    ]);
}