'use strict';
var el = {
    originalRows: [],
    bodyHeight: document.documentElement.clientHeight
}
let bankDate;
let selfData = {
    toolbar: []
};
var editIndex = 0;
$(function () {

    initDict('pay_mode,pay_type,contractCategory,payment_stage,pay_contract_type,contractPayCategory,currency,contract_pay_boot_item');

    initColumns();

    loadGrid();

});


function initColumns() {
//初始化税率下拉框
    $('#taxCode').combobox({
        valueField: 'taxCode',
        textField: 'taxName',
        url: g.ctx + 'pc/sys/tax/rest/listAll',
        editable: false,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
        panelWidth: 300,
        value:'J1',
        tipPosition: 'bottom',
    });

    $('#payOrgName').textbox({
        buttonText: '选择',
        iconCls: 'icon-man',
        iconAlign: 'left',
        onClickButton: function () {
            layer.open({
                title: "付款单位选择",
                type: 2,
                area: ['600px', '550px'],
                content: '/pc/contract/manage/page/choseSupplier?type=1',
                btn: ['选择', '关闭'],
                yes: function (index, layero) {
                    var body = layer.getChildFrame('body', index);
                    var iframeWin = window[layero.find('iframe')[0]['name']];
                    var name = $(layero).find("iframe")[0].contentWindow.document.getElementById("name").value;
                    var code = $(layero).find("iframe")[0].contentWindow.document.getElementById("code").value;
                    if (name != undefined && code != '') {
                        $('#payOrgName').textbox('setValue', name);
                        $('#payOrgCode').val(code);
                        layer.close(index);
                    } else {
                        layer.alert("未选择", {icon: 2})
                    }
                },
            });
        }
    });


    $('#payeeName').textbox({
        buttonText: '选择',
        iconCls: 'icon-man',
        iconAlign: 'left',
        onClickButton: function () {
            layer.open({
                title: "收款单位选择",
                type: 2,
                area: ['650px', '550px'],
                content: '/pc/contract/manage/page/choseSupplier?type=2',
                btn: ['选择', '关闭'],
                yes: function (index, layero) {
                    var body = layer.getChildFrame('body', index);
                    var iframeWin = window[layero.find('iframe')[0]['name']];
                    var name = $(layero).find("iframe")[0].contentWindow.document.getElementById("name").value;
                    var code = $(layero).find("iframe")[0].contentWindow.document.getElementById("code").value;
                    if (name != undefined && code != '') {
                        $('#payeeName').textbox('setValue', name);
                        $('#payeeCode').val(code);
                        //查询供应商货币信息
                        $.ajax({
                            type: 'POST',
                            url: g.ctx + 'pc/supplier/purchaseCategory/rest/findCurryCode',
                            async: false,
                            data: {"supplierCode": code},
                            success: function (res) {
                              if(res !=''){
                                  $('#payCurrency').combobox('setValue', res);
                              }
                            }
                        });

                        //查询供应商银行信息
                        $.ajax({
                            type: 'POST',
                            url: g.ctx + 'pc/contract/pay/rest/supplierBankDate',
                            async: false,
                            data: {"contractSupplierCode": code},
                            success: function (res) {
                                bankDate = res;
                                if (res.length > 0) {
                                    if (res.length == 1) {
                                        $("#bankName").textbox('setValue', res[0].openingBankName);
                                        $("#bankAccount").textbox('setValue', res[0].bankAccount);
                                        $("#bankCode").textbox('setValue', res[0].bankCode);
                                        $("#bankSwiftCode").textbox('setValue', res[0].bankInterCode);
                                    } else {
                                        $("#bankAccount").combobox({
                                            valueField: 'bankAccount',
                                            textField: 'bankAccount',
                                            data: bankDate,
                                            editable: false,
                                            panelHeight: 'auto',
                                            onLoadSuccess: function () {
                                                $("#bankAccount").combobox('select', bankDate[0].bankAccount);
                                                $("#bankName").textbox('setValue', bankDate[0].openingBankName);
                                                $("#bankCode").textbox('setValue', bankDate[0].bankCode);
                                                $("#bankSwiftCode").textbox('setValue', bankDate[0].bankInterCode);
                                            }
                                        });
                                    }
                                } else {
                                    $("#bankName").textbox('setValue','');
                                    $("#bankAccount").textbox('setValue', '');
                                    $("#bankCode").textbox('setValue', '');
                                    $("#bankSwiftCode").textbox('setValue', '');
                                }
                            }
                        });
                        layer.close(index);
                    } else {
                        layer.alert("未选择", {icon: 2})
                    }
                },
            });
        }
    });
    $("#bankAccount").combobox({
        valueField: 'bankAccount',
        textField: 'bankAccount',
        data: bankDate,
        editable: false,
        panelHeight: 'auto',
        onChange: function (d) {
            bankDate.forEach(function (v, n) {
                if (v.bankAccount == d) {
                    $("#bankName").textbox('setValue', v.openingBankName);
                    $("#bankCode").textbox('setValue', v.bankCode);
                    $("#bankSwiftCode").textbox('setValue', v.bankInterCode);
                }
            });
        }
    });


    $('#createTime').datebox({
        value: moment().format('YYYY-MM-DD'),
    });

    $('#payeeAmount').numberbox({
        min: 0,
        precision: 4
    });

    $('#paymentProgress').numberbox({
        min: 0,
        precision: 2
    });


    $("#settlementMethod").combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: getDictList('pay_mode')
    });
    $("#payCurrency").combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: getDictList('currency'),
       /* onLoadSuccess: function () {
            var id = $("#id").val();
            var data = $('#payCurrency').combobox('getData');
            if (data.length > 0) {
                if (id == '') {
                    $("#payCurrency").combobox('select', 'CNY');
                }
            }
        },*/
    });
    $("#payType").combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: getDictList('pay_type')
    });

    $("#sapPayType").combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        value:'是',
        data: [
            {"code": "是", "name": "是"},
            {"code": "否", "name": "否"}
        ]
    });

    $("#isBalanceDue").combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: [
            {"code": "是", "name": "是"},
            {"code": "否", "name": "否"}
        ]
    });


    $("#applicationType").combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: getDictList('pay_contract_type')
    });

    $("#totalAmount").textbox({
        onChange: function (newValue, oldValue) {
            $('#amountCapital').textbox('setValue', number_chinese(newValue));
        }
    });


    $('#belongDeptName').combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        value:'申请部门',
        editable: false,
        data: [
            {"code": "申请部门", "name": "申请部门"},
            {"code": "需要分摊", "name": "需要分摊"}
        ]

        // buttonText:'选择',
        // iconCls:'icon-man',
        // iconAlign:'left',
        // onClickButton:function () {
        //     var userOrgyDialog = openDialog('userOrgyDialog', g.ctx + 'pc/sys/org/orgTree', {
        //         title: "组织部门",
        //         width: '400px',
        //         height: '700px',
        //         cache: false,
        //         modal: true,
        //         border: false,
        //         draggable: false,
        //         shadow: false,
        //         onClose: function () {
        //             userOrgyDialog.dialog('destroy');
        //         },
        //         buttons: [
        //             {
        //                 text: itablei8n.save,
        //                 handler: function () {
        //                     topWin.frames['userOrgyDialog'].confirm(function (cbox) {
        //                         $("#belongDeptCode").val(cbox.code);
        //                         $('#belongDeptName').textbox('setValue', cbox.name);
        //                         userOrgyDialog.dialog('close');
        //                     });
        //                 }
        //             },
        //             {
        //                 text: itablei8n.close,
        //                 handler: function () {
        //                     userOrgyDialog.dialog('close');
        //                 }
        //             }
        //         ]
        //     });
        // }
    });


    $("#accepProcess").textbox({
        buttonText: '选择',
        iconCls: 'icon-search',
        iconAlign: 'left',
        onClickButton: function () {
            topWin.layer.open({
                title: "OA流程选择",
                type: 2,
                area: ['70%', '70%'],
                content: '/pc/contract/pay/page/choseOaProcess?flag=0',
                btn: ['选择', '关闭'],
                yes: function (index, layero) {
                    var iframeWin = topWin.window[layero.find('iframe')[0]['name']];
                    iframeWin.selectRow(function (code) {
                        if (code != '') {
                            $('#accepProcess').textbox('setValue', code);
                            topWin.layer.close(index);
                        } else {
                            topWin.layer.alert("未选择", {icon: 2})
                        }
                    });
                },
            });
        }
    });


    $("#process").textbox({
        buttonText: '选择',
        iconCls: 'icon-search',
        iconAlign: 'left',
        onClickButton: function () {
            topWin.layer.open({
                title: "OA流程选择",
                type: 2,
                area: ['70%', '70%'],
                content: '/pc/contract/pay/page/choseOaProcess?flag=1',
                btn: ['选择', '关闭'],
                yes: function (index, layero) {
                    var iframeWin = topWin.window[layero.find('iframe')[0]['name']];
                    iframeWin.selectRow(function (code) {
                        console.log(1, code)
                        if (code != '') {
                            $('#process').textbox('setValue', code);
                            topWin.layer.close(index);
                        } else {
                            topWin.layer.alert("未选择", {icon: 2})
                        }
                    });
                },
            });
        }
    });


    $("#accepProcess").textbox({
        buttonText: '选择',
        iconCls: 'icon-search',
        iconAlign: 'left',
        onClickButton: function () {
            var ProcessType = "3";
            topWin.layer.open({
                title: "验收流程选择",
                type: 2,
                area: ['70%', '70%'],
                content: '/pc/contract/pay/page/choseOaProcess?flag=1' + '&ProcessType=' + ProcessType,
                btn: ['选择', '关闭'],
                yes: function (index, layero) {
                    var iframeWin = topWin.window[layero.find('iframe')[0]['name']];
                    iframeWin.selectRows(function (row) {
                        let r = [];
                        // let accepProcessData = [];
                        // accepProcessData = JSON.parse(accepProcessData)
                        accepProcessData = [];
                        for(var i=0;i<row.length;i++){
                            r.push(row[i].ProcessId);
                            accepProcessData.push({
                                "docId":row[i].ProcessId,
                                "subject":row[i].ProcessTitle
                            })
                        }
                        $('#accepProcess').textbox('setValue', r.join(","));
                        // $('#accepProcessData').val(JSON.stringify(accepProcessData));
                        accepProcessData = JSON.stringify(accepProcessData);
                        topWin.layer.close(index);
                    });
                },
            });
        }
    });

    var check = $("#check").val();
       if(check==2){//编辑
           selfData.toolbar =  [
               {
                   text: '删除',
                   id: 'btn_del',
                   iconCls: 'icon-remove',
                   handler: function (d) {
                       delOrderDetail();
                   }
               },
           ];
       }else if(check==1){//新增
           selfData.toolbar =  [
               {
                   text: '获取订单明细',
                   id: 'btn_add',
                   iconCls: 'icon-add',
                   handler: function () {
                       var startTime = $("#startTime").datebox('getValue'), endTime = $("#endTime").datebox('getValue');
                       addOrderDetail(startTime, endTime);
                   }
               },
               {
                   text: '删除',
                   id: 'btn_del',
                   iconCls: 'icon-remove',
                   handler: function (d) {
                       delOrderDetail();
                   }
               },
           ];
       }else{//查看
           selfData.toolbar =  [];
       }
}


