/**
 * 对账模块-对账单新增页面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',
    paymentType: '#paymentType',


    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: [],
    currenyList: [],
    companyCodeList: [],
    purchaseGroupList: [],
    paymentMethodList: [],
    paymentWayList: [],
    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')

    debugger
    el.companyCodeList = getNecessaryDataList("pc/sys/company/rest/listAll");
    el.purchaseGroupList = getNecessaryDataList("pc/sys/purchaseGroup/rest/listAll");
    el.currenyList = getDictList("currency");
    el.paymentWayList = getDictList("payment_way");
    el.paymentMethodList = getDictList("payment_method");


    $(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);
    if (optType!==0){
        initTbApproveLog();
    }
});

var canEdit = true;

/**
 * 初始化入库明细表格
 */
function initTbDetails(column) {
    var dataDiv = $(el.dataDiv).outerHeight() + 90;
    var toolBar = [];
    debugger
    if (optType===1) {
        toolBar.push(
            {
                text: '添加',
                iconCls: 'icon-add',
                handler: function () {
                    addInvoiceItem();
                }
            },
            '-',
            {
                text: '删除',
                iconCls: 'icon-remove',
                handler: function () {
                    delInvoiceItem(1);
                }
            },
            '-',
            {
                text: '恢复删除',
                iconCls: 'icon-remove',
                handler: function () {
                    delInvoiceItem(0);
                }
            },
            '-',
            {
                text: '提交',
                iconCls: 'icon-save',
                handler: function () {
                    submitPaymentDetail();
                }
            },
            '-',
            {
                text: '保存',
                iconCls: 'icon-ok',
                handler: function () {
                    savePaymentDetail(2);
                }
            },
            '-',
            {
                text: '导出',
                iconCls: 'icon-print',
                handler: function () {
                    gysgl_derive();
                }
            },
            '-',
            {
                text: '导入',
                iconCls: 'icon-import',
                handler: function () {
                    gysgl_upload();
                }
            },
        )
    } else if (optType===2) {
        toolBar.push(
            {
                text: '导出',
                iconCls: 'icon-print',
                handler: function () {
                    gysgl_derive();
                }
            },
        )
    }
    var frozenColumns = [
        {
            field: 'ck',
            checkbox: true
        },
        {
            field: 'deleteFlag',
            title: '删除标记',
            width: 70,
            formatter: function (value) {
                if (value ===1) {
                    return '<span style="color: red;">已删除</span>';
                }else {
                    return "未删除";
                }
            }
        },

        {
            field: 'status',
            title: '数据状态',
            width: 95,
            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 '';
                }
            }
        }
    ]

    var columns = [

        {
            field: 'paymentPlanNo',
            title: '付款计划单号',
            width: 110,
            sortable: true
        },
        {
            field: 'paymentPlanDetailNo',
            title: '付款计划明细行号',
            width: 140,
            sortable: true
        },
        {
            field: 'accountStatementNo',
            title: '对账单号',
            width: 90,
            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 supplierDialogElement2 = openDialog("supplierDialog2", g.ctx + "pc/finance/account/statement/chose/statement/dialog?single=1", {
                                title: "对账单选择",
                                width: '80%',
                                height: '70%',
                                cache: false,
                                modal: true,
                                border: 'thin',
                                draggable: false,
                                shadow: false,
                                onClose: function () {
                                    supplierDialogElement2.dialog('destroy');
                                },
                                buttons: [{
                                    text: '选择', iconCls: 'icon-accept', handler: function () {
                                        topWin.frames['supplierDialog2'].confirmChose(function (selectrow) {
                                            supplierDialogElement2.dialog('close');

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

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

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

                                            let paymentType = $("#tbDetails").edatagrid('getEditor', {
                                                index: editor, field: 'paymentType'
                                            }).target;
                                            paymentType.combobox("setValue", "D");
                                            $(paymentType.target).textbox("readonly", true);

                                            let supplierCode = $("#tbDetails").edatagrid('getEditor', {
                                                index: editor, field: 'supplierCode'
                                            }).target;
                                            supplierCode.textbox("setValue", selectrow.supplierCode);
                                            $(supplierCode.target).textbox("readonly", true);
                                            let supplierName = $("#tbDetails").edatagrid('getEditor', {
                                                index: editor, field: 'supplierName'
                                            }).target;
                                            supplierName.textbox("setValue", selectrow.supplierName);
                                            $(supplierName.target).textbox("readonly", true);
                                            let purchaseGroup = $("#tbDetails").edatagrid('getEditor', {
                                                index: editor, field: 'purchaseGroup'
                                            }).target;
                                            purchaseGroup.combobox("setValue", selectrow.purchaseGroup);
                                            $(purchaseGroup.target).textbox("readonly", true);
                                            let paymentWay = $("#tbDetails").edatagrid('getEditor', {
                                                index: editor, field: 'paymentWay'
                                            }).target;
                                            paymentWay.combobox("setValue", selectrow.paymentWay);
                                            // $(paymentWay.target).textbox("readonly", true);
                                            let paymentTermCode = $("#tbDetails").edatagrid('getEditor', {
                                                index: editor, field: 'paymentTermCode'
                                            }).target;
                                            paymentTermCode.combobox("setValue", selectrow.paymentTermCode);
                                            $(paymentTermCode.target).textbox("readonly", true);
                                            let currencyCode = $("#tbDetails").edatagrid('getEditor', {
                                                index: editor, field: 'currencyCode'
                                            }).target;
                                            currencyCode.combobox("setValue", selectrow.currencyCode);
                                            $(currencyCode.target).textbox("readonly", true);

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

                                        });
                                    }
                                }, {
                                        text: '关闭', iconCls: 'icon-cancel', handler: function () {
                                            supplierDialogElement2.dialog('close');
                                        }

                                }]
                            })
                        }
                    }]
                }
            }
            // editor: {
            //     type: 'textbox', options: {
            //         required: false, editable: false, icons: [{
            //             iconCls: 'icon-search', handler: function () {
            //                     var url = g.ctx + "pc/finance/account/statement/chose/statement/dialog?single=1";
            //                     var choseAccountStatement = openDialog('accountStatementDialog', url, {
            //                         title: '对账单选择',
            //                         width: '80%',
            //                         height: '70%',
            //                         cache: false,
            //                         modal: true,
            //                         border: 'thin',
            //                         draggable: false,
            //                         shadow: false,
            //                         onClose: function () {
            //                             choseAccountStatement.dialog('destroy');
            //                         },
            //                         buttons: [
            //                             {
            //                                 text: '选择',
            //                                 iconCls: 'icon-accept',
            //                                 handler: function () {
            //
            //                                     topWin.frames['accountStatementDialog'].chooseRow(function (selectrow) {
            //                                         choseAccountStatement.dialog('close');
            //
            //                                         let accountStatementNo = $("#tbDetails").edatagrid('getEditor', {
            //                                             index: editor, field: 'accountStatementNo'
            //                                         }).target;
            //                                         accountStatementNo.textbox("setValue", selectrow[0].accountStatementNo);
            //
            //                                         let supplierCode = $("#tbDetails").edatagrid('getEditor', {
            //                                             index: editor, field: 'supplierCode'
            //                                         }).target;
            //                                         supplierCode.textbox("setValue", selectrow[0].supplierCode);
            //                                         let supplierName = $("#tbDetails").edatagrid('getEditor', {
            //                                             index: editor, field: 'supplierName'
            //                                         }).target;
            //                                         supplierName.textbox("setValue", selectrow[0].supplierName);
            //                                         let purchaseGroup = $("#tbDetails").edatagrid('getEditor', {
            //                                             index: editor, field: 'purchaseGroup'
            //                                         }).target;
            //                                         purchaseGroup.combobox("setValue", selectrow[0].purchaseGroupCode);
            //                                         let paymentWay = $("#tbDetails").edatagrid('getEditor', {
            //                                             index: editor, field: 'paymentWay'
            //                                         }).target;
            //                                         paymentWay.combobox("setValue", selectrow[0].paymentMethod);
            //                                         let paymentTermCode = $("#tbDetails").edatagrid('getEditor', {
            //                                             index: editor, field: 'paymentTermCode'
            //                                         }).target;
            //                                         paymentTermCode.combobox("setValue", selectrow[0].paymentTerms);
            //                                         let currencyCode = $("#tbDetails").edatagrid('getEditor', {
            //                                             index: editor, field: 'currencyCode'
            //                                         }).target;
            //                                         currencyCode.combobox("setValue", selectrow[0].currencyCode);
            //
            //                                         let companyCode = $("#tbDetails").edatagrid('getEditor', {
            //                                             index: editor, field: 'companyCode'
            //                                         }).target;
            //                                         companyCode.combobox("setValue", selectrow[0].companyCode);
            //                                     });
            //
            //
            //
            //
            //                                     //     $(el.supplierCode).val(data.supplierCode);
            //                                     //     $(el.accountStatementId).val(data.id);
            //
            //                                         // $(el.accountStatementNo).textbox('setValue',data.accountStatementNo);
            //                                         // $(el.supplierName).textbox('setValue',data.supplierName);
            //                                         // $(el.companyCode).combobox( 'setValue', data.companyCode);
            //                                         // $(el.currencyCode).textbox('setValue',data.currencyCode);
            //                                         // $(el.purchaseGroup).combobox('setValue',data.purchaseGroup);
            //                                         // $(el.paymentWay).combobox('setValue',data.paymentWay);
            //                                         // $(el.invoiceTaxAmount).textbox('setValue',new BigNumber(data.taxAmount).decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN));
            //                                         // $(el.invoiceNetAmount).textbox('setValue',new BigNumber(data.notTaxAmount).decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN));
            //                                         // $(el.diffAmount).textbox('setValue',new BigNumber(data.taxAmount).minus(new BigNumber(data.notTaxAmount)).decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN));
            //                                         // el.supplierCurrencyCode = data.currencyCode;
            //                                         // findStatementDetail();
            //                                         // findAdvanceDetail();
            //                                 }
            //                             },
            //                             {
            //                                 text: '关闭',
            //                                 iconCls: 'icon-cancel',
            //                                 handler: function () {
            //                                     choseAccountStatement.dialog('close');
            //                                 }
            //                             }
            //                         ]
            //                     })
            //
            //
            //
            //
            //             }
            //         }]
            //     }
            // }
        },
        {
            field: 'supplierCode',
            title: '供应商编码',
            width: 60,
            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/purchaseCategory/page/selector?single=1", {
                                title: "供应商选择",
                                width: '80%',
                                height: '70%',
                                cache: false,
                                modal: true,
                                border: 'thin',
                                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');
                                            let supplierCode = $("#tbDetails").edatagrid('getEditor', {
                                                index: editor, field: 'supplierCode'
                                            }).target;
                                            supplierCode.textbox("setValue", selectrow[0].supplierCode);
                                            let supplierName = $("#tbDetails").edatagrid('getEditor', {
                                                index: editor, field: 'supplierName'
                                            }).target;
                                            supplierName.textbox("setValue", selectrow[0].supplierName);
                                            let purchaseGroup = $("#tbDetails").edatagrid('getEditor', {
                                                index: editor, field: 'purchaseGroup'
                                            }).target;
                                            purchaseGroup.combobox("setValue", selectrow[0].purchaseGroupCode);
                                            let paymentWay = $("#tbDetails").edatagrid('getEditor', {
                                                index: editor, field: 'paymentWay'
                                            }).target;
                                            paymentWay.combobox("setValue", selectrow[0].paymentMethod);
                                            let paymentTermCode = $("#tbDetails").edatagrid('getEditor', {
                                                index: editor, field: 'paymentTermCode'
                                            }).target;
                                            paymentTermCode.combobox("setValue", selectrow[0].paymentTerms);
                                            let currencyCode = $("#tbDetails").edatagrid('getEditor', {
                                                index: editor, field: 'currencyCode'
                                            }).target;
                                            currencyCode.combobox("setValue", selectrow[0].currencyCode);

                                            let companyCode = $("#tbDetails").edatagrid('getEditor', {
                                                index: editor, field: 'companyCode'
                                            }).target;
                                            companyCode.combobox("setValue", selectrow[0].companyCode);
                                            endInvoiceEditor();
                                        });
                                    }
                                }, {
                                    text: '关闭', iconCls: 'icon-cancel', handler: function () {
                                        supplierDialogElement.dialog('close');
                                    }
                                }]
                            })
                        }
                    }]
                }
            }
        },
        {
            field: 'supplierName',
            title: '供应商全称',
            width: 240,
            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',
                    data: el.companyCodeList,
                    valueField: 'companyCode',
                    textField: 'codeWithDesc',
                    limitToList: 'false',
                    // prompt: '-- 请选择 --',
                    required: true,
                    // method: 'GET',
                    editable: false,
                    panelHeight: 150
                }
            }
        },
        {
            field: 'paymentType',
            title: '类型',
            width: 100,
            sortable: true,
            formatter: function (value) {
                switch (value) {
                    case 'D':
                        return '对账款';
                    case 'S':
                        return '预付款';
                    default:
                        return '对账款';
                }
            },
            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,
                    required: true,
                    valueField: 'dicId',
                    textField: 'dicTxt',
                    panelHeight: 'auto',
                    data: [
                        {dicTxt: '对账款', dicId: "D"},
                        {dicTxt: '预付款', dicId: "S"}
                    ],
                }
            }
        },
        {
            field: 'currencyCode',
            title: '币种',
            width: 140,
            sortable: true,
            formatter: function (value) {
                return getDicName('currency',value)
            },
            editor: {
                type: 'combobox',
                options: {
                    data: el.currenyList,
                    // url: g.ctx + 'pc/sys/dict/getDicByType?type=currency',
                    valueField: 'code',
                    textField: 'codeWithDesc',
                    limitToList: 'true',
                    // prompt: '-- 请选择 --',
                    required: true,
                    // method: 'GET',
                    editable: false,
                    panelHeight: 150
                }
            }
        },
        {
            field: 'actualPayAmount',
            title: '应付金额',
            width: 90,
            sortable: true,
            formatter: function (value) {
                return formatterCustomPrice(value,2,true,false)
            },
            editor: {
                type: 'numberbox',
                options: {
                    // min: 0,
                    precision: 2,
                    // onChange: function (nv, ov) {
                    //     if(ov){
                    //         updateRowData(nv, 'taxAmount');
                    //     }
                    // }
                }
            }
        },
        {
            field: 'appliedUnpaidAmount',
            title: '已请款未付金额(历史)',
            width: 160,
            sortable: true,
            formatter: function (value) {
                return formatterCustomPrice(value,2,true,false)
            }
        },
        {
            field: 'accountStatementYear',
            title: '对账单年份',
            width: 100,
            sortable: true,
            // formatter: function (value,row,index) {
            //     if (row.id > 0) {
            //         return value;
            //     } else {
            //         if (value) {
            //
            //         } e
            //         return '<input type="text" value="">'; // 显示编辑图标
            //     }
            // }
            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',
                    data: el.paymentMethodList,
                    valueField: 'code',
                    textField: 'codeWithDesc',
                    limitToList: 'true',
                    // prompt: '-- 请选择 --',
                    required: true,
                    // 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',
                    data: el.paymentWayList,
                    valueField: 'code',
                    textField: 'codeWithDesc',
                    limitToList: 'true',
                    // prompt: '-- 请选择 --',
                    required: true,
                    // 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',
                    data: el.purchaseGroupList,
                    valueField: 'code',
                    textField: 'codeWithDesc',
                    limitToList: 'true',
                    // prompt: '-- 请选择 --',
                    required: true,
                    // 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: 'createUserName',
            title: '创建人',
            width: 100
        } ,
        {
            field: 'createTime',
            title: '创建时间',
            width: 120,
            sortable: true,
            exportDateFormatter:'date',
            formatter: function (value, row) {
                if (!value) {
                    return '';
                }
                return '<span>' + moment(value).format('YYYY-MM-DD') + '</span>';
            }
        }
    ];
    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()),
                status: $("#status2").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: [
                frozenColumns
            ],
            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 (inx,row) {
                // initFileForm('invoice-file-form');
                // optType === 1 编辑， optType == 5 采购审批，只允许编辑两列
                debugger
                if (optType===1){
                    if (editor && editor === inx) {
                        return;
                    }
                    endInvoiceEditor();
                    //判断如果付款计划明细ID大于0，且新增标识不为X 则不允许编辑
                    $(el.tbDetails).edatagrid('editRow', inx);
                    editor = inx;
                    var eValue = $(el.tbDetails).edatagrid('getEditor', { index: inx, field: 'accountStatementNo' });
                    var vvvv = eValue.oldHtml;

                    var ed21 = $(el.tbDetails).edatagrid('getEditor', { index: inx, field: 'paymentPlanYear' });
                    $(ed21.target).textbox("readonly",true);
                    var ed22 = $(el.tbDetails).edatagrid('getEditor', { index: inx, field: 'paymentPlanMonth' });
                    $(ed22.target).textbox("readonly",true);
                    // if ((row.id > 0 && (!row.newSign || row.newSign !== 'X')) || vvvv) {
                    if (row.id > 0 || vvvv) {
                        var ed2 = $(el.tbDetails).edatagrid('getEditor', { index: inx, field: 'companyCode' });
                        if (ed2) {
                            $(ed2.target).textbox("readonly",true);
                        }
                        var ed3 = $(el.tbDetails).edatagrid('getEditor', { index: inx, field: 'supplierCode' });
                        if (ed3) {
                            $(ed3.target).textbox("readonly",true);
                        }
                        var ed4 = $(el.tbDetails).edatagrid('getEditor', { index: inx, field: 'paymentTermCode' });
                        if (ed4) {
                            $(ed4.target).textbox("readonly",true);
                        }
                        var ed5 = $(el.tbDetails).edatagrid('getEditor', { index: inx, field: 'currencyCode' });
                        if (ed5) {
                            $(ed5.target).textbox("readonly",true);
                        }
                        var ed6 = $(el.tbDetails).edatagrid('getEditor', { index: inx, field: 'paymentWay' });
                        if (ed6) {
                            // $(ed6.target).textbox("readonly",true);
                        }
                        var ed7 = $(el.tbDetails).edatagrid('getEditor', { index: inx, field: 'purchaseGroup' });
                        if (ed7) {
                            $(ed7.target).textbox("readonly",true);
                        }
                        var ed11 = $(el.tbDetails).edatagrid('getEditor', { index: inx, field: 'accountStatementYear' });
                        $(ed11.target).textbox("readonly",true);
                        var ed12 = $(el.tbDetails).edatagrid('getEditor', { index: inx, field: 'accountStatementMonth' });
                        $(ed12.target).textbox("readonly",true);
                        var ed13 = $(el.tbDetails).edatagrid('getEditor', { index: inx, field: 'paymentType' });
                        if (ed13) {
                            $(ed13.target).textbox("readonly",true);
                        }
                        canEdit = false;
                        // endInvoiceEditor();
                    } else {
                        canEdit = true;
                    }

                    if (row.id > 0 && vvvv) {
                    // if ((row.id > 0 && (!row.newSign || row.newSign !== 'X'))) {
                        var ed9 = $(el.tbDetails).edatagrid('getEditor', { index: inx, field: 'accountStatementNo' });
                        $(ed9.target).textbox("readonly",true);
                        canEdit = false;
                        // endInvoiceEditor();
                    }

                    debugger
                    // var row = $(el.tbDetails).edatagrid('getRows')[editor];
                }
            },
            // clickCell: function (index, field, value) {
            //     $(el.tbDetails).edatagrid('editRow', inx);
            //             page.replyDetailGrid.datagrid('selectRow', index).datagrid('beginEdit', index);
            //             var ed = page.replyDetailGrid.datagrid('getEditor', {index: index, field: field});
            //             if (ed) {
            //                 ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
            //             }
            //             page.editIndex = index;
            //
            // },

            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');
                // }

            },
            // 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,
        // accountStatementYear: $(el.paymentPlanYear).val(),
        // accountStatementMonth: $(el.paymentPlanMonth).val(),
        paymentPlanYear: $(el.paymentPlanYear).val(),
        paymentPlanMonth: $(el.paymentPlanMonth).val(),
        // paymentType: $(el.paymentType).val()

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

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

