'use strict';

/**
 *
 *
 * @author Zhong
 * @date 2019/11/1
 * @version
 */

((factory) => {
    if (typeof module !== 'undefined') {
        module.exports = factory();
    } else {
        window.BILLS_UTIL = factory();
    }
})(() => {
    // 清单模板各清单重设ID时，重新转换清单基数的ID引用
    function parseCalcBase(calcBase, uuidMapping) {
        const orgIDRefs = [...new Set(calcBase.match(/@\d+/g))];
        orgIDRefs.forEach(orgRef => {
            const orgID = orgRef.match(/\d+/)[0];
            const newID = uuidMapping[orgID] || null;
            // ID匹配不上则不转换这个引用
            if (!newID) {
                return;
            }
            const replaceStr = `@${newID}`;
            calcBase = calcBase.replace(new RegExp(`${orgRef}\\b`, 'g'), replaceStr);
        });
        return calcBase;
    }

    /*
     * @param {Array}billsList (完整的清单树结构数据)
     * @param {Function}idFactory 生成ID的方法
     * @return {void}
     * */
    function resetTreeData(billsList, idFactory) {
        const idMapping = {};
        idMapping['-1'] = -1;
        // 建立新ID-旧ID映射
        billsList.forEach(bills => idMapping[bills.ID] = idFactory());
        const reg = /@\d+/;
        billsList.forEach(function (bills) {
            bills.ID = idMapping[bills.ID] ? idMapping[bills.ID] : -1;
            bills.ParentID = idMapping[bills.ParentID] ? idMapping[bills.ParentID] : -1;
            bills.NextSiblingID = idMapping[bills.NextSiblingID] ? idMapping[bills.NextSiblingID] : -1;
            const needToParseCalcBase = bills.calcBase && reg.test(bills.calcBase);
            if (needToParseCalcBase) {
                bills.calcBase = parseCalcBase(bills.calcBase, idMapping);
            }
        });
    }

    return {
        parseCalcBase,
        resetTreeData
    };
});