function loadGrid() {

    $("#table_order").edatagrid({
        iconCls: 'icon-list',
        url: '/pc/mall/shoppingPay/rest/detailOrderLists?id=&payId=' + $("#id").val(),
        height: 400,
        fitColumns: true,
        singleSelect: false,
        pagination: true,
        loadMsg: "数据加载中......",
        rownumbers: true,
        remoteSort: true,
        nowrap: true,
        striped: true,
        page: 1,
        pageSize: 10,
        /*frozenColumns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                }
            ]
        ],*/
        columns: [[
            {field: 'cartInfoId', title: 'cartInfoId', hidden: true,width: '80'},
            {field: 'cartCode', title: '订单编码', width: '120',sortable:true},
            {field: 'skuCode', title: '商品编码', hidden: true,width: '80'},
            {field: 'skuName', title: '商品名称', width: '140'},
            {field: 'unitCost', title: '单价', width: '80',sortable:true},
            {field: 'qty', title: '商品数量', width: '80',sortable:true},
            {field: 'unit', title: '单位', width: '120'},
            {field: 'receiptNum', title: '收货数量', width: '80',sortable:true},
            {field: 'totalAmount', title: '收货金额', width: '100',sortable:true},
            // {field: 'returnQuatity', title: '退货数量', width: '80',sortable:true},
            // {field: 'refundAmount', title: '退货金额', width: '80',sortable:true},
            {field: 'actualReceivedQuantity', title: '实际收货数量', width: '80',sortable:true,editor: {
                    type: 'numberbox', options: {required: false,  precision: 2}
                },},
            {field: 'actualTotalAmount', title: '实际付款总金额(元)', width: '80',sortable:true,editor: {
                    type: 'numberbox', options: {required: false,  precision: 2}
                },},

            {
                field: 'payCategory', title: '报销类别<button type="button" onclick="copy(\'payCategory\')" class="easyui-linkbutton">复制</button>', width: '220', editor: {
                    type: 'combobox', options: {
                        required: true,
                        valueField: "code",
                        textField: "codeWithDesc",
                        data: getDictList('contractPayCategory'),
                        editable: true,
                        panelHeight: '150'
                    }
                },
                formatter: function (value) {
                    return getDicName('contractPayCategory', value)
                }
            },
            {
                field: 'serviceDesc', title: '业务描述', width: '200', editor: {
                    type: 'textbox', options: {required: true}
                },
                formatter: function (value,row) {
                    if(value=='' || value==null){
                        return row.skuName ;
                    }
                    return value;
                }
            },
            {field: 'requireName', title: '使用人', width: '100'},
            //{field: 'inOrderCode', title: '内部订单号',width:'120' },
            {field: 'purCode', title: '申请单号', width: '120',sortable:true},
            {field: 'projectNo', title: '项目编号', width: '120',sortable:true,editor: {
        type: 'textbox'
    }},
            {
                field: 'customerCode', title: '服务客户', width: '100', editor: {
                    type: 'textbox',
                    options: {
                        required: true,
                        editable: false,
                        icons: [{
                            iconCls: 'icon-search',
                            handler: function () {
                                parent.layer.open({
                                    title: '客户选择器',
                                    type: 2,
                                    area: ['80%', '80%'],
                                    skin: 'layui-layer-molv',
                                    content: g.ctx + 'pc/supplier/customer/page/select',
                                    btn: ['确定', '关闭'],
                                    yes: function (index, layero) {
                                        let iframeWin = parent.window[layero.find('iframe')[0]['name']];
                                        parent.layer.close(index);
                                        let rowIndex = editIndex;
                                        iframeWin.getChecked(function (dta) {
                                            let customerCode = $("#table_order").edatagrid('getEditor', {
                                                index: rowIndex,
                                                field: 'customerCode'
                                            }).target;
                                            let customerName = $("#table_order").edatagrid('getEditor', {
                                                index: rowIndex,
                                                field: 'customerName'
                                            }).target;
                                            customerCode.textbox('setValue', '');
                                            customerName.textbox('setValue', '');
                                            customerCode.textbox('setValue', dta.customerCode);
                                            customerName.textbox('setValue', dta.customerName1);

                                        });

                                    }
                                });
                            }
                        }]
                    }
                }
            },
            {
                field: 'customerName',
                title: '服务客户实际值',
                width: '120',
                editor: {type: 'textbox', options: {required: true, editable: false}}
            },
            {
                field: 'drivingFactors', title: '驱动因素', width: '200',  editor: {
                    type: 'combobox', options: {
                        required: true,
                        valueField: "code",
                        textField: "codeWithDesc",
                        data: getDictList('contract_pay_boot_item'),
                        editable: false,
                        panelHeight: '150'
                    }
                },
                formatter: function (value) {
                    return getDicName('contract_pay_boot_item', value)
                }
            },
            //{field: 'assetsCode', title: '固定资产',width:'120' },
            {
                field: 'costCenterCode', title: '成本中心', width: '120', editor: {
                    type: 'textbox',
                    options: {
                        required: true,
                        editable: false,
                        icons: [{
                            iconCls: 'icon-search',
                            handler: function () {
                                parent.layer.open({
                                    title: '成本中心选择器',
                                    type: 2,
                                    area: ['60%', '60%'],
                                    skin: 'layui-layer-molv',
                                    content: g.ctx + 'pc/mall/shoppingPay/page/select',
                                    btn: ['确定', '关闭'],
                                    yes: function (index, layero) {
                                        let iframeWin = parent.window[layero.find('iframe')[0]['name']];
                                        parent.layer.close(index);
                                        let rowIndex = editIndex;
                                        iframeWin.getChecked(function (dta) {
                                            let costCenterCode = $("#table_order").edatagrid('getEditor', {
                                                index: rowIndex,
                                                field: 'costCenterCode'
                                            }).target;
                                            let costCenterName = $("#table_order").edatagrid('getEditor', {
                                                index: rowIndex,
                                                field: 'costCenterName'
                                            }).target;
                                            costCenterCode.textbox('setValue', '');
                                            costCenterName.textbox('setValue', '');
                                            costCenterCode.textbox('setValue', dta.costCenter);
                                            costCenterName.textbox('setValue', dta.describe);

                                        });

                                    }
                                });
                            }
                        }]
                    }
                }
            },
            {
                field: 'costCenterName',
                title: '成本中心名称',
                width: '120',
                editor: {type: 'textbox', options: {required: true, editable: false}}
            }
        ]],
        toolbar: selfData.toolbar,
        onBeginEdit: function (index, row) {
            editIndex = index;
            var serviceDesc = $("#table_order").edatagrid('getEditor', {index: index, field: 'serviceDesc'});
            $(serviceDesc.target).textbox('setValue', row.skuName);
        }
    });


}

