/**
 * 对账模块-对账单新增页面JS
 *
 * Created by li.kui on 2020/8/1.
 */
'use strict';
var el = {
    dataPanel: '#dataPanel',
    dataDiv: '#dataDiv',
    id: '#id',
    paymentPlanNo: '#paymentPlanNo',
    dataTabs: '#dataTabs',
    tbDetails: '#tbDetails',

    tb: '#tb',

    supplierCode: '#supplierCode',
    supplierName: '#supplierName',
    companyCode: '#companyCode',
    companyName: '#companyName',
    supCodeOrName: '#supCodeOrName',

    paymentTermDesc: '#paymentTermDesc',
    paymentTermCode: '#paymentTermCode',
    paymentWay: '#paymentWay',
    purchaseGroup: '#purchaseGroup',
    status: '#status',

    currencyCode: '#currencyCode',
    remark: '#remark',
    paymentExpireDateStart: '#paymentExpireDateStart',
    paymentExpireDateEnd: '#paymentExpireDateEnd',

    paymentPlanYear: '#paymentPlanYear',
    paymentPlanMonth: '#paymentPlanMonth',


    bpPayableBalance: '#bpPayableBalance',
    bpEstimateBalance: '#bpEstimateBalance',
    etPayableBalance: '#etPayableBalance',
    etEstimateBalance: '#etEstimateBalance',
    beginPeriodTotal: '#beginPeriodTotal',
    tbApproveLog: '#tbApproveLog',
    endPeriodTotal: '#endPeriodTotal',
    currPaymentAmount: '#currPaymentAmount',
    notTaxAmount: '#notTaxAmount',
    differenceAmount: '#differenceAmount',
    approveOpinion: '#approveOpinion',
    delDetail : [],


    filterFlag: false,
    tbDeduction: '#tbDeduction',
    tbRebate: '#tbRebate',
    localCurrency : '#localCurrency',
    originalCurrency: '#originalCurrency',
    ledgerAccount: '#ledgerAccount',
    ledgerAccountName: '#ledgerAccountName',
    advanceLocalCurrency: '#advanceLocalCurrency',
    advanceOriginalCurrency: '#advanceOriginalCurrency',
    invoiceFileInput: '#invoiceFileInput',


    poType: '#poType',
    choseSupplierDialog: null,
    choseRebateDataDialog: null,
    userTableColumn: [],
    originalRows: [],
    removeList: [],
    bodyHeight: document.documentElement.clientHeight,
    defaultColumns: []
};

var businessFalg = "0";
var editor = undefined;

/**
 * 文档就绪
 */
$(function () {
    initDict('payment_method,payment_way,currency, unit')
    initNecessaryDatas('pc/sys/company/rest/listAll')
    initNecessaryDatas('pc/sys/purchaseGroup/rest/listAll')
    $(el.dataPanel).panel({
        collapsible: true,
        onCollapse: function () {
            $(el.dataTabs).tabs('select', 0);
            $(el.tbDetails).edatagrid('resize', {height: el.bodyHeight - 80});
            if (optType!==0){
                // $(el.tbApproveLog).datagrid('resize', {height: el.bodyHeight - 80});
            }
        },
        onExpand: function () {
            $(el.dataTabs).tabs('select', 0);
            var dataDiv = $(el.dataDiv).outerHeight() + 90;
            $(el.tbDetails).edatagrid('resize', {height: 400});
            if (optType!==0){
                // $(el.tbApproveLog).datagrid('resize', {height: el.bodyHeight - dataDiv});
            }
        }
    });

    // 加载页面输入或下拉框数据
    initPageInput();
    //行状态1待提交 2已提交 3删除
    el.defaultColumns = [

    ];
    initTbDetails(el.defaultColumns);
    debugger
    var options = $(el.tbDetails).edatagrid('options');
    // if (optType!==0){
    //     initTbApproveLog();
    // }
});

/**
 * 初始化入库明细表格
 */