function delInvoiceItem(deltype) {
    endInvoiceEditor();
    var rows = $(el.tbDetails).edatagrid('getSelections');
    if (rows.length<=0) {
        layer.msg("请选择您要删除的付款计划明细信息");
        return;
    }
    var delIds = [];
    var isSave = false;
    for (var i = 0; i < rows.length; i++) {
        if (rows[i].deleteFlag === 1 && deltype === 1) {
            layer.msg("已经删除的付款计划明细数据不能在删除");
            return;
        }
        if (rows[i].id ===0 && deltype === 1) {
            // var rowIndex = $(el.tbDetails).edatagrid('getRowIndex', i);
            var item = rows[i];
            var rowIndex = $(el.tbDetails).edatagrid('getRowIndex', item);
            $(el.tbDetails).edatagrid('deleteRow', rowIndex);
            continue;
        } else {
            if (rows[i].accountStatementNo && deltype === 1 && (!rows[i].remark || rows[i].remark === '')) {
                layer.msg("请输入删除原因.");
                return;
            }
            if (deltype === 1 && (!rows[i].remark || rows[i].remark === '')) {
                layer.msg("请输入删除原因.");
                return;
            }

            if (deltype === 1 && (rows[i].remark && rows[i].remark !== '')) {
                isSave = true;
            }


            if (rows[i].deleteFlag === 0 && deltype === 0) {
                layer.msg("未删除的数据不能恢复删除");
                return;
            }
            if (rows[i].id ===0 && deltype === 0) {
                layer.msg("未保存的数据不能恢复删除");
                return;
            }
            delIds.push(rows[i].id);
        }
    }
    if (delIds.length === 0) {
        return;
    }
    var conStr = "确定删除已选中的付款计划明细?";
    if (deltype === 0) {
        conStr = "确定恢复已选中的删除数据?";
    }
    topWin.layer.confirm(conStr, {icon: 3}, function (index) {
        let loadIndex = topWin.layer.load(0);
        if (deltype === 1 && isSave) {
            savePaymentDetail(1);
            topWin.layer.close(loadIndex);
            return;
        }
        // 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 () {
                if (deltype === 0) {
                    topWin.layer.msg('恢复成功');
                } else {
                    topWin.layer.msg('删除成功');
                }
                topWin.layer.close(loadIndex);
                $(el.tbDetails).edatagrid('reload');
            },
            error: function (data) {
                topWin.layer.close(loadIndex);
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    })
}