/*
function copy(type) {
    let allRows = $('#table_order').datagrid('getRows');
    for (let i = 0; i < allRows.length; i++) {
        $('#table_order').datagrid('updateRow', {
            index: i,
            row: {
                [type]: allRows[0][type]
            }
        });
    }
}
*/

function copy(type) {
    endEditinTableOrderg();
    let allRows = $("#table_order").datagrid('getRows');
    console.log(allRows.length);
    for (let i = 0;i<allRows.length;i++){
        $("#table_order").datagrid('endEdit', i);

    }
    for (let i = 0; i < allRows.length; i++) {
        $("#table_order").datagrid('updateRow', {
            index: i,
            row: {
                [type]: allRows[0][type]
            }
        });
    }
}

function endEditinTableOrderg() {
    let editIndex = $('#table_order').edatagrid("options").editIndex;
    if (editIndex == undefined) {
        return true
    }
    if ($('#table_order').datagrid('validateRow', editIndex)) {
        $('#table_order').datagrid('endEdit', editIndex);
        editIndex = undefined;
        return true;
    } else {
        return false;
    }
}

function addOrderDetail(startTime, endTime) {
    if (!startTime) {
        topWin.layer.alert('请选择开始时间', {icon: 0});
        return false;
    }

    if (!endTime) {
        topWin.layer.alert('请选择结束时间', {icon: 0});
        return false;
    }
    //获取订单明细数据
    findPayDetail(startTime, endTime);
}

