import reg from "../shares/reg.js";
import {$el} from './getElPlugin.js'

/**
 * @param opt Object {
     data:opt.data,
     rule:opt.rule,
     dom:opt.dom,
     el:opt.el,
     idx:opt.idx
     success:opt.success
 * }
 */

export default function htmlInsert(opt) {
    let _opt = opt instanceof Array
        ? [...opt]
        : [opt]
    for (let opt of _opt) {
        let once = {
                data: opt.data instanceof Array ? [...opt.data] : [opt.data],
                rule: opt.rule,
                dom: opt.dom,
                el: opt.el,
                idx: 0,
                success: opt.success,
                resItem: null,
            }, sHtml = '',
            tarHtml = []
        once.data.map((item, idx) => {
            if (!once.rule && !(item instanceof Array) && (JSON.stringify(item)!=='{}') && item ) {
                sHtml += domWalk(once.dom, item, once.success, once.idx)
                tarHtml.push(domWalk(once.dom, item, once.success, once.idx))
            }
        });
        (once.el
            && ( typeof once.el === 'string' && ($el(once.el).innerHTML = sHtml)
            || (()=>{
                if(once.el instanceof Array){
                    once.el.map(item=>{
                        item.innerHTML  = sHtml
                    })
                }
            })()
            ));
        once.data.map((item, idx) => {
            once.success && once.success({rItem: item, idx: idx,tarHtml:tarHtml[idx],})
        })
    }
    return true
}

export function domWalk(dom, item, cb, userIdx) {
    let str = reg.regDom.test(dom) && (!/item/g.test(dom.match(reg.regDom)?.[0])) ? '' : dom
    if (str) {
        return str
    }
    let key = dom.match(reg.regDom)?.[1].trim()
    str = dom.replace(dom.match(reg.regDom)?.[0], (new Function('item', `with(item){ return ${key}}`))(item))
    return domWalk(str, item, cb, userIdx)
}