function initTbDetails(column) {
    var dataDiv = $(el.dataDiv).outerHeight() + 90, orderType = $(el.orderType).val();
    // var columns = dynamicColumns(orderType);
    var toolBar = [];
    debugger
    var optType = 2;
    if (optType===0) {
        // toolBar.push(
        //     {
        //         text: '新增',
        //         iconCls: 'icon-add',
        //         handler: function () {
        //             // var companyCode = $(el.companyCode).combobox('getValue'), factoryCode = $(el.factoryCode).combobox('getValue'), taxCode = $(el.taxCode).combobox('getValue'),
        //             //     inStockStartDate = $(el.inStockStartDate).datebox('getValue'), inStockEndDate = $(el.inStockEndDate).datebox('getValue'),
        //             //     currencyCode = $(el.currencyCode).combobox('getValue'), supplierCode = $(el.supplierCode).textbox('getValue'),
        //             //     poType = getTextByJs($(el.poType).combobox('getValues')),
        //             //     voucherType = $(el.voucherType).combobox('getValue'),
        //             //     purchaseGroup = $('#purchaseGroup').combobox('getValue');
        //             // businessFalg  = "0";
        //             addInvoiceItem();
        //             // getVoucherData(companyCode, factoryCode, supplierCode, currencyCode, inStockStartDate, inStockEndDate,purchaseGroup,poType,taxCode,voucherType,businessFalg);
        //         }
        //     },
        //     // '-',
        //     // {
        //     //     text: '全选',
        //     //     iconCls: 'icon-ok',
        //     //     handler: function () {
        //     //         detailSelectAll();
        //     //     }
        //     // },
        //     // '-',
        //     // {
        //     //     text: '取消全选',
        //     //     iconCls: 'icon-remove',
        //     //     handler: function () {
        //     //         cancelSelectAll();
        //     //     }
        //     // },
        //     // '-',
        //     // {
        //     //     text: '导出',
        //     //     iconCls: 'icon-download',
        //     //     handler: function () {
        //     //         detailExport();
        //     //     }
        //     // },
        //     // '-',
        //     // {
        //     //     text: '填充应付未清金额',
        //     //     iconCls: 'icon-ok',
        //     //     handler: function () {
        //     //         payableOutstanding();
        //     //     }
        //     // },
        //     // '-',
        //     // {
        //     //     text: '修改其他折扣',
        //     //     iconCls: 'icon-import',
        //     //     handler: function () {
        //     //         updateOther();
        //     //     }
        //     // },
        //     // "-",
        //     // {
        //     //     text: '批量价格调整',
        //     //     id: 'btn_pljgtz',
        //     //     iconCls: 'icon-import',
        //     //     handler: function () {
        //     //         importTaxPriceExcel();
        //     //     }
        //     // },
        //     "-",
        //     {
        //         text: '删除',
        //         id: 'btn_del',
        //         iconCls: 'icon-delete',
        //         handler: function () {
        //             remove();
        //         }
        //     },
        //     "-",
        //     {
        //         text: '恢复删除',
        //         id: 'btn_del',
        //         iconCls: 'icon-delete',
        //         handler: function () {
        //             remove();
        //         }
        //     },
        //     "-",
        //     {
        //         text: '保存',
        //         id: 'btn_save',
        //         iconCls: 'icon-save',
        //         handler: function () {
        //             savePaymentDetail();
        //         }
        //     },
        // "-",
        // {
        //     text: '导出',
        //     iconCls: 'icon-download',
        //     handler: function () {
        //         detailExport();
        //     }
        // },
        // "-",
        // {
        //     text: '导入',
        //     iconCls: 'icon-download',
        //     handler: function () {
        //         detailExport();
        //     }
        // }
        // )
    }else if (optType===1) {
        toolBar.push(
            {
                text: '添加',
                iconCls: 'icon-add',
                handler: function () {
                    // addVoucherData();
                    addInvoiceItem();
                }
            },
            '-',
            {
                text: '删除',
                iconCls: 'icon-remove',
                handler: function () {
                    delInvoiceItem(1);
                }
            },
            '-',
            {
                text: '恢复删除',
                iconCls: 'icon-remove',
                handler: function () {
                    // delStatementItem();
                    delInvoiceItem(0);
                }
            },
            '-',
            {
                text: '提交',
                iconCls: 'icon-save',
                handler: function () {
                    submitPaymentDetail();
                }
            },
            // '-',
            // {
            //     text: '获取凭证信息',
            //     iconCls: 'icon-add',
            //     handler: function () {
            //         var companyCode = $(el.companyCode).combobox('getValue'), factoryCode = $(el.factoryCode).combobox('getValue'), taxCode = $(el.taxCode).combobox('getValue'),
            //             inStockStartDate = $(el.inStockStartDate).datebox('getValue'), inStockEndDate = $(el.inStockEndDate).datebox('getValue'),
            //             currencyCode = $(el.currencyCode).combobox('getValue'), supplierCode = $(el.supplierCode).textbox('getValue'),
            //             poType = getTextByJs($(el.poType).combobox('getValues')),
            //             voucherType = $(el.voucherType).combobox('getValues'),
            //             purchaseGroup = $('#purchaseGroup').combobox('getValue');
            //         getVoucherData(companyCode, factoryCode, supplierCode, currencyCode, inStockStartDate, inStockEndDate,purchaseGroup,poType,taxCode,voucherType);
            //     }
            // },
            '-',
            {
                text: '保存',
                iconCls: 'icon-ok',
                handler: function () {
                    savePaymentDetail();
                }
            },
            // '-',
            // {
            //     text: '修改其他折扣',
            //     iconCls: 'icon-import',
            //     handler: function () {
            //         updateOther();
            //     }
            // },
            // "-",
            // {
            //     text: '设置不参与',
            //     id: 'btn_pljgtz',
            //     iconCls: 'icon-delete',
            //     handler: function () {
            //         remove();
            //     }
            // },
            // "-",
            // {
            //     text: '导出',
            //     iconCls: 'icon-download',
            //     handler: function () {
            //         detailExport();
            // advanceExport();
            //     }
            // },
        )
    } else if (optType===2) {
        toolBar.push(
            // {
            //     text: '导出',
            //     iconCls: 'icon-download',
            //     handler: function () {
            //         detailExport();
            //     }
            // }
        )
    }
    var columns = [
        {
            field: 'ck',
            checkbox: true
        },
        {
            field: 'deleteFlag',
            title: '删除标记',
            width: 80,
            formatter: function (value) {
                if (value ===1) {
                    return '<span style="color: red;">已删除</span>';
                }else {
                    return "未删除";
                }
            }
        },

        {
            field: 'status',
            title: '数据状态',
            width: 115,
            sortable: true,
            exportEnum:[
                {code:1,codeWithDesc:'待提交'},
                {code:2,codeWithDesc:'已提交'},
                {code:3,codeWithDesc:'删除'},
            ],
            formatter: function (value) {
                switch (value) {
                    case 1:
                        return '待提交';
                    case 2:
                        return '已提交';
                    case 3:
                        return '删除';
                    default:
                        return '';
                }
            }
        },
        {
            field: 'paymentPlanNo',
            title: '付款计划单号',
            width: 140,
            sortable: true
        },
        {
            field: 'paymentPlanDetailNo',
            title: '付款计划明细行号',
            width: 140,
            sortable: true
        },
        {
            field: 'supplierCode',
            title: '供应商编码',
            width: 140,
            sortable: true,
            editor: {
                type: 'textbox', options: {
                    required: false, editable: false, icons: [{
                        iconCls: 'icon-search', handler: function () {
                            // var supplierType = $("#supplierType").val();
                            // if (supplierType == "") {
                            //     topWin.layer.msg("请先选择供应商类型");
                            //     return;
                            // }
                            var supplierDialogElement = openDialog("supplierDialog", g.ctx + "pc/supplier/supplierSelect?single=1", {
                                title: "供应商选择",
                                width: '800',
                                height: '80%',
                                cache: false,
                                modal: true,
                                border: false,
                                draggable: false,
                                shadow: false,
                                onClose: function () {
                                    supplierDialogElement.dialog('destroy');
                                },
                                buttons: [{
                                    text: '选择', iconCls: 'icon-accept', handler: function () {
                                        topWin.frames['supplierDialog'].chooseRow(function (selectrow) {

                                            supplierDialogElement.dialog('close');
                                            // var load = topWin.layer.load(0, {
                                            //     shade: [0.6, '#eee'] //0.1透明度的白色背景
                                            // });
                                            // var postRows = []
                                            // for (let i = 0; i < rows.length; i++) {
                                            //     // 注意这个地方使用供应商名称存编码，后台有特殊处理
                                            //     postRows.push({
                                            //         id: rows[i].id,
                                            //         supplierName: row.supplierCode
                                            //     })
                                            // }
                                            let supplierCode = $("#tbDetails").edatagrid('getEditor', {

                                                index: editor, field: 'supplierCode'

                                            }).target;
                                            supplierCode.textbox("setValue", selectrow.supplierCode)
                                            let supplierName = $("#tbDetails").edatagrid('getEditor', {
                                                index: editor, field: 'supplierName'
                                            }).target;
                                            supplierName.textbox("setValue", selectrow.supplierName)



                                            // $.ajax({
                                            //     url: g.ctx + 'pc/order/shortagePlan/rest/batchFillSupplier',
                                            //     method: "POST",
                                            //     contentType: 'application/json',
                                            //     data: JSON.stringify(postRows),
                                            //     complete: function () {
                                            //         topWin.layer.close(load)
                                            //     },
                                            //     success: function (data) {
                                            //         supplierDialogElement.dialog('close');
                                            //         topWin.layer.msg("操作成功", {icon: 1});
                                            //         $(el.tb).datagrid("reload")
                                            //     },
                                            //     error: function (data) {
                                            //         topWin.layer.alert(data.responseJSON.message, {icon: 2});
                                            //     }
                                            // });

                                        });
                                    }
                                }, {
                                    text: '关闭', iconCls: 'icon-cancel', handler: function () {
                                        supplierDialogElement.dialog('close');
                                    }
                                }]
                            })
                        }
                    }]
                }
            }
        },
        {
            field: 'supplierName',
            title: '供应商全称',
            width: 140,
            sortable: true,
            editor: {
                type: 'textbox', options: {
                    required: false, editable: false
                }
            }
        },
        {
            field: 'companyCode',
            title: '公司',
            width: 240,
            sortable: true,
            exportEnum:getNecessaryDataList('pc/sys/company/rest/listAll'),
            formatter: function (value) {
                return getNecessaryDataName('pc/sys/company/rest/listAll',value);
            },
            editor: {
                type: 'combobox',
                options: {
                    url: g.ctx + 'pc/sys/company/rest/listAll',
                    valueField: 'companyCode',
                    textField: 'codeWithDesc',
                    limitToList: 'true',
                    prompt: '-- 请选择 --',
                    method: 'GET',
                    editable: false,
                    panelHeight: 150
                }
            }
        },
        {
            field: 'currencyCode',
            title: '币种',
            width: 140,
            sortable: true,
            formatter: function (value) {
                return getDicName('currency',value)
            },

            editor: {
                type: 'combobox',
                options: {
                    url: g.ctx + 'pc/sys/dict/getDicByType?type=currency',
                    valueField: 'code',
                    textField: 'codeWithDesc',
                    limitToList: 'true',
                    prompt: '-- 请选择 --',
                    method: 'GET',
                    editable: false,
                    panelHeight: 150
                }
            }
        },
        {
            field: 'actualPayAmount',
            title: '应付金额',
            width: 90,
            sortable: true,
            formatter: function (value) {
                return formatterCustomPrice(value,5,true,false)
            },
            editor: {
                type: 'numberbox',
                options: {
                    // min: 0,
                    precision: 2,
                    // onChange: function (nv, ov) {
                    //     if(ov){
                    //         updateRowData(nv, 'taxAmount');
                    //     }
                    // }
                }
            }
        },
        {
            field: 'appliedUnpaidAmount',
            title: '已请款未付金额(历史)',
            width: 90,
            sortable: true,
            formatter: function (value) {
                return formatterCustomPrice(value,5,true,false)
            },
            editor: {
                type: 'numberbox',
                options: {
                    // min: 0,
                    precision: 2,
                    // onChange: function (nv, ov) {
                    //     if(ov){
                    //         updateRowData(nv, 'taxAmount');
                    //     }
                    // }
                }
            }
        },
        {
            field: 'accountStatementYear',
            title: '对账单年份',
            width: 100,
            sortable: true,
            editor: {
                type: 'textbox'
            }
        },
        {
            field: 'accountStatementMonth',
            title: '对账单月份',
            width: 100,
            sortable: true,
            editor: {
                type: 'textbox'
            }
        } ,
        {
            field: 'paymentTermCode',
            title: '付款条件',
            width: 200,
            sortable: true,
            formatter: function (value) {
                return getDicName('payment_method',value)
            },
            editor: {
                type: 'combobox',
                options: {
                    url: g.ctx + 'pc/sys/dict/getDicByType?type=payment_method',
                    valueField: 'code',
                    textField: 'codeWithDesc',
                    limitToList: 'true',
                    prompt: '-- 请选择 --',
                    method: 'GET',
                    editable: false,
                    panelHeight: 150
                }
            }

        },
        {
            field: 'paymentWay',
            title: '付款方式',
            width: 200,
            sortable: true,
            formatter: function (value) {
                return getDicName('payment_way',value)
            },
            editor: {
                type: 'combobox',
                options: {
                    url: g.ctx + 'pc/sys/dict/getDicByType?type=payment_way',
                    valueField: 'code',
                    textField: 'codeWithDesc',
                    limitToList: 'true',
                    prompt: '-- 请选择 --',
                    method: 'GET',
                    editable: false,
                    panelHeight: 150
                }
            }
        },
        {
            field: 'purchaseGroup',
            title: '采购组',
            width: 100,
            sortable: true,
            exportEnum:getNecessaryDataList('pc/sys/purchaseGroup/rest/listAll'),
            formatter: function (value) {
                return getNecessaryDataName('pc/sys/purchaseGroup/rest/listAll',value);
            },
            editor: {
                type: 'combobox',
                options: {
                    url: g.ctx + 'pc/sys/purchaseGroup/rest/listAll',
                    valueField: 'code',
                    textField: 'codeWithDesc',
                    limitToList: 'true',
                    prompt: '-- 请选择 --',
                    method: 'GET',
                    editable: false,
                    panelHeight: 150
                }
            }
        },

        {
            field: 'paymentPlanYear',
            title: '付款计划年份',
            width: 100,
            sortable: true,
            editor: {
                type: 'textbox',
                // editable: false
                options: {
                    editable: false,
                }
            }
        },
        {
            field: 'paymentPlanMonth',
            title: '付款计划月份',
            width: 100,
            sortable: true,
            editor: {
                type: 'textbox',
                options: {
                    editable: false,
                }
            }
        } ,
        {
            field: 'paymentPlanWeek',
            title: '付款周',
            width: 100,
            editor: {
                type: 'textbox',
                editable: false
            }
        } ,
        {
            field: 'paymentExpireDate',
            title: '付款到期日',
            width: 120,
            sortable: true,
            exportDateFormatter:'date',
            formatter: function (value, row) {
                if (!value) {
                    return '';
                }
                return '<span style="color: red;">' + moment(value).format('YYYY-MM-DD') + '</span>';
            },
            editor: {
                type: 'datebox',
                options: {
                    editable: false,
                    parser: function (value) {
                        if (value) {
                            return new Date(value);
                        } else {
                            return new Date();
                        }
                    }
                }
            }
        },
        {
            field: 'remark',
            title: '备注',
            width: 120,
            sortable: false,
            editor: {
                type: 'textbox'
            }
        }

        // {
        //     field: 'taxAmount',
        //     title: '对账含税金额',
        //     width: 100,
        //     sortable: true,
        //     formatter: function (value) {
        //         if (value < 0) {
        //             return '<span style="color: red;">' + formatterCustomPrice(value,2,true,false) + '</span>';
        //         }else {
        //             return formatterCustomPrice(value,2,true,false);
        //         }
        //     }
        // },

    ];

    //供应商不能看到的字段
    // if (Number($(el.isSupplier).val())===1){
    //     columns = columns.filter(obj => obj.field !== 'paymentExpireDate');
    // }
    if (optType !== 0) {
        $(el.tbDetails).edatagrid({
            loadMsg: '数据加载中, 请耐心等待......',
            url: g.ctx + 'pc/finance/payment/plan/detail/rest/find/by/paymentPlan/id',
            // height: el.bodyHeight - dataDiv,
            height: 600,
            singleSelect: false,
            rownumbers: true,
            // filterBtnIconCls: 'icon-filter',
            // 定义从服务器对数据进行排序
            remoteSort: false,
            // 定义是否允许多列排序
            // multiSort: true,
            pagination: true,
            pageSize: 500,
            pageList: [10, 50, 100, 200, 500, 1000, 2000, 3000],
            showFooter: true,
            queryParams: {
                ppId: $(el.id).val(),
                supCodeOrName: $.trim($(el.supCodeOrName).val()),
                companyCode: $(el.companyCode).combobox('getValue'),
                paymentTermCode: $(el.paymentTermCode).combobox('getValue'),//付款条件
                paymentWay: $(el.paymentWay).combobox('getValue'),//付款方式
                currencyCode: $(el.currencyCode).combobox('getValue'),
                purchaseGroup: $(el.purchaseGroup).combobox('getValue'),
                paymentExpireDateStart: $(el.paymentExpireDateStart).datebox('getValue'),
                paymentExpireDateEnd: $(el.paymentExpireDateEnd).datebox('getValue')
            },
            frozenColumns: [
                // [
                //     {
                //         field: 'ck',
                //         checkbox: true
                //     }
                // ]
            ],
            columns: [
                columns
            ],
            toolbar: toolBar,
            // loadFilter: pagerFilter,
            // onLoadSuccess: function (data) {
            //     // if (optType===0){
            //     //     // 默认全部选中
            //     //     $(el.tbDetails).datagrid('selectAll');
            //     // }
            //     // var dataRows = data.rows;
            //     //
            //     // calculationAmount(dataRows);
            //     // el.originalRows = data.rows;
            //     // if (data.footer){
            //     //
            //     //     $(el.taxAmount).textbox('setValue', new BigNumber(data.footer[0].taxAmount).decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN).toFormat(2));
            //     //     $(el.notTaxAmount).textbox('setValue',new BigNumber(data.footer[0].notTaxAmount).decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN).toFormat(2));
            //     //     $(el.differenceAmount).textbox('setValue',new BigNumber(data.footer[0].diffTaxAmount).decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN).toFormat(2));
            //     //     if ($(el.currencyCode).val() == "CNY") {
            //     //         $(el.supplierCode2).combobox('setValue','');
            //     //         $(el.supplierName2).val('');
            //     //         $(el.supplierCode2).combobox('disable');
            //     //     } else {
            //     //         $(el.supplierCode2).combobox('enable');
            //     //         if (data.footer[0].supplierCode2){
            //     //             $(el.supplierCode2).combobox('setValue',data.footer[0].supplierCode2);
            //     //             $(el.supplierName2).val(data.footer[0].supplierName2);
            //     //         }
            //     //     }
            //     // }
            // },
            // onBeforeSortColumn: function (sort, order) {
            //     console.log(sort)
            //     if (order.toUpperCase() === 'DESC')
            //         order = -1
            //     else
            //         order = 1;
            //     el.originalRows.sort(function (a, b) {
            //         if (parseFloat(a[sort]) > 1 * b[sort])
            //             return 1 * order;
            //         else if (a[sort] * 1 < 1 * b[sort])
            //             return -1 * order;
            //         else
            //             return 0;
            //     });
            //     return true;
            // },
            onClickRow: function (index,row) {
                // initFileForm('invoice-file-form');
                // optType === 1 编辑， optType == 5 采购审批，只允许编辑两列
                debugger
                if (optType===1){
                    endInvoiceEditor();
                    //判断如果付款计划明细ID大于0，则不允许编辑
                    if (row.id > 0) {

                    }

                    $(el.tbDetails).edatagrid('editRow', index);
                    editor = index;
                    debugger
                    // var file = $(el.tbInvoice).edatagrid('getEditor', {index: editor, field: 'file'});
                    var row = $(el.tbDetails).edatagrid('getRows')[editor];

                    // if (file) {
                    //     $(file.target).next().children(".validatebox-readonly").click(function () {
                    //         console.log(row)
                    //         console.log(row.fileId)
                    //         if (row.fileId){
                    //         }
                    //     });
                    //     $(file.target).filebox('setText',row.fileName);
                    // }
                    // addOrDelInvoice();
                }
            },
            onLoadSuccess: function (data) {
                // $('#tbDetails').parent(".datagrid-view").children(".datagrid-view1")
                //     .children(".datagrid-body")
                //     .children(".datagrid-body-inner")
                //     .children(".datagrid-btable")
                //     .children("tbody")
                //     .children("tr")
                //     .children("td")
                //     .children(".datagrid-cell-rownumber").css('height', '60px').css('line-height', '60px')
                // if (data.rows.length>0){
                // initFileForm('invoice-file-form');
                // }

            },
            // onClickRow: function (index, row) {
            //     // if (row.voucherFlag === 'H') {
            //     $(el.tbDetails).datagrid('selectRow', index);
            //     // }
            //     var rows = $(el.tbDetails).datagrid('getSelections');
            //     calculationAmount(rows);
            // },
            // onCheck: function(){
            //     var rows = $(el.tbDetails).datagrid('getSelections');
            //     calculationAmount(rows);
            // },
            // onUncheck: function () {
            //     var rows = $(el.tbDetails).datagrid('getSelections');
            //     calculationAmount(rows);
            // }
        });
    }
}

