var tableArray = [
    {
        parms: {},
        node: "reimbursementApplierGrid",
        gridManager: null,
        data: null,
        columns: getColumns(),
    },
    {
        parms: {},
        node: "financialAuditGrid",
        gridManager: null,
        data: null,
        columns: [
            {display: "", name: "rstgr", width: 80, minwidth: 80, type: "string", align: "left", hide: true},
            {display: "EP流程子序号", name: "zepItemno", width: 80, minwidth: 80, type: "string", align: "left"},
            {
                display: "是否付款", name: "zepPay", width: 120, minwidth: 120, type: "string", align: "left",
                editor: {
                    required: false, type: "select",
                    data: {
                        type: 'system',
                        name: "dictionary",
                        getParam: function (item) {
                            return {fieldName: "ZEP_PAY"}
                        },
                        back: {
                            ZEP_PAY: "zepPay",
                        }
                    },
                }
            },
            {
                display: "原因代码", name: "rstgrName", width: 120, minwidth: 120, type: "string", align: "left",
                editor: {
                    required: false, type: "select",
                    data: {
                        type: 'system',
                        name: "dictionary",
                        getParam: function (item) {
                            return {
                                fieldName: "RSTGR",
                                filterValue:$("#bukrs").val()
                            }
                        },
                        back: {
                            RSTGR: "rstgr",
                            TXT40: "rstgrName",
                        }
                    },
                }
            },
            {
                display: "不含税金额（审批）",
                name: "zepPdamount1",
                width: 120,
                minwidth: 120,
                type: "money",
                align: "left",
                editor: {
                    mask: 'nnnnnnnnn.nn',
                    type: 'text'
                }
            },
            {
                display: "税额（审批）", name: "zepPdtax1", width: 120, minwidth: 120, type: "money", align: "left",
                editor: {
                    mask: 'nnnnnnnnn.nn',
                    type: 'text'
                }
            },
            {
                display: "含税金额（审批）",
                name: "zepPtdamount1",
                width: 120,
                minwidth: 120,
                type: "money",
                align: "left",
                editor: {
                    mask: 'nnnnnnnnn.nn',
                    type: 'text'
                }
            },
            {
                display: "不含税金额（审批-本位币）",
                name: "zepPdamount",
                width: 160,
                minwidth: 120,
                type: "money",
                align: "left",
                editor: {
                    mask: 'nnnnnnnnn.nn',
                    type: 'text'
                }
            },
            {
                display: "税额（审批-本位币）",
                name: "zepPdtax",
                width: 150,
                minwidth: 120,
                type: "money",
                align: "left",
                editor: {
                    mask: 'nnnnnnnnn.nn',
                    type: 'text'
                }
            },
            {
                display: "含税金额（审批-本位币）",
                name: "zepPtdamount",
                width: 150,
                minwidth: 120,
                type: "money",
                align: "left",
                editor: {
                    mask: 'nnnnnnnnn.nn',
                    type: 'text'
                }
            },
            {display: "", name: "zlsch", width: 80, minwidth: 80, type: "string", align: "left", hide: true},
            {
                display: "付款方式", name: "zlschTextView", width: 200, minwidth: 120, type: "string", align: "left",
                editor: {
                    type: 'dictionary',
                    data: {name: 'zlsch'},
                    textField: 'zlschTextView',
                    valueField: 'zlsch',
                    required: false,
                    render: function (item) {
                        return item.zlschTextView;
                    }
                },
            },
            {
                display: "直联付款标识", name: "zepBank", width: 120, minwidth: 120, type: "string", align: "left",
                editor: {
                    required: false, type: "select",
                    data: {
                        type: 'system',
                        name: "dictionary",
                        getParam: function (item) {
                            return {fieldName: "ZEP_BANK"}
                        },
                        back: {
                            ZEP_BANK: "zepBank",
                        }
                    },
                }
            },
        ]
    }
    , {
        parms: {},
        node: "financialAudit_sapReturnGrid",
        gridManager: null,
        data: null,
        columns: [
            {display: "EP流程子序号", name: "zepItemno", width: 80, minwidth: 80, type: "string", align: "left"},
            {display: "记账凭证编号", name: "belnr", width: 120, minwidth: 120, type: "string", align: "left"},
            {display: "记账凭证财年", name: "gjahr", width: 120, minwidth: 120, type: "string", align: "left"},
            {display: "记账过账日期", name: "budat", width: 120, minwidth: 120, type: "string", align: "left"},
            {display: "记账凭证日期", name: "bldat", width: 120, minwidth: 120, type: "string", align: "left"},
            {display: "返回状态", name: "msgty", width: 120, minwidth: 120, type: "string", align: "left"},
            {display: "返回消息", name: "msgtx", width: 300, minwidth: 120, type: "string", align: "left"},
        ]
    }
    , {
        parms: {},
        node: "paymentAccomplish_sapReturnGrid",
        gridManager: null,
        data: null,
        columns: [
            {display: "EP流程子序号", name: "zepItemno", width: 80, minwidth: 80, type: "string", align: "left"},
            {display: "付款凭证编号", name: "belnr1", width: 120, minwidth: 120, type: "string", align: "left"},
            {display: "付款凭证财年", name: "gjahr1", width: 120, minwidth: 120, type: "string", align: "left"},
            {display: "付款状态", name: "zpayStaus", width: 120, minwidth: 120, type: "string", align: "left"}
        ]
    }
];