/**
 * 数据导出
 */
function gysgl_derive() {
    var params = getQuery();
    // params.ppId = id;
    var tableData = getExcelKeyTitle("tbDetails");
    xhrPostExport('pc/finance/payment/plan/detail/rest/exportPaymentPlanDetailData',  params,tableData)
}


function gysgl_upload() {
    // $(el.tbDetails).edatagrid("saveRow")
    // endInvoiceEditor();
    $("#detailUpload .filebox-label").click();
}

/**
 * 数据导入回调
 */
function dataImport() {
    var files = $("#detailFileInput").filebox('files'), formData = new FormData();
    if (files.length != 1) {
        return
    }
    formData.append('file', files[0]);
    let loadIndex = topWin.layer.load(0);
    var url = g.ctx + 'pc/finance/payment/plan/detail/rest/importPaymentPlanDetail'
    $.ajax({
        url: url, type: 'POST', data: formData, processData: false,
        contentType: false,
        async: true, // 设置为同步请求
        complete: function () {
            $("#detailFileInput").filebox('clear')
            topWin.layer.close(loadIndex);
        },
        success: function (data) {
            // topWin.layer.msg("导入成功", {icon: 1});
            // topWin.layer.msg(data, {icon: 1});
            topWin.layer.alert(data, {icon: 1});
            $(el.tbDetails).datagrid("reload")
        }, error: function (data) {
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });
}


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('提交成功');
                topWin.layer.close(loadIndex);
                $(el.tbDetails).edatagrid("reload")
            },
            error: function (data) {
                topWin.layer.close(loadIndex);
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    })
}