/**
 * 获取订单明细数据
 *
 * @param startTime 开始时间
 * @param endTime 结束时间
 */
function findPayDetail(startTime, endTime) {
    var queryParams = $("#table_order").datagrid('options').queryParams;
    queryParams.startTime = startTime;
    queryParams.endTime = endTime;


    $("#table_order").datagrid('options').loadFilter = pagerFilter;
    $("#table_order").datagrid('options').url = g.ctx + 'pc/mall/shoppingPay/rest/findPayDetail';
    $("#table_order").datagrid('load');
    setTotalAmoutnt();
}

//汇总计算合同金额
function setTotalAmoutnt() {
    setTimeout(function () {

        let orderRows = $("#table_order").datagrid('getRows');
        let totalAmoutnt = 0;
        for (let i = 0; i < orderRows.length; i++) {
            totalAmoutnt = totalAmoutnt + parseFloat(orderRows[i].totalAmount);
            console.log("明细金额"+ parseFloat(orderRows[i].totalAmount));
        }
        $("#totalAmount").textbox('setValue', totalAmoutnt.toFixed(2));
        $('#totalAmountNo').textbox('setValue', totalAmoutnt.toFixed(2));
        $('#amountCapital').textbox('setValue', number_chinese(totalAmoutnt.toFixed(2)));
    }, 500);


}