function getColumns() {
    var columns =[]
    //columns push reimbursementApplierGrid的字段
    columns.push({display: "EP流程子序号", name: "zepItemno", width: 80, minwidth: 80, type: "string", align: "left"},);
    columns.push({display: "研发项目", name: "zzyl01", width: 200, minwidth: 80, type: "string", align: "left",
        editor: {
            required: false, type: "text",
        }
    });
    columns.push({display: "", name: "reimbursementDetailId", width: 80, minwidth: 80, type: "string", align: "left", hide: true},);
    columns.push({display: "", name: "reimbursementBaseInfoId", width: 80, minwidth: 80, type: "string", align: "left", hide: true},);
    columns.push({display: "", name: "mwskz", width: 80, minwidth: 80, type: "string", align: "left", hide: true},);
    columns.push({display: "计划内外付款标识", name: "zepPlan", width: 120, minwidth: 120, type: "string", align: "left",
        editor: {
            required: true, type: "select",
            data: {
                type: 'system',
                name: "dictionary",
                getParam: function (item) {
                    return {fieldName: "ZEP_PLAN"}
                },
                back: {
                    ZEP_PLAN: "zepPlan",
                    ZEP_PLANNAME: "zepPlanname"
                }
            },
        }
    });
    columns.push({display: "计划内外标识名称", name: "zepPlanname", width: 120, minwidth: 120, type: "string", align: "left",});
    columns.push({display: "BP标识", name: "zepBptype", width: 80, minwidth: 60, type: "string", align: "left",});
    columns.push({display: "BP标识描述", name: "zepBptypename", width: 100, minwidth: 80, type: "string", align: "left",});
    columns.push({display: "BP(合作伙伴)", name: "partner", width: 120, minwidth: 120, type: "string", align: "left",
        editor: {
            required: true, type: "select",
            data: {
                type:'system',
                name: "getCusAndSuppliers",
                getParam: function (item) {
                    return {
                        ZEP_BPTYPE: item.zepBptype,
                        BUKRS:$("#bukrs").val()
                    }
                },
                back: {
                    PARTNER: "partner",
                    NAME_ORG1: "koinh",
                    BANKN: "bankn",
                    BANKL: "bankl",
                    SWIFT: "swift",
                }
            }
        }});
    columns.push({display: "BP账号名称", name: "koinh", width: 120, minwidth: 120, type: "string", align: "left",});
    columns.push({display: "BP银行账号", name: "bankn", width: 200, minwidth: 120, type: "string", align: "left",
        editor: {
            required: true, type: "select",
            data: {
                type: 'system',
                name: "getCusAndBanks",
                getParam: function (item) {
                    return {
                        ZEP_BPTYPE: item.zepBptype,
                        PARTNER:item.partner
                    }
                },
                back: {
                    BANKN: "bankn",
                    BANKL: "bankl",
                    SWIFT: "swift",
                }
            },
        }
    });
    columns.push({display: "BP联行号", name: "bankl", width: 200, minwidth: 120, type: "string", align: "left",});
    columns.push({display: "SWIFT/BIC", name: "swift", width: 120, minwidth: 120, type: "string", align: "left",});
     columns.push({display: "计划付款日期", name: "zepFpldate", width: 120, minwidth: 120, type: "string", align: "left",
        editor: {
            type: "date"
        }
    });
    columns.push({display: "成本中心", name: "kostl", width: 120, minwidth: 120, type: "string", align: "left",
        editor: {
            required: false, type: "select",
            data: {
                type: 'system',
                name: "dictionary",
                getParam: function (item) {
                    return {fieldName: "KOSTL"}
                },
                back: {
                    KOSTL: "kostl",
                    LTEXT: "ktext1"
                }
            },
        }});
    columns.push({display: "成本中心名称", name: "ktext1", width: 120, minwidth: 120, type: "string", align: "left",});
    columns.push({display: "内部订单", name: "aufnr", width: 120, minwidth: 120, type: "string", align: "left",
        editor: {
            required: false, type: "select",
            data: {
                type: 'system',
                name: "getCompanyOrders",
                getParam: function (item) {
                    return {
                        BUKRS: $("#bukrs").val()
                    }
                },
                back: {
                    AUFNR: "aufnr",
                    KTEXT: "ktext"
                }
            },
        }
    });
    columns.push({display: "内部订单描述", name: "ktext", width: 200, minwidth: 120, type: "string", align: "left",});
    var statusId = $("#statusId").val();
    if (statusId != 0){
        columns.push({display: "费用类型代码", name: "zepExtype", width: 120, minwidth: 120, type: "string", align: "left",
            editor: {
                required: false, type: "select",
                data: {
                    type: 'system',
                    name: "dictionary",
                    getParam: function (item) {
                        return {fieldName: "SPKZL"}
                    },
                    back: {
                        SPKZL: "zepExtype",
                        SPTXT: "zepExtypename",
                        SAKNR: "hkont",
                        TXT50_SKAT: "txt50"
                    }
                },
            }});
        columns.push({display: "费用类型名称", name: "zepExtypename", width: 120, minwidth: 120, type: "string", align: "left",});
        columns.push({display: "费用会计科目", name: "hkont", width: 120, minwidth: 120, type: "string", align: "left",});
        columns.push({display: "总账科目描述", name: "txt50", width: 120, minwidth: 120, type: "string", align: "left",});
        columns.push({display: "", name: "zyl05", width: 80, minwidth: 80, type: "string", align: "left", hide: true},);
        columns.push({
            display: "发票类型", name: "zyl05TextView", width: 120, minwidth: 120, type: "string", align: "left",
            editor: {
                type: 'dictionary',
                data: {name: 'zyl05'},
                textField: 'zyl05TextView',
                valueField: 'zyl05',
                required: false,
                render: function (item) {
                    return item.zyl05TextView;
                }
            },
        },);
        columns.push({display: "发票号码", name: "zyl06", width: 300, minwidth: 120, type: "string", align: "left",
            editor: {
                type: 'text',
                required: false,
            }});

        columns.push({display: "不含税金额", name: "netwr", width: 120, minwidth: 120, type: "money", align: "left",
            //等于含税金额减去税额
            render:function(item){
                return item.netwr = MathUtil.sub(item.kzwi1,item.kwetr);
            }
        });
        columns.push({display: "税码", name: "mwskzTextView", width: 120, minwidth: 120, type: "string", align: "left",
            editor: {
                type: 'dictionary',
                data: {name:'mwskz'},
                textField:'mwskzTextView',
                valueField:'mwskz',
                required: false,
                render: function (item) {
                    return item.mwskzTextView;
                }
            }});
        columns.push({display: "税额", name: "kwetr", width: 120, minwidth: 120, type: "money", align: "left",
            editor: {
                mask: 'nnnnnnnnn.nn',
                type: 'text'
            }});
    }
    columns.push({display: "币别", name: "waers", width: 120, minwidth: 120, type: "string", align: "left",
        editor: {
            type: 'text'
        }});
    columns.push({display: "汇率", name: "kursf", width: 120, minwidth: 120, type: "string", align: "left",
        editor: {
            mask: 'nnnnnnnnn.nn',
            type: 'text'
        }});

    columns.push({display: "含税金额", name: "kzwi1", width: 120, minwidth: 120, type: "money", align: "left",
        editor: {
            required: true,
            mask: 'nnnnnnnnn.nn',
            type: 'text'
        }});
    columns.push({display: "含税金额（本位币）", name: "kzwi11", width: 120, minwidth: 120, type: "money", align: "left",
        editor: {
            mask: 'nnnnnnnnn.nn',
            type: 'text'
        }});
    columns.push({display: "税额（本位币）", name: "kwetr1", width: 120, minwidth: 120, type: "money", align: "left",
        editor: {
            mask: 'nnnnnnnnn.nn',
            type: 'text'
        }});
    return columns;
}
var isAllData = true;
var zepPayFlag = false,changed = false;