function checkDataSave(type,callback) {
    endInvoiceEditor();
    // var rows = $(el.tbDetails).edatagrid('getSelections');
    var rows = $(el.tbDetails).datagrid('getRows');
    var isExit = false;
    for (let i = 0 ; i < rows.length ; i ++) {
        var item = rows[i];
        if (item.id === 0) {
            isExit = true;
        }
    }
    if(isExit === true) {
        topWin.layer.confirm("有新增未保存的数据是否继续退出?", {icon: 3}, function (index) {
            callback();
        });
    } else {
        callback();
    }
}

function savePaymentDetail(type) {
    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 (type !==1) {
            if (!item.supplierCode || !item.supplierName) {
                layer.msg("请选择供应商");
                return;
            }

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

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

            if (!item.purchaseGroup) {
                layer.msg("请选择采购组");
                return;
            }
            //负数的也可以新增，有冲销
            if (!item.actualPayAmount || item.actualPayAmount == 0) {
                layer.msg("请填写应付金额");
                return;
            }
            if (item.accountStatementNo) {
                if (!item.accountStatementYear || !item.accountStatementMonth) {
                    layer.msg("请填写对账单年月");
                    return;
                }
            } else {
                if (item.accountStatementYear || item.accountStatementMonth) {
                    layer.msg("请不要填写对账单年月");
                    return;
                }
            }


            if (!item.paymentExpireDate) {
                layer.msg("付款到期日不能为空");
                return;
            }
        }

        // obj.deleteFlag = 0;
        // obj.status = 0;
        obj.id = item.id;
        obj.remark = item.remark;
        //删除操作时，保存删除的原因，如果id为0，则不需要保存。因为执行的是删除操作
        if (type === 1 && item.id !== 0) {
            obj.deleteFlag = -1;
            statementItem.push(obj);

        } else if(type === 2) {
            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.paymentType = item.paymentType;//明细类型
            obj.purchaseGroup = item.purchaseGroup;//采购组编码
            obj.paymentPlanWeek = item.paymentPlanWeek;//付款计划周(对账单上付款到期日所在周)
            obj.paymentExpireDate = item.paymentExpireDate;//付款到期日
            obj.paymentPlanDetailNo = item.paymentPlanDetailNo;
            obj.accountStatementYear = item.accountStatementYear;
            obj.accountStatementMonth = item.accountStatementMonth;
            obj.accountStatementNo = item.accountStatementNo;
            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);
            if (type === 1) {
                topWin.layer.alert('数据删除成功', {icon: 1});
            } else {
                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 = optType1;
    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/payment/plan/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).datagrid('options').queryParams = getQuery();
    $(el.tbDetails).datagrid('load');
}

function getQuery() {
    var queryParams = $(el.tbDetails).datagrid('options').queryParams;
    queryParams.ppId = $(el.id).val();
    queryParams.supCodeOrName = $.trim($(el.supCodeOrName).val());
    queryParams.status = $("#status2").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('');
    $("#status2").val("-1");
    $(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 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
    });

    $(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 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() {
}