function addInvoiceItem() {
    // endInvoiceEditor();
    var index = $(el.tbDetails).edatagrid('appendRow', {
        id: 0,
        currencyCode: '',
        paymentPlanNo: $(el.paymentPlanNo).val(),
        status: 1,
        paymentPlanYear: $(el.paymentPlanYear).val(),
        paymentPlanMonth: $(el.paymentPlanMonth).val(),

    }).edatagrid("getRows").length - 1;
    // $(el.tbInvoice).edatagrid('beginEdit', index);
    $(el.tbDetails).edatagrid('editRow', index);
    editor = index;
    // addOrDelInvoice();
}

function endInvoiceEditor() {
    $(el.tbDetails).edatagrid('saveRow')
    editor = undefined;
    //重新计算表头的某些字段值
    // var rows = $(el.tbInvoice).edatagrid('getRows');
    // countPageHeadInvoice(rows);
}

function delInvoiceItem(deltype) {
    endInvoiceEditor();
    var rows = $(el.tbDetails).edatagrid('getSelections');
    if (rows.length<=0) {
        layer.msg("请选择您要删除的付款计划明细信息");
        return;
    }
    var delIds = [];
    for (var i = 0; i < rows.length; i++) {
        if (rows[i].deleteFlag === 1 && deltype === 1) {
            layer.msg("已经删除的付款计划明细数据不能在删除");
            return;
        }
        if (rows[i].deleteFlag === 0 && deltype === 0) {
            layer.msg("未删除的数据不能恢复删除");
            return;
        }
        delIds.push(rows[i].id);
    }
    var conStr = "确定删除已选中的付款计划明细?";
    if (deltype === 0) {
        conStr = "确定恢复已选中的删除数据?";
    }
    topWin.layer.confirm(conStr, {icon: 3}, function (index) {
        let loadIndex = topWin.layer.load(0);

        // for (var i = 0; i < rows.length; i++) {
        //     var index = $(el.tbDetails).edatagrid("getRowIndex", rows[i]);
        //     $(el.tbDetails).edatagrid("deleteRow", index);
        // }

        $.ajax({
            type: 'POST',
            url: g.ctx + 'pc/finance/payment/plan/rest/del',
            data: {
                ids: delIds.join(","),
                type : deltype
            },
            complete: function () {
                topWin.layer.close(loadIndex);
            },
            success: function () {
                topWin.layer.msg('删除成功');
                // $(el.tb).datagrid('load');
                // // topWin.layer.alert("发布成功", {icon: 1}, function (idx) {
                topWin.layer.close(loadIndex);
                // //     $(el.tb).datagrid('load');
                // // });
                // // callback();
                $(el.tbDetails).edatagrid('reload');
            },
            error: function (data) {
                topWin.layer.close(loadIndex);
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    })


    //重新计算表头的某些字段值
    // var rows = $(el.tbDetails).edatagrid('getRows');
    // countPageHeadInvoice(rows);
    //即时删除，重新加载 todo
}


function submitPaymentDetail() {
    endInvoiceEditor();
    var rows = $(el.tbDetails).edatagrid('getSelections');
    if (rows.length<=0) {
        layer.msg("请选择您要提交的付款计划明细信息");
        return;
    }
    var delIds = [];
    for (var i = 0; i < rows.length; i++) {
        if (rows[i].id === 0) {
            layer.msg("请先保存在提交");
            return;
        }

        if (rows[i].deleteFlag === 1) {
            layer.msg("已经删除的数据无法提交");
            return;
        }
        delIds.push(rows[i].id);
    }
    topWin.layer.confirm("确定提交已选中的付款计划明细?", {icon: 3}, function (index) {
        let loadIndex = topWin.layer.load(0);

        $.ajax({
            type: 'POST',
            url: g.ctx + 'pc/finance/payment/plan/rest/submit',
            data: {
                ids: delIds.join(",")
            },
            complete: function () {
                topWin.layer.close(loadIndex);
            },
            success: function () {
                topWin.layer.msg('提交成功');
                // $(el.tb).datagrid('load');
                // // topWin.layer.alert("发布成功", {icon: 1}, function (idx) {
                topWin.layer.close(loadIndex);
                // //     $(el.tb).datagrid('load');
                // // });
                // // callback();
                $(el.tbDetails).edatagrid("reload")
            },
            error: function (data) {
                topWin.layer.close(loadIndex);
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    })


    //重新计算表头的某些字段值
    // var rows = $(el.tbDetails).edatagrid('getRows');
    // countPageHeadInvoice(rows);
    //即时删除，重新加载 todo
}


function savePaymentDetail() {
    endInvoiceEditor();

    var rows = $(el.tbDetails).edatagrid('getSelections');
    if (rows.length === 0) {
        topWin.layer.alert('请选择需要保存的明细数据', {icon: 0});
        return false;
    }
    var statementItem = [];
    for (let i = 0 ; i < rows.length ; i ++) {

        var item = rows[i];
        if (item.deleteFlag === 1) {
            layer.msg("已经删除的明细数据无法保存");
            return;
        }


        var obj = {};


        if (!item.supplierCode || !item.supplierName) {
            layer.msg("请选择供应商");
            return;
        }

        if (!item.companyCode) {
            layer.msg("请选择公司");
            return;
        }

        if (!item.currencyCode) {
            layer.msg("请选择币种");
            return;
        }

        // if (!item.currencyCode) {
        //     layer.msg("请选择币种");
        //     return;
        // }

        if (!item.accountStatementYear || !item.accountStatementMonth) {
            layer.msg("请填写对账单年月");
            return;
        }

        // obj.deleteFlag = 0;
        // obj.status = 0;
        obj.id = item.id;
        obj.status = item.status;
        obj.supplierCode = item.supplierCode;
        obj.supplierName = item.supplierName;
        obj.companyCode = item.companyCode;
        obj.currencyCode = item.currencyCode;
        obj.actualPayAmount = item.actualPayAmount;//应付金额
        obj.appliedUnpaidAmount = item.appliedUnpaidAmount;//已请款未付金额（历史）
        obj.paymentTermCode = item.paymentTermCode;//付款条件
        obj.paymentWay = item.paymentWay;//付款方式
        obj.purchaseGroup = item.purchaseGroup;//采购组编码
        obj.paymentPlanWeek = item.paymentPlanWeek;//付款计划周(对账单上付款到期日所在周)
        obj.paymentExpireDate = item.paymentExpireDate;//付款到期日
        obj.remark = item.remark;
        obj.paymentPlanDetailNo = item.paymentPlanDetailNo;
        obj.accountStatementYear = item.accountStatementYear;
        obj.accountStatementMonth = item.accountStatementMonth;
        statementItem.push(obj);
    }
    // var dataParams = {};
    // dataParams.detailDate = statementItem;
    // dataParams.optType = optType;
    var headData = {};
    headData.id = $(el.id).val();
    headData.optType = optType;
    headData.paymentPlanNo = $(el.paymentPlanNo).val();
    // var dataParams = {};
    // dataParams.headData = headData;
    // dataParams.detailDate = statementItem;
    // if (Number(foreignCurrencyAddFlag)===0) {
    //     dataParams.invoicedReceiptData = invoicedReceipt;
    // }

    var url = g.ctx + 'pc/finance/payment/plan/rest/saveOrUpdate';
    var loading = topWin.layer.msg('数据保存中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    $.ajax({
        url: url,
        type: 'POST',
        data: {
            optType: optType,
            headData: JSON.stringify(headData),
            statementItem: JSON.stringify(statementItem)
        },
        // data: JSON.stringify(dataParams),

        // optType: optType,
        // // headData: JSON.stringify(headData),
        // statementItem: JSON.stringify(statementItem)
        // contentType: 'application/json',
        success: function (data) {
            topWin.layer.close(loading);
            topWin.layer.alert('数据保存成功', {icon: 1});
            // moldMoveDialog.dialog('close');
            $(el.tbDetails).edatagrid('reload');
            // callback(data);
        },
        error: function (data) {
            topWin.layer.close(loading);
            topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
        }
    });

}

function approvalPayment(optType1,callback) {
    endInvoiceEditor();
    //optType 3 采购主管确认， 4 财务确认， 5 财务拒绝

    var approveOpinion = $(el.approveOpinion).val();
    if (!approveOpinion && optType1 === 5) {
        topWin.layer.alert('请选择驳回的理由', {icon: 0});
        return false;
    }

    var headData = {};
    headData.id = $(el.id).val();
    headData.status = $(el.status).val();
    headData.optType = optType1;
    headData.remark = approveOpinion;

    var url = g.ctx + 'pc/finance/payment/plan/rest/approvalPayment';
    var loading = topWin.layer.msg('数据保存中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    $.ajax({
        url: url,
        type: 'POST',
        data: {
            optType: optType,
            headData: JSON.stringify(headData)
        },
        // data: JSON.stringify(dataParams),

        // optType: optType,
        // // headData: JSON.stringify(headData),
        // statementItem: JSON.stringify(statementItem)
        // contentType: 'application/json',
        success: function (data) {
            topWin.layer.close(loading);
            topWin.layer.alert('数据保存成功', {icon: 1});
            // moldMoveDialog.dialog('close');
            // $(el.tbDetails).edatagrid('reload');
            callback(data);
        },
        error: function (data) {
            topWin.layer.close(loading);
            topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
        }
    });

}

/**
 * 初始化审批记录表格
 */
function initTbApproveLog() {
    var dataDiv = $(el.dataDiv).outerHeight() + 90;

    // $(el.tbApproveLog).datagrid({
    //     loadMsg: '数据加载中, 请耐心等待......',
    //     height: el.bodyHeight - dataDiv,
    //     url: g.ctx + 'pc/finance/account/statement/detail/rest/find/as/approve/log',
    //     singleSelect: false,
    //     rownumbers: true,
    //     // 定义从服务器对数据进行排序
    //     remoteSort: false,
    //     // 定义是否允许多列排序
    //     // multiSort: true,
    //     pagination: true,
    //     queryParams: {
    //         ppId: $(el.id).val()
    //     },
    //     columns: [
    //         [
    //             {
    //                 field: 'approveNode',
    //                 title: '审批节点描述',
    //                 width: 120,
    //                 formatter: function (value) {
    //                     if(Number(value) === 1){
    //                         return '对账确认';
    //                     }else {
    //                         return '财务节点';
    //                     }
    //                 }
    //             },
    //             {
    //                 field: 'approveResult',
    //                 title: '审批结果',
    //                 width: 120,
    //                 formatter: function (value) {
    //                     switch (Number(value)){
    //                         case 0:
    //                             return '<span style="color: red;">拒绝</span>';
    //                         case 1:
    //                             return '<span style="color: green;">同意</span>';
    //                         case 2:
    //                             return '<span style="color: orange;">采购撤销</span>';
    //                         case 3:
    //                             return '<span style="color: orange;">财务撤销</span>';
    //                         default:
    //                             return '';
    //                     }
    //                 }
    //             },
    //             {
    //                 field: 'approveOpinion',
    //                 title: '审批意见',
    //                 width: 300
    //             },
    //             {
    //                 field: 'approveUserName',
    //                 title: '审批用户姓名',
    //                 width: 130
    //             },
    //             {
    //                 field: 'approveTime',
    //                 title: '审批时间',
    //                 width: 140,
    //                 sortable: true,
    //                 formatter: function (value) {
    //                     if (value) {
    //                         return moment(value).format("YYYY-MM-DD HH:mm:ss");
    //                     }
    //                     return '';
    //                 }
    //             }
    //         ]
    //     ]
    // });
}


function searchAsData() {
    $(el.tbDetails).edatagrid('options').queryParams = getQuery();
    $(el.tbDetails).edatagrid('load');
}

function getQuery() {
    var queryParams = $(el.tbDetails).edatagrid('options').queryParams;
    queryParams.ppId = $(el.id).val();
    queryParams.supCodeOrName = $.trim($(el.supCodeOrName).val());
    queryParams.companyCode = $(el.companyCode).combobox('getValue');
    queryParams.paymentTermCode = $(el.paymentTermCode).combobox('getValue');//付款条件
    queryParams.paymentWay = $(el.paymentWay).combobox('getValue');//付款方式
    queryParams.currencyCode = $(el.currencyCode).combobox('getValue');
    queryParams.purchaseGroup = $(el.purchaseGroup).combobox('getValue');
    queryParams.createTimeStart = $(el.paymentExpireDateStart).datebox('getValue');
    queryParams.createTimeEnd = $(el.paymentExpireDateEnd).datebox('getValue');
    return queryParams;
}

/**
 * 重置查询
 */
function resetAsSearch() {
    $(el.supCodeOrName).val('');
    $(el.companyCode).combobox('setValue', '');
    $(el.paymentWay).combobox('setValue', '');
    $(el.paymentTermCode).combobox('setValue', '');
    $(el.purchaseGroup).combobox('setValue', '');
    $(el.currencyCode).combobox('setValue', '');
    $(el.paymentExpireDateStart).datebox('setValue', '');
    $(el.paymentExpireDateEnd).datebox('setValue', '');
    searchAsData();
}

/**
 * 入库明细导出
 */
function detailExport() {

    var rows = $(el.tbDetails).edatagrid('getRows');
// // 遍历每一行数据，对金额字段进行四舍五入处理
//     $.each(rows, function(index, row) {
//         var
//             notTaxAmount = new BigNumber(0),
//             diffTaxAmount = new BigNumber(0),
//             taxAmount = new BigNumber(0);
//         if (row.notTaxAmount !== undefined && row.notTaxAmount !== null) {//对账未税金额 notTaxAmount 一致
//             row.notTaxAmount = notTaxAmount.plus(row.notTaxAmount).toFormat(2);
//         }
//         if (row.diffTaxAmount !== undefined && row.diffTaxAmount !== null) {//对账税额 diffTaxAmount 一致
//             row.diffTaxAmount = diffTaxAmount.plus(row.diffTaxAmount).toFormat(2);
//         }
//         if (row.taxAmount !== undefined && row.taxAmount !== null) {// 对账含税金额 taxAmount 一致
//             row.taxAmount = taxAmount.plus(row.taxAmount).toFormat(2);
//         }
//     });
//    // 对账含税金额  taxAmount  对账税额 diffTaxAmount
//
//     var footers = $(el.tbDetails).datagrid('getFooterRows');
//     var taxAmountSum = new BigNumber(0),
//         diffTaxAmountSum = new BigNumber(0);
//     var taxAmount = footers[0]['taxAmount'];
//     var diffTaxAmount = footers[0]['diffTaxAmount'];
//     footers[0]['taxAmount'] = taxAmountSum.plus(taxAmount).toFormat(2);
//     footers[0]['diffTaxAmount']= diffTaxAmountSum.plus(diffTaxAmount).toFormat(2);

    $(el.tbDetails).edatagrid('toExcel', {
        filename: '入库明细数据.xls',
        rows: rows,
        worksheet: '入库明细'
    });
}



/**
 * 删除
 */
function remove(){
    var rows = $(el.tbDetails).edatagrid('getSelections');
    if(rows.length === 0){
        topWin.layer.alert('请选中一条记录', {icon: 0});
        return false;
    }
    for(var i = 0; i < rows.length; i++){
        // el.removeList.push(rows[i].receiveCode+'_'+rows[i].receiveRowNo);
        el.removeList.push(rows[i].receiveId);
    }
    parent.layer.confirm('是否确认设置不参与？', function (index) {
        var queryParams = $(el.tbDetails).datagrid('options').queryParams;
        if (optType===1){
            queryParams.ppId = $(el.id).val();
            queryParams.removeLists = el.removeList.join(',');
            queryParams.factoryCode = $(el.factoryCode).combobox('getValue');
            $(el.tbDetails).datagrid('options').url = g.ctx + 'pc/finance/account/statement/detail/rest/find/by/statement/id/factoryCode';
            $(el.tbDetails).datagrid('load');
            parent.layer.close(index);
            if (el.filterFlag){
                $(el.tbDetails).datagrid('enableFilter');
                $('.datagrid-htable .datagrid-filter-c input').attr('AutoComplete','off')
            }
        }
        if (optType===0){
            var companyCode = $(el.companyCode).combobox('getValue'), factoryCode = $(el.factoryCode).combobox('getValue'), taxCode = $(el.taxCode).combobox('getValue'),
                inStockStartDate = $(el.inStockStartDate).datebox('getValue'), inStockEndDate = $(el.inStockEndDate).datebox('getValue'),
                currencyCode = $(el.currencyCode).combobox('getValue'), supplierCode = $(el.supplierCode).textbox('getValue'),
                poType = getTextByJs($(el.poType).combobox('getValues')),
                voucherType = $(el.voucherType).combobox('getValues'),
                purchaseGroup = $('#purchaseGroup').combobox('getValue');
            if(!supplierCode){
                topWin.layer.alert('请选择供应商信息', {icon: 0});
                return false;
            }

            if(!currencyCode){
                topWin.layer.alert('请选择币种', {icon: 0});
                return false;
            }

            if(!companyCode){
                topWin.layer.alert('请选择采购公司', {icon: 0});
                return false;
            }

            if(!factoryCode){
                topWin.layer.alert('请选择工厂', {icon: 0});
                return false;
            }

            if(!inStockStartDate){
                topWin.layer.alert('请选择入库开始时间', {icon: 0});
                return false;
            }

            if(!inStockEndDate){
                topWin.layer.alert('请选择入库结束时间', {icon: 0});
                return false;
            }
            if(!voucherType){
                topWin.layer.alert('请选择凭证类型', {icon: 0});
                return false;
            }
            if(!taxCode){
                topWin.layer.alert('请选择税率', {icon: 0});
                return false;
            }

            if(moment(inStockStartDate) > moment(inStockEndDate)){
                topWin.layer.alert('入库开始时间不能大于结束时间', {icon: 0});
                return false;
            }
            queryParams.supplierCode = supplierCode;
            if (Number(voucherType)===1){
                queryParams.companyCode = companyCode;
            }
            queryParams.factoryCode = factoryCode;
            queryParams.currencyCode = currencyCode;
            queryParams.postTimeStart = inStockStartDate;
            queryParams.postTimeEnd = inStockEndDate;
            // queryParams.purchaseGroup = purchaseGroup;
            queryParams.poTypes = poType;
            queryParams.receiveType = $(el.orderType).val();
            queryParams.taxCode = taxCode;
            if (Number(voucherType)===1||Number(voucherType)===2){
                queryParams.voucherTypes = voucherType+',3';
            }else {
                queryParams.voucherType = voucherType;
            }
            queryParams.removeLists = el.removeList.join(',');
            queryParams.businessFalg = businessFalg;
            // queryParams.paymentTermCode = $(el.paymentTermCode).val();
            queryParams.accountStatementFlag = 1;
            $(el.tbDetails).datagrid('options').loadFilter = pagerFilter;
            $(el.tbDetails).datagrid('options').url = g.ctx + 'pc/finance/receipt/voucher/rest/provide/create/statement';
            $(el.tbDetails).datagrid('load');
            parent.layer.close(index);
            if (el.filterFlag){
                $(el.tbDetails).datagrid('enableFilter');
                $('.datagrid-htable .datagrid-filter-c input').attr('AutoComplete','off')
            }
        }
    });
}

/**
 * 导入
 */
function importTaxPriceExcel() {
}

/**
 * 初始化页面输入框
 */
function initPageInput() {
    var isSupplier = $(el.isSupplier).val();
    var companyDataUrl = g.ctx + 'pc/sys/company/rest/listAll';


    //采购组
    $(el.purchaseGroup).combobox({
        required: false,
        editable: false,
        valueField: 'code',
        textField: 'codeWithDesc',
        limitToList: 'true',
        method: 'POST',
        prompt: '--- 请选择 ---',
        url: g.ctx + 'pc/sys/purchaseGroup/rest/listAll?isAuthority='+(Number(isSupplier) === 0?'1':''),
    });

    // 初始化公司代码下拉框
    $(el.companyCode).combobox({
        required: false,
        url: companyDataUrl,
        panelHeight: 'auto',
        valueField: 'companyCode',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        editable: false,
    });
    $(el.currencyCode).combobox({
        url: g.ctx + 'pc/sys/dict/getDicByType?type=currency',
        panelHeight: 'auto',
        limitToList: 'true',
        prompt: '-- 请选择 --',
        method: 'GET',
        valueField: 'code',
        textField: 'codeWithDesc',
        editable: false
    });


    // if (optType===0){
    //
    // }


    $(el.accountStatementYear).combobox({
        required: true,
        valueField: 'code',
        textField: 'name',
        limitToList: 'true',
        data: [
            {'name': moment().format('YYYY'), 'code': moment().format('YYYY')},
            {'name': moment().add(-12, 'month').format('YYYY'), 'code': moment().add(-12, 'month').format('YYYY')},
            {'name': moment().add(-24, 'month').format('YYYY'), 'code': moment().add(-24, 'month').format('YYYY')},
        ],
        editable: false,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
    });
    $(el.accountStatementMonth).combobox({
        required: true,
        valueField: 'code',
        textField: 'name',
        limitToList: 'true',
        data: [
            {'name': '01', 'code': '01'},
            {'name': '02', 'code': '02'},
            {'name': '03', 'code': '03'},
            {'name': '04', 'code': '04'},
            {'name': '05', 'code': '05'},
            {'name': '06', 'code': '06'},
            {'name': '07', 'code': '07'},
            {'name': '08', 'code': '08'},
            {'name': '09', 'code': '09'},
            {'name': '10', 'code': '10'},
            {'name': '11', 'code': '11'},
            {'name': '12', 'code': '12'},
        ],
        editable: false,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
    });

    // 采购组
    $(el.purchaseGroupCode).combobox({
        required: false,
        valueField: 'code',
        textField: 'codeWithDesc',
        method: 'POST',
        // panelHeight: 200,
        // panelWidth: 240,
        editable: false,
        panelHeight: 'auto',
        prompt: '--- 请选择 ---',
        url: g.ctx + 'pc/sys/purchaseGroup/rest/listAll',
        onChange: function (data) {
            var oriCc = $(el.purchaseGroupCode).combobox('getValue');
            if(oriCc !== data.code){
                clearPageTableData();
            }
        }
    });

    // 付款条件
    $(el.paymentTermCode).combobox({
        required: false,
        editable: false,
        panelHeight: '200',
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        method: 'GET',
        url: g.ctx + 'pc/sys/dict/getDicByType?type=payment_method',

    });
    // 付款方式
    $(el.paymentWay).combobox({
        required: false,
        editable: false,
        panelHeight: '200',
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        method: 'GET',
        url: g.ctx + 'pc/sys/dict/getDicByType?type=payment_way'
    });

}



/**

 /**
 * 主管确认
 *
 * @param callback 回调函数
 */
function purchaseSave(callback) {
    var id = $(el.id).val(), remark = $(el.remark).val(), taxAmount = $(el.taxAmount).textbox('getValue'),
        notTaxAmount = $(el.notTaxAmount).val(), deductionAmount = "",
        rebateAmount = "", approveOpinion = $(el.approveOpinion).val(),
        bpPayableBalance = "", bpEstimateBalance = "",
        etPayableBalance = "", etEstimateBalance = "",
        currPaymentAmount = "";
    if(!approveOpinion){
        topWin.layer.alert('请您输入审批意见', {icon: 0});
        return false;
    }
    // if(!remark){
    //     topWin.layer.alert('请您输入备注', {icon: 0});
    //     return false;
    // }


    var headData = {};
    headData.id = id;
    headData.taxAmount = Number(taxAmount.replace(/,/g,''));
    headData.notTaxAmount = Number(notTaxAmount.replace(/,/g,''));
    // headData.deductionAmount = deductionAmount;
    // headData.rebateAmount = rebateAmount;
    headData.remark = remark;
    headData.bpPayableBalance = Number(bpPayableBalance.replace(/,/g,''));
    headData.bpEstimateBalance = Number(bpEstimateBalance.replace(/,/g,''));
    headData.etPayableBalance = Number(etPayableBalance.replace(/,/g,''));
    headData.etEstimateBalance = Number(etEstimateBalance.replace(/,/g,''));
    headData.currPaymentAmount = Number(currPaymentAmount.replace(/,/g,''));

    // 对账单明细
    var detail = $(el.tbDetails).datagrid('getRows'),
        statementItem = [], dsiId = [], taxData = [],paymentTermCode =  [];
    if (detail.length === 0) {
        topWin.layer.alert('入库明细无数据, 请添加', {icon: 0});
        return false;
    }
    for(var i0 = 0; i0 < detail.length; i0++) {
        var ri = $(el.tbDetails).datagrid('getRowIndex', detail[i0]);
        $(el.tbDetails).datagrid('endEdit', ri);
    }

    var itSumAmount = new BigNumber(0);
    for(var i1 = 0; i1 < detail.length; i1++){
        var item = detail[i1];
        // 校验数量不能超过剩余可开票数量: 本次对账确认数量 <= 凭证可用数量
        if(Number(item.asQuantity) > Number(item.surplusNum)){
            topWin.layer.alert('入库凭证: ' + item.receiveCode + '#' + item.receiveRowNo + ', 填写的确认对账数量不能大于可用数量', {icon: 0});
            return false;
        }

        taxData.push(item.taxCode);
        paymentTermCode.push(item.paymentTermCode);
        statementItem.push(item);

        itSumAmount = itSumAmount.plus(item.taxAmount);
    }


    // 检查对账单明细中对账税率是否都相同
    if(!checkIsAllEqual(taxData)){
        topWin.layer.alert('对账单明细中税率不相同', {icon: 0});
        return false;
    }
    // 检查对账单明细中付款条件是否都相同  20240730 财务月底对账，暂不作校验
    if(!checkIsAllEqual(paymentTermCode)){
        //topWin.layer.alert('对账单明细中付款条件不相同', {icon: 0});
        //return false;
    }
    // 明细删除
    for(var i2 = 0; i2 < el.delDetail.length; i2++){
        dsiId.push(el.delDetail[i2].id);
    }

    var result = {};
    result.approveOpinion = approveOpinion;
    result.headData = headData;
    result.statementItem = statementItem;
    result.delSiIds = dsiId;
    callback(result);
}

/**
 * 数据保存
 *
 * @param callback 回调函数
 */
function financeSave(callback) {
    var id = $(el.id).val(), approveOpinion = $(el.approveOpinion).val(),
        bpPayableBalance = "", bpEstimateBalance = "",
        etPayableBalance = "", etEstimateBalance = "",
        currPaymentAmount = "";
    if(!approveOpinion){
        topWin.layer.alert('请输入审批意见', {icon: 0});
        return false;
    }

    var headData = {};
    headData.id = id;
    headData.bpPayableBalance = Number(bpPayableBalance.replace(/,/g,''));
    headData.bpEstimateBalance = Number(bpEstimateBalance.replace(/,/g,''));
    headData.etPayableBalance = Number(etPayableBalance.replace(/,/g,''));
    headData.etEstimateBalance = Number(etEstimateBalance.replace(/,/g,''));
    headData.currPaymentAmount = Number(currPaymentAmount.replace(/,/g,''));

    var result = {};
    result.approveOpinion = approveOpinion;
    result.headData = headData;
    result.statementItem = [];
    result.delSiIds = [];
    result.addDeductionIds = [];
    result.delDeductionIds = [];
    result.addRebateIds = [];
    result.delRebateIds = [];

    callback(result);
}

/**
 * 主管拒绝对账单
 *
 * @param callback 回调函数
 */
function purchaseRefuseStatement(callback) {
    var id = $(el.id).val(), remark = $(el.remark).val(), taxAmount = $(el.taxAmount).textbox('getValue'),
        notTaxAmount = $(el.notTaxAmount).val(), deductionAmount = "",
        rebateAmount = "", approveOpinion = $(el.approveOpinion).val();
    if(!approveOpinion){
        topWin.layer.alert('请您输入审批意见', {icon: 0});
        return false;
    }

    var headData = {};
    headData.id = id;
    headData.taxAmount = Number(taxAmount.replace(/,/g,''));
    headData.notTaxAmount = Number(notTaxAmount.replace(/,/g,''));
    // headData.deductionAmount = deductionAmount;
    // headData.rebateAmount = rebateAmount;
    headData.remark = remark;

    var result = {};
    result.approveOpinion = approveOpinion;
    result.headData = headData;
    result.statementItem = [];
    result.delSiIds = [];
    result.addDeductionIds = [];
    result.delDeductionIds = [];
    result.addRebateIds = [];
    result.delRebateIds = [];

    callback(result);
}

/**
 * 检查数组元素是否都相同
 *
 * @param array 待检查数组
 * @returns {boolean} 结果
 */
function checkIsAllEqual(array) {
    if (array.length > 0) {
        return !array.some(function (value, index) {
            return value !== array[0];
        });
    } else {
        return true;
    }
}

// 分页数据的操作
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;
}

function btnFilter() {
    // if (el.filterFlag){
    //     el.filterFlag = false;
    //     $(el.tbDetails).datagrid('disableFilter');
    // }else {
    //     el.filterFlag = true;
    //     $(el.tbDetails).datagrid('enableFilter');
    //     $('.datagrid-htable .datagrid-filter-c input').attr('AutoComplete','off')
    // }
}