//创建表格（参数、列、插入的节点、数据源）
function loadGrid(obj) {
    var toolbarOptions = null;
    var canEdit = false;//是否可编辑
    var canDelay = false;//是否加载。不加载是为了隐藏的表格如果是必填，提交会校验是否填写。
    var isApply = isApplyProcUnit();
    if (isApply){
        if (obj.node==="reimbursementApplierGrid"){
            canEdit = true;
        }else if (obj.node==="financialAuditGrid"
            //|| obj.node==="capitalPostGrid"
        ){
            //canDelay = true;
        }
    }
    var subProcUnitId = getSubProcUnitId();
    //财务审核
    if ("financeNode" === subProcUnitId){
        if (obj.node==="financialAuditGrid"){
            canEdit = true;
            var columns = obj.columns;
            columns.some(column => {
                if (//column.name == "rstgrName" ||
                    column.name == "zepPay"
                    || column.name == "zlschTextView"
                    //|| column.name == "zepBank"
                ){
                    column.editor.required = true;
                }
            })
            obj.columns = columns;
        }
    }

    //申请人审核
    if ("applyPerson" === subProcUnitId){
        if (obj.node==="reimbursementApplierGrid"){
            canEdit = true;
            var columns = obj.columns;
            columns.some(column => {
                if (column.name == "zepExtype" || column.name == "zyl06" || column.name == "zyl05TextView"){
                    column.editor.required = true;
                }
            })
            obj.columns = columns;
        }
    }

    //资金岗
    // if ("fundNode" === subProcUnitId && obj.node==="capitalPostGrid"){
    //     canEdit = true;
    // }
    if(obj.node==="reimbursementApplierGrid" && isApply) {//只有第一个表格含工具栏
        toolbarOptions = UICtrl.getDefaultToolbarOptions({
            addHandler: function () {
                tableArray.forEach((item) => {
                    UICtrl.addGridRow(item.gridManager, {zepItemno: getZepItemNo(),zepBptype:"K",zepBptypename:"供应商",waers: 'CNY', kursf: 1.00,zlsch:"T",
                        zlschTextView:"T-电汇"});
                });
            },
            deleteHandler: function () {
                // tableArray.forEach((item) => {
                //
                // });
                var _grid = UICtrl.getGridManager('#reimbursementApplierGrid');
                DataUtil.delSelectedRows({
                    action: 'sapCostReimbursement/deleteSapCostReimbursementDetails.ajax',
                    param: {},
                    gridManager: _grid,
                    idFieldName: 'reimbursementDetailId',
                    onSuccess: function () {
                        reloadGrid();
                    }
                });
                tableArray.forEach((item) => {
                    // if (item.node != "reimbursementApplierGrid"){
                    //     var data = item.gridManager.getSelectedRows();
                    //     $.each(data, function (i, o) {
                    //         item.gridManager.deleteRow(o);
                    //     });
                    // }
                    var data = item.gridManager.getSelectedRows();
                    $.each(data, function (i, o) {
                        item.gridManager.deleteRow(o);
                    });
                })

                // var _secondGrid = UICtrl.getGridManager('#financialAuditGrid');
                // if (_secondGrid != null){
                //     var secondRows = _secondGrid.currentData.Rows;
                //     totalFinancialAuditGrid(secondRows);
                // }
            },
            copyHandler: {
                id: 'copyHandler', text: '复制', img: 'fa-copy', click: function () {
                    tableArray.forEach((item) => {
                        //var row = DataUtil.getSelectedRow(item.gridManager);
                        var row = item.gridManager.getSelectedRow();
                        if (!row) {
                            Public.tip("请勾选一条数据");
                            return;
                        }
                        var newRow = JSON.parse(JSON.stringify(row));
                        newRow.zepItemno = getZepItemNo();
                        newRow.reimbursementDetailId = null;
                        newRow.zepPdamount1 = null;
                        newRow.zepPdtax1 = null;
                        newRow.zepPtdamount1 = null;
                        newRow.zepPdamount = null;
                        newRow.zepPdtax = null;
                        newRow.zepPtdamount = null;
                        UICtrl.addGridRow(item.gridManager, newRow);
                    });
                }
            }
        });
    }
    obj.gridManager = UICtrl.grid("#" + obj.node, {
        columns: obj.columns,
        dataAction: "local",
        data: obj.data,
        parms: obj.parms,
        pageSize: 20,
        toolbar: toolbarOptions,
        usePager: false,
        enabledEdit: canEdit,
        delayLoad: canDelay,
        // width: "100%",
        // height: 300,
        heightDiff: -8,
        checkbox: true,
        fixedCellHeight: true,
        selectRowButtonOnly: true,
        onBeforeCheckRow: function (checked, data) {
            //同时选定或取消所有表格中的对应行
            tableArray.forEach((item) => {
                let rows = item.gridManager.rows;
                let row = {};
                rows.forEach((temp) => {
                    if (temp.zepItemno === data.zepItemno) {
                        row = temp;
                    }
                })
                checked ? item.gridManager.select(row) : item.gridManager.unselect(row);
            })
            return false;//阻止默认事件、防止某个表格的对应行被多次选中
        },
        onBeforeCheckAllRow: function (a, b) {
            return false;//阻止默认事件
        },
        onAfterEdit:function (item) {
            if(item.column.name == "waers"
                || item.column.name == "kursf"
                || item.column.name == "kzwi1"
                || item.column.name == "mwskzTextView"
                || item.column.name == "kwetr"){
                //税额计算
                //等于含税金额/(1+税码对应的税率）*税码对应税率，可手工修改
                var value = MathUtil.div(item.record.kzwi1, MathUtil.add(1 , item.record.mwskzTextView));
                var kwetr = MathUtil.mul(value, item.record.mwskzTextView).toFixed(2);

                //含税金额（本位币）计算
                //"公司代码等于1000币别等于CNY时，默认等于含税金额；
                // 公司代码等于1000币别不等于CNY时，等于含税金额*币别对应的汇率"
                var money = 0;
                if (item.record.waers === "CNY"){
                    money=item.record.kzwi1;
                }else {
                    money = MathUtil.mul(item.record.kzwi1,item.record.kursf)
                }
                //税额（本位币）计算
                //等于（含税金额-本位币）/(1+税码对应的税率）*税码对应税率，可手工修改
                var kwetr1 = MathUtil.div(money,MathUtil.add(1,item.record.mwskzTextView)).mul(item.record.mwskzTextView).toFixed(2)

                obj.gridManager.updateRow(item.record, {kwetr: kwetr,kzwi11: money,kwetr1: kwetr1});
                totalGrid();
                changeFinancialAuditGridData();
            }
            var check = true;
            if (item.column.name == "zepPtdamount1"){
                var value = item.value;
                var zepItemno = item.record.zepItemno;
                var _grid = UICtrl.getGridManager('#reimbursementApplierGrid');
                var _secondGrid = UICtrl.getGridManager('#financialAuditGrid');
                if (_grid != null){
                    var datas = _grid.currentData.Rows;
                    if (datas.length > 0){
                        $.each(datas, function (i, data) {
                            if (data.zepItemno == zepItemno && (MathUtil.compare(value,data.kzwi1) > 0)){
                                Public.tip("含税金额（审批）不能大于含税金额")
                                check = false;
                                $.each(_secondGrid.currentData.Rows, function (i, row) {
                                    if (data.zepItemno == row.zepItemno){
                                        _secondGrid.updateRow(row,{
                                            zepPtdamount1:data.kzwi1,
                                        })
                                    }
                                })
                            }
                        });
                    }
                }
            }
            if(item.column.name == "zepPdamount1"
                || item.column.name == "zepPdtax1"
                || item.column.name == "zepPtdamount1"
                || item.column.name == "zepPdamount"
                || item.column.name == "zepPdtax"
                || item.column.name == "zepPtdamount"
            ){
                var _secondGrid = UICtrl.getGridManager('#financialAuditGrid');
                if (_secondGrid != null){
                    var secondRows = _secondGrid.currentData.Rows;
                    //先计算值
                    var _grid = UICtrl.getGridManager('#reimbursementApplierGrid');
                    if (_grid != null){
                        var datas = _grid.currentData.Rows;
                        if (datas.length > 0 && secondRows.length > 0){
                            $.each(datas, function (i, data) {
                                $.each(secondRows, function (i, row) {
                                    if (data.zepItemno === row.zepItemno ){
                                        var mwskzTextView = data.mwskzTextView;//税率
                                        var waers = data.waers;//币别
                                        var kursf = data.kursf;//汇率
                                        //编辑含税金额审批，税额审批、不含税金额审批变化。
                                        if (item.column.name == "zepPtdamount1" && check){
                                            //税额计算
                                            //等于含税金额/(1+税码对应的税率）*税码对应税率，可手工修改
                                            var value = MathUtil.div(item.record.zepPtdamount1, MathUtil.add(1 , mwskzTextView));
                                            var zepPdtax1 = MathUtil.mul(value, mwskzTextView).toFixed(2);

                                            //不含税金额=含税金额-税额
                                            var zepPdamount1 = MathUtil.sub(item.record.zepPtdamount1,zepPdtax1);

                                            obj.gridManager.updateRow(item.record, {
                                                zepPdtax1: zepPdtax1,//税额（审批）
                                                zepPdamount1: zepPdamount1,//不含税金额（审批）
                                                zepPdamount: MathUtil.mul(zepPdamount1,kursf),//不含税金额（审批-本位币）
                                                zepPdtax: MathUtil.mul(zepPdtax1,kursf),//税额（审批-本位币）
                                                zepPtdamount: MathUtil.add(MathUtil.mul(zepPdamount1,kursf),MathUtil.mul(zepPdtax1,kursf))//含税金额（审批-本位币）
                                            });
                                        }
                                        //编辑税额，含税金额审批=不含税金额审批-修改后的税额
                                        if (item.column.name == "zepPdtax1"){
                                            //不含税金额=含税金额-税额
                                            var zepPdamount1 = MathUtil.sub(item.record.zepPtdamount1,item.record.zepPdtax1);
                                            obj.gridManager.updateRow(item.record, {
                                                zepPdamount1: zepPdamount1,//不含税金额（审批）
                                                zepPdtax: MathUtil.mul(item.record.zepPdtax1,kursf),//税额（审批-本位币）
                                                zepPdamount: MathUtil.sub(item.record.zepPtdamount,MathUtil.mul(item.record.zepPdtax1,kursf)),//不含税金额（审批-本位币）
                                            });
                                        }
                                    }
                                });
                            });
                        }
                    }
                    if (check){
                        totalFinancialAuditGrid(secondRows);
                    }
                }
            }
            //是否付款选择“N”，“原因代码”和“银企直连标志”非必填
            if (item.column.name == "zepPay" && obj.node == "financialAuditGrid"){
                if (item.value == "Y"){
                    zepPayFlag = true;
                }
                if (item.value == "N"){
                    zepPayFlag = false;
                }
                var columns = obj.columns;
                columns.some(column => {
                    if (column.name == "rstgrName" ||
                        column.name == "zepBank" ){
                        column.editor.required = zepPayFlag;
                    }
                })
                obj.gridManager.set('columns', columns);
                //UICtrl.setGridColumns(obj.gridManager,columns);
            }
            //发票类型无的时候，发票号码默认无
            if (item.column.name == "zyl05TextView"){
                var value = item.record.zyl05;
                var text = "";
                if (value == 0){
                    text = "无";
                }
                var _grid = UICtrl.getGridManager('#reimbursementApplierGrid');
                var zepItemno = item.record.zepItemno;
                $.each(_grid.currentData.Rows, function (i, row) {
                    if (zepItemno == row.zepItemno){
                        _grid.updateRow(row,{
                            zyl06:text,
                        })
                    }
                })
            }
            //费用报销单据发票号码栏，校验发票号码是否重复，重复(状态是已完成，申请，审批中)则提示该发票已经提交过，发票无效
            if (item.column.name == "zyl06" && !isNaN(item.record.zyl06)){
                Public.ajax(web_app.name+"/sapCostReimbursement/checkzyl06.ajax",{zyl06:item.record.zyl06},function (data) {
                    if (data > 0){
                        Public.tip("该发票 '"+item.value+"' 已经提交过，发票无效");
                        var _grid = UICtrl.getGridManager('#reimbursementApplierGrid');
                        var zepItemno = item.record.zepItemno;
                        $.each(_grid.currentData.Rows, function (i, row) {
                            if (zepItemno == row.zepItemno){
                                _grid.updateRow(row,{
                                    zyl06:"",
                                })
                            }
                        })
                    }
                })
            }
            return item;
        },
        onAfterShowData:function (){
            if ("financeNode" === subProcUnitId){
                initFinancialAuditGridData();
            }
            if ("fundNode" === subProcUnitId){
                //如果财务审核是无需付款，付款银行账号非必填
                var _secondGrid = UICtrl.getGridManager('#financialAuditGrid');
                if (_secondGrid!=null){
                    var checked7 = false;
                    $.each(_secondGrid.currentData.Rows, function (i, row) {
                        if (row.zepPay == "Y"){
                            checked7 = true
                        }
                    });
                    if (checked7){
                        UICtrl.setElRequiredFlag("#bankn1",true)
                    }
                }
            }
            totalGrid();
        }
    });
    UICtrl.setSearchAreaToggle(obj.gridManager);

}