function delOrderDetail() {

    let row = $("#table_order").datagrid('getSelected');
    if (!row) {
        layer.msg("请选中一条记录");
        return;
    }
    let id = row.id;
    topWin.layer.confirm("是否删除", function (index) {
        if (id) {
            $.ajax({
                async: false,
                url: g.ctx + "pc/mall/shoppingPay/rest/detailRemove",
                data: {id: id},
                success: function (data) {
                    topWin.layer.alert("删除成功", {icon: 1}, function (idx) {
                        $("#table_order").datagrid("reload");
                        console.log("删除成功");
                        topWin.layer.close(index);
                        topWin.layer.close(idx);

                    });

                },
                error: function () {
                    layer.msg("删除失败");
                }
            });
        } else {
            let rowIndex = $("#table_order").datagrid('getRowIndex', row);
            $("#table_order").edatagrid('deleteRow', rowIndex);
            setTotalAmoutnt();
            topWin.layer.close(index);

        }


        /*
                var rowIndex = $("#table_order").datagrid('getRowIndex', row);
                $("#table_order").datagrid('deleteRow', rowIndex);
                topWin.layer.close(index);*/
    })

}


function submitShoppingPayDetalsForm(call) {
    debugger;
    let b;

    //let isBalanceDue = $("#isBalanceDue").textbox('getValue');
    /* let process = $("#process").textbox('getValue');

     if (isBalanceDue != '' && isBalanceDue == '是' && process == '') {
         topWin.layer.alert("请选择相关流程信息!")
         return;
     }
 */
    let editIndex = $('#table_order').edatagrid("options").editIndex;
    if (!$('#table_order').datagrid('validateRow', editIndex)) {
        topWin.layer.alert("请输入必填项");
        return false;
    }
    // 关闭明细行编辑
    if (editIndex !== -1) {
        $('#table_order').edatagrid('endEdit', editIndex);
    }

    let orderRows = $('#table_order').edatagrid('getRows');
    let totalAmoutnt = 0;
    for (let i = 0; i < orderRows.length; i++) {
        let pre = "第" + (i + 1) + "行明细，";
        if(orderRows[i].payCategory ==null  || orderRows[i].payCategory ==''){
            topWin.layer.alert(pre+"报销类别不能空!")
            return;
        }
        if(orderRows[i].customerCode ==null  || orderRows[i].customerCode ==''){
            topWin.layer.alert(pre+"服务客户不能空!")
            return;
        }
        if(orderRows[i].drivingFactors ==null || orderRows[i].drivingFactors ==''){
            topWin.layer.alert(pre+"驱动因素不能空")
            return;
        }
        if(orderRows[i].costCenterCode  ==null || orderRows[i].costCenterCode ==''){
            topWin.layer.alert(pre+"成本中心不能空!")
            return;
        }
        if(!orderRows[i].serviceDesc){
            orderRows[i].serviceDesc = orderRows[i].skuName;
        }
        totalAmoutnt = totalAmoutnt +parseFloat(orderRows[i].totalAmount);
    }
    $("#totalAmount").textbox('setValue', totalAmoutnt.toFixed(2));
    $('#totalAmountNo').textbox('setValue', totalAmoutnt.toFixed(2));
    $('#amountCapital').textbox('setValue', number_chinese(totalAmoutnt.toFixed(2)));
    let formPayData = $("#formPayData").serializeJson();
    console.log(formPayData)
    let orderlist = JSON.stringify(orderRows);
    console.log(orderlist)
    var payFiles = $("#payFiles").attr('data-fileIds')
    formPayData.payFiles = payFiles;
    formPayData.orderlist = orderlist;
    formPayData.accepProcessData = accepProcessData;

    if ($("#formPayData").form('validate')) {
        $.ajax({
            url: '/pc/mall/shoppingPay/rest/form/formPayData',
            type: 'POST',
            async: false,
            data: formPayData,
            success: function (res) {
                topWin.layer.alert("保存成功!", {icon: 1}, function (idx) {
                    topWin.layer.close(idx);
                    call()
                });
            },
            error: function (res) {
                topWin.layer.alert(res.responseJSON.message, {icon: 2});
            }
        });
    }
    return b;
}

