import _ from 'lodash'

/**
 * 主表赋值 接待活动单据主表报销金额赋值公式
 * 公式说明 此公式仅为接待活动单据使用
 * @author fengjiansheng
 * @data 2021-09-03
 */
export default {
    execute: function () {
        console.log("s1 SetMasterJdhdAmount")
        if (arguments && arguments[0] && arguments[0].length > 0 && arguments[1]) {
            let context = arguments[1]
            let controlField = arguments[0][arguments[0].length - 1]
            let subMoneyTotal = 0
            for (let [index, data] of arguments[0].entries()) {
                if(index === arguments[0].length - 1) {
                    continue
                }
                let tempSubTableObject = context.getTableType(data.FieldTableCode)
                if (!_.isEqual(tempSubTableObject.type, "sub")) {
                    console.error("SetMasterJdhdAmount公式配置错误,第", (index + 1), "个参数需为子表金额字段")
                    return null
                }
                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) {
                        if (_.isEqual(data.FieldTableCode,controlField.FieldTableCode)) {
                            let isAddFlag = "0"
                            if(!_.isEmpty(tempSubData.getValue(controlField.FieldCode))) {
                                isAddFlag = tempSubData.getValue(controlField.FieldCode).code
                            }
                            let tempData = tempSubData.getValue(data.FieldCode)
                            if (_.isNumber(_.toNumber(tempData))) {
                                subMoneyTotal += _.isEqual("1",isAddFlag)  ? 0 : _.toNumber(tempData)
                            } else {
                                console.error("SetMasterJdhdAmount公式配置错误,配置字段为非金额数据")
                                return null
                            }
                        } else{
                            let tempData = tempSubData.getValue(data.FieldCode);
                            if (_.isNumber(_.toNumber(tempData))) {
                                subMoneyTotal += _.toNumber(tempData)
                            } else {
                                console.error("SetMasterJdhdAmount公式配置错误,配置字段为非金额数据")
                                return null
                            }
                        }
                    }
                }
            }
            return subMoneyTotal
        }
    },
    getResultType: function () {
        return FMR.ConstDataTypes.General
    }
}