$(document).ready(function () {
    initialize();
    bindQueryEvent();
    nodeController();
});


function initialize() {
    $('#fileList').fileList();

    //获取数据源初始化表格
    Public.ajax(web_app.name + '/sapCostReimbursement/slicedSapCostReimbursementDetailList.ajax', {reimbursementBaseInfoId: getId()}, function (data) {
        //根据定义列拆除实体对象，封装成每个table对应的数据集
        tableArray.forEach(obj => {
            obj.data = {
                Rows: data.Rows.map(item => {
                    let row = {};
                    obj.columns.forEach(col => {
                        if (item.hasOwnProperty(col.name)) {
                            row[col.name] = item[col.name];
                        }
                    });
                    return row;
                })
            };
        });
        useArrayTable(loadGrid);
    })
}

function bindQueryEvent() {
    $('#bukrs').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {fieldName: "BUKRS"}
        },
        onChange: function (value, data) {
            $('#bukrs').val(data.BUKRS);
            $('#butxt').val(data.BUTXT);
        }
    });

    $('#employeeLoanBillCode').searchbox({
        type: "costReimbursement", name: "employeeLoanBillCode",
        getParam: function (item) {
            return {
                personMemberId: $("#personMemberId").val()
            }
        },
        onChange: function (value, data) {
            $('#employeeLoanBillCode').val(data.billCode);
        }
    });

    $('#bankn1').searchbox({
        type: "system", name: "getCompanyAndBankInfos",
        getParam: function (item) {
            return {BUKRS: $("#bukrs").val()}
        },
        onChange: function (value, data) {
            $('#bankn1').val(data.BANKN1);
            $('#zt012kText1').val(data.TEXT1);
        }
    });
}