$.extend($.fn.datagrid.methods, {
    editCell: function (jq, param) {
        return jq.each(function () {
            var opts = $(this).datagrid('options');
            var fields = $(this).datagrid('getColumnFields', true).concat($(this).datagrid('getColumnFields'));
            for (var i = 0; i < fields.length; i++) {
                var col = $(this).datagrid('getColumnOption', fields[i]);
                col.editor1 = col.editor;
                if (fields[i] != param.field) {
                    col.editor = null;
                }
            }
            $(this).datagrid('beginEdit', param.index);
            for (var i = 0; i < fields.length; i++) {
                var col = $(this).datagrid('getColumnOption', fields[i]);
                col.editor = col.editor1;
            }
        });
    }
});

var editIndex = undefined;

function endEditing() {

    if (editIndex == undefined) {
        return true
    }
    if ($('#table_pay').datagrid('validateRow', editIndex)) {
        $('#table_pay').datagrid('endEdit', editIndex);
        editIndex = undefined;
        return true;
    } else {
        return false;
    }
}

function onClickCell(index, field) {
    if (endEditing()) {
        var d = $("#table_pay").datagrid('getRows');
        changeJe(d);
        let dd = $('#table_pay').datagrid('selectRow', index);
        dd.datagrid('editCell', {index: index, field: field});
        editIndex = index;
    }
}

