import _ from 'lodash'
import util from './FormulaConstants'

/**
 * 金额校验 校验业务登记单主子表金额是否相等
 * @author fengjiansheng
 * @date 2021-08-29
 */
export default {
    execute: function () {
        console.log("s1 CheckAmount")
        if (arguments && arguments[0] && arguments[0].length > 1 && arguments[1]) {
            let context = arguments[1]
            let masterField = arguments[0][0]
            let masterTableObject = context.getTableType(masterField.FieldTableCode)
            if (!_.isEqual(masterTableObject.type, "master")) {
                console.error("CheckAmount公式配置错误,第一个参数需为主表金额字段")
                return false;
            }
            let masterData = context.getMasterData().getValue(masterField.FieldCode)
            let masterMoney = _.toNumber(masterData)
            let subMoneyTotal = 0
            for (let [index, data] of arguments[0].entries()) {
                if (index === 0) {
                    continue
                }
                let tempSubTableObject = context.getTableType(data.FieldTableCode)
                if (!_.isEqual(tempSubTableObject.type, "sub")) {
                    console.error("CheckAmount公式配置错误,第", (index + 1), "个参数需为子表金额字段")
                    return false;
                }
                let allSubData = context.getAllSubData()
                if (!allSubData || _.isEmpty(allSubData)) {
                    break
                }
                let tempAllSubData = context.getAllSubData()[tempSubTableObject.title]
                if (!tempAllSubData || _.isEmpty(tempAllSubData)) {
                    continue
                }
                if (tempAllSubData instanceof Array) {
                    for (const tempSubData of tempAllSubData) {
                        let tempData = tempSubData.getValue(data.FieldCode)
                        if (_.isNumber(_.toNumber(tempData))) {
                            subMoneyTotal += _.toNumber(tempData)
                        } else {
                            console.error("公式配置错误,配置字段为非金额数据")
                            return false
                        }
                    }
                }
            }
            return Math.abs(masterMoney - subMoneyTotal ) <= 0.0000001
        }
    },
    getResultType: function () {
        return FMR.ConstDataTypes.Bool
    }
}
