const util = require('@vue/component-compiler-utils');
const VueTemplateCompiler = require('vue-template-compiler');
const loaderUtils = require('loader-utils');

const addDiv = require('./addDiv');
const conditionalCompilation = require('./conditionalCompilation');

// 一个vue文件可能被多次loader加载
const hasLoadVue = {};

module.exports = function (source) {
    if (source.substr(0, 21) === '<!-- webview only -->') {
        return source;
    }

    const options = loaderUtils.getOptions(this);

    let result = util.parse({
        source: source,
        compiler: VueTemplateCompiler,
        needMap: false
    });

    // 配合微信在自定义组件外层增加一层div
    if ((options.isUni || process.argv.indexOf('--uni') !== -1) && !hasLoadVue[this.resourcePath]) {
        hasLoadVue[this.resourcePath] = true;
        result = addDiv(result, this.resourcePath);
    }

    // 条件编译
    result = conditionalCompilation(result, options);

    let styleStr = '';

    result.styles && result.styles.forEach(style => {
        let attrStr = '';

        for (let key in style.attrs) {
            if (style[key] === true) {
                attrStr += ` ${key}`;
            } else {
                attrStr += ` ${key}="${style[key]}"`;
            }
        }

        styleStr += `\n<style${attrStr}>
    ${style.content}
</style>`
    });
    const attrsTemplate = []
    Object.keys(result.template.attrs).forEach(attr => {
        attrsTemplate.push(`${attr}="${result.template.attrs[attr]}"`)
    })

    const attrsScript = []
    Object.keys(result.script.attrs).forEach(attr => {
        attrsScript.push(`${attr}="${result.script.attrs[attr]}"`)
    })

    const newSource = `<template ${attrsTemplate.join(' ')}>
    ${result.template.content}
</template>

<script ${attrsScript.join(' ')}>
    ${result.script.content}
</script>
${styleStr}`;

    return newSource;
}