/**
 * 流程引擎回调设置打样的id
 * @param value 打样申请的id
 */
function setId(id) {
    $("#id").val(id);
    $('#fileList').fileList({bizId: id});
}

/**
 * 流程引擎获取打样申请id的回掉方法。
 * @return
 */
function getId() {
    return $("#id").val() || "";
}

function getExtendedData(processAction) {

    //回退、打回、转交时，不需要验证必填项是否已经填写；
    if (processAction == ProcessAction.BACK
        || processAction == ProcessAction.REPLENISH
        || processAction == ProcessAction.TRANSMIT || "2" == getHandleResult()) {
        isAllData = false
        //不验证
        $('#submitForm').attr('check', false);
    }
    let resultArray = useArrayTable(getTableDataAll);

    //根据zepItemno将各列表属性合并为一个完整实体
    const result = resultArray[0].map((obj1) => {
        const mergedObj = {...obj1};
        for (let i = 1; i < resultArray.length; i++) {
            const currentArr = resultArray[i];
            const currentObj = currentArr.find((obj) => obj.zepItemno === obj1.zepItemno);
            if (currentObj) {
                Object.assign(mergedObj, currentObj);
            }
        }
        return mergedObj;
    });
    var _reimbursementGrid = UICtrl.getGridManager('#reimbursementApplierGrid');
    var reimbursementDatas = DataUtil.getGridData({
        gridManager: _reimbursementGrid,
        isAllData: isAllData,
        onCheck: function () {
            return true;
        }
    });
    if (!reimbursementDatas) {
        return false;
    }
    var nos = [];
    for (var i = 0; i < reimbursementDatas.length; i++) {
        var item = reimbursementDatas[i];
        if (nos.length>0 && nos.includes(item.zepItemno) ) {
            Public.tip("EP流程子序号不能重复")
            return false;
        }else {
            nos.push(item.zepItemno);
        }
    }
    var subProcUnitId = getSubProcUnitId();
    //如果没有收到SAP消息回执，不能提交归档
    if ("file" === subProcUnitId){
        var _financialGrid = UICtrl.getGridManager('#financialAuditGrid');
        var financialDatas = DataUtil.getGridData({
            gridManager: _financialGrid,
            isAllData: isAllData,
            onCheck: function () {
                return true;
            }
        });
        if (!financialDatas) {
            return false;
        }
        var checked7 = false
        var num = 0;
        $.each(financialDatas, function (i, o) {
            if (o.zepPay == "Y"){
                checked7 = true
            }
        });
        var _grid = UICtrl.getGridManager('#paymentAccomplish_sapReturnGrid');
        var datas = DataUtil.getGridData({
            gridManager: _grid,
            isAllData: isAllData,
            onCheck: function () {
                return true;
            }
        });
        if (!datas) {
            return false;
        }
        var checked6 = false
        if (checked7){
            $.each(datas, function (i, o) {
                if (Public.isBlank(o.belnr1) || Public.isBlank(o.gjahr1)){
                    checked6 = true;
                }
            })
        }
        if (checked6){
            Public.tip("请收到'付款完成、sap回执'消息后才归档");
            return false;
        }
    }
    let extendedData = {};
    extendedData.CRDetail = Public.encodeJSONURI(result);
    return extendedData;

}

