| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 | 'use strict';/** * * * @author Mai * @date * @version */const math = require('mathjs');class MaterialCalculate {    constructor(ctx, stage_id_list, tenderInfo) {        this.ctx = ctx;        this.stageList = stage_id_list;        this.percentReg = /[0-9]+%/g;        this.tenderInfo = tenderInfo;    }    /**     * 获取 计算基数     * @returns {Promise<void>}     */    async getCalcBase() {        if (this.bases) { return; }        const stage_list = await this.ctx.service.stage.getStageMsgByStageId(this.stageList);        const bases = await this.ctx.service.stage.getMaterialCalcBase(stage_list, this.tenderInfo);        this.bases = bases.sort(function(a, b) {            return a.sort - b.sort;            // if (a && b) {            //     return b.code.indexOf(a.code) >= 0 ? 1 : 0;            // } else {            //     return 0;            // }        });        for (const b of this.bases) {            b.reg = new RegExp(b.code, 'igm');        }    }    _calculateExpr(expr) {        try {            let formula = expr;            for (const b of this.bases) {                formula = formula.replace(b.reg, b.value);            }            const percent = formula.match(this.percentReg);            if (percent) {                for (const p of percent) {                    const v = math.eval(p.replace('%', '/100'));                    formula = formula.replace(p, v);                }            }            const value = parseFloat(math.eval(formula));            return value;        } catch (err) {            return 0;        }    }    async calculateExpr(expr) {        await this.getCalcBase();        return this._calculateExpr(expr);    }}module.exports = MaterialCalculate;
 |