const qs = require('qs');
const shortId  = require('shortid');

module.exports = function (source) {
    const query = qs.parse(this.resourceQuery);
    let output = source;

    // Vue刚编译，进来进行文件判断是否有cover-view
    if (Object.keys(query).length === 0) {
        if (/<\/cover-view>/.test(source)) {
            global._bili_cache_data.coverMapping[this.resourcePath] = {
                shortId : shortId.generate()
            }
        }
    } else if (global._bili_cache_data.coverMapping[this.resourcePath]){
        // cover-view 替换节点
        output = source.replace(/(<cover-view[^<]*>)|(<cover-input[^<]*>)|(<cover-textarea[^<]*>)|(<cover-label[^<]*>)|(<cover-button[^<]*>)|(<cover-image[^<]*>)|(<cover-svga[^<]*>)/mg, (x)=>{
            return x.replace('>', ` key="${shortId.generate()}" classKey="${global._bili_cache_data.coverMapping[this.resourcePath].shortId}">`);
        })
    }

    // 半屏小程序降级（用户直接将全屏小程序input编译成半屏）替换，将 b-input 和 b-textarea 替换成 b-textfield
    if (global._bili_cache_data.APPID.indexOf('widget') > -1) {
        output = output.replace(/(<b-input)|(<b-textarea)|(<\/b-input>)|(<\/b-textarea>)/mg, function (str) {
            if (str === '<b-input') return '<b-textfield';
            if (str === '<b-textarea') return '<b-textfield  multiple="true"';
            if (str === '</b-input>') return '</b-textfield>';
            if (str === '</b-textarea>') return '</b-textfield>';
        });
    }

    return output;
}