//提交前校验
function checkConstraints() {
    //判断成本中心、内部订单必输1个，可以同时都输入
    var _grid = UICtrl.getGridManager('#reimbursementApplierGrid');
    var datas = DataUtil.getGridData({
        gridManager: _grid,
        isAllData: isAllData,
        onCheck: function () {
            return true;
        }
    });
    if (!datas) {
        return false;
    }
    var checked = false
    $.each(datas, function (i, o) {
        if (Public.isBlank(o.kostl) && Public.isBlank(o.aufnr)){
            checked = true
        }
    });
    if (checked) {
        Public.tip("成本中心、内部订单必输1个，可以同时都输入")
        return false
    }
    //原因代码、是否付款、直联付款标识必输，且如果为多行的话，这三个字段的值必须相同，不相同报错提示，不允许提交
    var subProcUnitId = getSubProcUnitId();
    //财务审核
    if ("financeNode" === subProcUnitId){
        var _grid = UICtrl.getGridManager('#financialAuditGrid');
        var datas = DataUtil.getGridData({
            gridManager: _grid,
            isAllData: true,
            onCheck: function () {
                return true;
            }
        });
        if (!datas) {
            return false;
        }
        var checked1 = false
        var checked2 = false
        var checked3 = false
        $.each(datas, function (i, o) {
            if (o.rstgrName != datas[0].rstgrName ){
                checked1 = true
            }
            if (o.zepPay != datas[0].zepPay ){
                checked2 = true
            }
            if (o.zepBank != datas[0].zepBank ){
                checked3 = true
            }
        });
        if (checked1) {
            Public.tip("原因代码不一致")
            return false
        }
        if (checked2) {
            Public.tip("是否付款不一致")
            return false
        }
        if (checked3) {
            Public.tip("直联付款标识不一致")
            return false
        }
    }

    //申请人审批阶段，SAP付款回执必须有值
    if ("applyPerson" == subProcUnitId){
        var _grid = UICtrl.getGridManager('#paymentAccomplish_sapReturnGrid');
        var datas = DataUtil.getGridData({
            gridManager: _grid,
            isAllData: isAllData,
            onCheck: function () {
                return true;
            }
        });
        var checked4 = false
        $.each(datas, function (i, o) {
            if (Public.isBlank(o.belnr1)){
                checked4 = true
            }
        });
        if (checked4) {
            Public.tip("SAP付款回执未完成，请稍后再试！")
            return false
        }
    }

    return true;
}