function changeJe(d) {
    var hs = 0.00;
    d.forEach(function (v, n) {
        let amount = v.amount;
        hs = parseFloat(hs) + parseFloat(amount);
    });
    $("#payeeAmount").textbox('setValue', hs.toFixed(4));
}

$.extend($.fn.validatebox.defaults.rules, {
    num: {
        validator: function (value) {
            return true;
        },
        message: '付款金额有误!'
    }
});

// 分页数据的操作
function pagerFilter(data) {
    if (typeof data.length == 'number' && typeof data.splice == 'function') {   // is array
        data = {
            total: data.length,
            rows: data
        }
    }
    var dg = $(this);
    var opts = dg.datagrid('options');
    var pager = dg.datagrid('getPager');
    pager.pagination({
        onSelectPage: function (pageNum, pageSize) {
            opts.pageNumber = pageNum;
            opts.pageSize = pageSize;
            pager.pagination('refresh', {
                pageNumber: pageNum,
                pageSize: pageSize
            });
            dg.datagrid('loadData', data);
        }
    });
    if (!data.originalRows) {
        data.originalRows = (data.rows);
        el.originalRows = (data.rows);
    }
    var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
    var end = start + parseInt(opts.pageSize);
    data.rows = (data.originalRows.slice(start, end));
    return data;
}