function getTableDataAll(obj) {
    let result = DataUtil.getGridData({
        gridManager: obj.gridManager,
        isAllData: isAllData
    });
    return result;
}

//调用数组
function useArrayTable(func, ...data) {
    const results = tableArray.map((item) => {
        return func(item, ...data);
    });
    return results;
}

//获取最新子序号（维护实体的标识）
function getZepItemNo() {
    let result = getTableDataAll(tableArray[tableArray.length - 1]);
    let zepItemNo = "001";
    if (result.length > 0) {
        //获取上一个节点的子序值
        let wornNo = parseInt(result[result.length - 1]["zepItemno"], 10);
        zepItemNo = ("00" + (wornNo + 1)).slice(-3);
    }
    return zepItemNo;
}

//UICtrl中校验是否允许编辑
function businessJudgmentUnit() {
    var isApply = isApplyProcUnit();
    if (isApply) {
        $("#approvalMoney").hide();
        //$("#financialAudit").hide();
        $("#financialAudit_sapReturn").hide();
        $("#capitalPost").hide();
        $("#paymentAccomplish_sapReturn").hide();
        return true;
    }else {
        UICtrl.setDisable($("#submitForm"));
    }
    //资金岗
    if ("fundNode" === getSubProcUnitId()){
        UICtrl.enable("#bankn1");
        UICtrl.enable("#zepTxt1");
        //UICtrl.setElRequiredFlag("#bankn1",true)
    }
    return true;
}


function nodeController(){
    var subProcUnitId = getSubProcUnitId();
    //财务审核
    if ("financeNode" === subProcUnitId){
        $("#financialAudit_sapReturn").hide();
        $("#capitalPost").hide();
        $("#paymentAccomplish_sapReturn").hide();
    }

    //资金岗
    if ("fundNode" === subProcUnitId){
        $("#financialAudit_sapReturn").hide();
        $("#paymentAccomplish_sapReturn").hide();
    }
}

function totalGrid(money) {
    var _grid = UICtrl.getGridManager('#reimbursementApplierGrid');
    if (_grid != null){
        var data = _grid.currentData.Rows,
            zepFtamount1 = 0,//申请总金额
            zepFtamount = 0,//申请总金额（本位币）
            zepFttax = 0,//申请总税额（本位币）
            zepFttax1 = 0;//申请总税额
        var _kzwi1 = 0;
        var _kzwi11 = 0;
        var _kwetr1 = 0;
        var _kwetr = 0;
        $.each(data, function (i, o) {
            _kzwi1 = o['kzwi1'] + '';
            _kzwi11 = o['kzwi11'] + '';
            _kwetr1 = o['kwetr1'] + '';
            _kwetr = o['kwetr'] + '';
            zepFtamount1 = MathUtil.add(zepFtamount1, _kzwi1);
            zepFtamount = MathUtil.add(zepFtamount, _kzwi11);
            zepFttax = MathUtil.add(zepFttax, _kwetr1);
            zepFttax1 = MathUtil.add(zepFttax1, _kwetr);
            $('#zepFtamount1').val(zepFtamount1);
            $('#zepFtamount').val(zepFtamount);
            $('#zepFttax').val(zepFttax);
            $('#zepFttax1').val(zepFttax1);
        });
    }
}

function initFinancialAuditGridData(){
    var _grid = UICtrl.getGridManager('#reimbursementApplierGrid');
    var _secondGrid = UICtrl.getGridManager('#financialAuditGrid');
    if (_grid != null && _secondGrid != null){
        var datas = _grid.currentData.Rows;
        if (datas.length > 0 && _secondGrid.currentData != null){
            var secondRows = _secondGrid.currentData.Rows;
            $.each(datas, function (i, data) {
                $.each(secondRows, function (i, row) {
                    if (data.zepItemno === row.zepItemno && (row.zepPdamount1===0 || Public.isBlank(row.zepPdamount1))){
                        _secondGrid.updateRow(row,{
                            zepPdamount1:data.netwr,
                            zepPdtax1:data.kwetr,
                            zepPtdamount1:data.kzwi1,
                            zepPdamount:data.netwr1,
                            zepPdtax:data.kwetr1,
                            zepPtdamount:data.kzwi11
                        })
                    }
                });
            });
            totalFinancialAuditGrid(secondRows);
        }
    }
}

function changeFinancialAuditGridData(){
    var _grid = UICtrl.getGridManager('#reimbursementApplierGrid');
    var _secondGrid = UICtrl.getGridManager('#financialAuditGrid');
    if (_grid != null && _secondGrid != null){
        var datas = _grid.currentData.Rows;
        if (datas.length > 0 && _secondGrid.currentData != null){
            var secondRows = _secondGrid.currentData.Rows;
            $.each(datas, function (i, data) {
                $.each(secondRows, function (i, row) {
                    if (data.zepItemno === row.zepItemno){
                        _secondGrid.updateRow(row,{
                            zepPdamount1:data.netwr,
                            zepPdtax1:data.kwetr,
                            zepPtdamount1:data.kzwi1,
                            zepPdamount:MathUtil.mul(data.netwr,data.kursf),
                            zepPdtax:data.kwetr1,
                            zepPtdamount:data.kzwi11
                        })
                    }
                });
            });
            totalFinancialAuditGrid(secondRows);
        }
    }
}

function totalFinancialAuditGrid(data){
    var zepPtamount = 0,//审批总金额（本位币）
        zepPttax = 0,//审批总税额（本位币）
        zepPtamount1 = 0,//zepPtamount1
        zepPttax1 = 0;//审批总税额
    $.each(data, function (i, o) {
        var _zepPtdamount = o['zepPtdamount'] + '';
        var _zepPdtax = o['zepPdtax'] + '';
        var _zepPtdamount1 = o['zepPtdamount1'] + '';
        var _zepPdtax1 = o['zepPdtax1'] + '';
        zepPtamount = MathUtil.add(zepPtamount, _zepPtdamount);
        zepPttax = MathUtil.add(zepPttax, _zepPdtax);
        zepPtamount1 = MathUtil.add(zepPtamount1, _zepPtdamount1);
        zepPttax1 = MathUtil.add(zepPttax1, _zepPdtax1);
        $('#zepPtamount').val(zepPtamount);
        $('#zepPttax').val(zepPttax);
        $('#zepPtamount1').val(zepPtamount1);
        $('#zepPttax1').val(zepPttax1);
    });
}

function reloadGrid(){
    //获取数据源初始化表格
    Public.ajax(web_app.name + '/sapCostReimbursement/slicedSapCostReimbursementDetailList.ajax', {reimbursementBaseInfoId: getId()}, function (data) {
        //根据定义列拆除实体对象，封装成每个table对应的数据集
        tableArray.forEach(obj => {
            obj.data = {
                Rows: data.Rows.map(item => {
                    let row = {};
                    obj.columns.forEach(col => {
                        if (item.hasOwnProperty(col.name)) {
                            row[col.name] = item[col.name];
                        }
                    });
                    return row;
                })
            };
            var gridManager = UICtrl.getGridManager("#"+obj.node);
            gridManager.setData(obj.data);
            Public.successTip("数据操作成功")
        });
    })
}