/**
 * 对账模块-对账单新增页面JS
 *
 * Created by li.kui on 2020/8/1.
 */
'use strict';
var el = {
    dataPanel: '#dataPanel',
    dataDiv: '#dataDiv',
    id: '#id',
    files: '#files',
    orderType: '#orderType',
    isSupplier: '#isSupplier',
    supplierCode: '#supplierCode',
    supplierName: '#supplierName',
    companyCode: '#companyCode',
    companyName: '#companyName',
    factoryCode: '#factoryCode',
    factoryName: '#factoryName',
    deductionAmount: '#deductionAmount',
    rebateAmount: '#rebateAmount',
    inStockStartDate: '#inStockStartDate',
    inStockEndDate: '#inStockEndDate',
    accountStatementNo: '#accountStatementNo',
    bpPayableBalance: '#bpPayableBalance',
    bpEstimateBalance: '#bpEstimateBalance',
    etPayableBalance: '#etPayableBalance',
    etEstimateBalance: '#etEstimateBalance',
    beginPeriodTotal: '#beginPeriodTotal',
    tbApproveLog: '#tbApproveLog',
    endPeriodTotal: '#endPeriodTotal',
    currPaymentAmount: '#currPaymentAmount',
    notTaxAmount: '#notTaxAmount',
    approveOpinion: '#approveOpinion',
    taxAmount: '#taxAmount',
    delDetail : [],
    currencyCode: '#currencyCode',
    remark: '#remark',
    dataTabs: '#dataTabs',
    tbDetails: '#tbDetails',
    tbDeduction: '#tbDeduction',
    tbRebate: '#tbRebate',
    localCurrency : '#localCurrency',
    originalCurrency: '#originalCurrency',
    advanceLocalCurrency: '#advanceLocalCurrency',
    advanceOriginalCurrency: '#advanceOriginalCurrency',
    invoiceFileInput: '#invoiceFileInput',
    fileId: '#fileId',
    voucherType: '#voucherType',
    taxCode: '#taxCode',
    paymentTermDesc: '#paymentTermDesc',
    paymentTermCode: '#paymentTermCode',
    purchaseGroup: '#purchaseGroup',
    poType: '#poType',
    choseSupplierDialog: null,
    choseRebateDataDialog: null,
    userTableColumn: [],
    bodyHeight: document.documentElement.clientHeight
};

/**
 * 文档就绪
 */
$(function () {
    initDict('payment_method,po_type,unit,businessFileType')
    initNecessaryDatas('pc/sys/tax/rest/listAll')
    $(el.dataPanel).panel({
        collapsible: true,
        onCollapse: function () {
            $(el.dataTabs).tabs('select', 0);

            $(el.tbDetails).datagrid('resize', {height: el.bodyHeight - 80});
            if (optType!==0){
                $(el.tbApproveLog).datagrid('resize', {height: el.bodyHeight - 80});
            }
            // $(el.tbRebate).datagrid('resize', {height: el.bodyHeight - 80});
            // $(el.tbDeduction).datagrid('resize', {height: el.bodyHeight - 80});
        },
        onExpand: function () {
            $(el.dataTabs).tabs('select', 0);

            var dataDiv = $(el.dataDiv).outerHeight() + 90;
            $(el.tbDetails).datagrid('resize', {height: el.bodyHeight - dataDiv});
            if (optType!==0){
                $(el.tbApproveLog).datagrid('resize', {height: el.bodyHeight - dataDiv});
            }
            // $(el.tbRebate).datagrid('resize', {height: el.bodyHeight - dataDiv});
            // $(el.tbDeduction).datagrid('resize', {height: el.bodyHeight - dataDiv});
        }
    });

    // 获取当前用户在本页面中表格列配置
    // findUserTableColumn();

    // 加载页面输入或下拉框数据
    initPageInput();

    initTbDetails();
    if (optType!==0){
        initTbApproveLog();
    }
    // initTbDeduction();
    // initTbRebate();
});

/**
 * 初始化入库明细表格
 */
function initTbDetails() {
    var dataDiv = $(el.dataDiv).outerHeight() + 90, orderType = $(el.orderType).val();
    // var columns = dynamicColumns(orderType);
    var toolBar = [];
    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('getValues'),
                        purchaseGroup = $('#purchaseGroup').combobox('getValue');
                    getVoucherData(companyCode, factoryCode, supplierCode, currencyCode, inStockStartDate, inStockEndDate,purchaseGroup,poType,taxCode,voucherType);
                }
            },
            '-',
            {
                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();
                }
            }
        )
    }else if (optType===1){
        toolBar.push(
            {
                text: '添加',
                iconCls: 'icon-add',
                handler: function () {
                    addVoucherData();
                }
            },
            '-',
            {
                text: '删除',
                iconCls: 'icon-remove',
                handler: function () {
                    delStatementItem();
                }
            },
            '-',
            {
                text: '导出',
                iconCls: 'icon-download',
                handler: function () {
                    detailExport();
                }
            },
            '-',
            {
                text: '填充应付未清金额',
                iconCls: 'icon-ok',
                handler: function () {
                    payableOutstanding();
                }
            }
        )
    }else if (optType===2){
        toolBar.push(
            {
                text: '导出',
                iconCls: 'icon-download',
                handler: function () {
                    detailExport();
                }
            }
        )
    }
    $(el.tbDetails).datagrid({
        loadMsg: '数据加载中, 请耐心等待......',
        url: g.ctx + 'pc/finance/account/statement/detail/rest/find/by/statement/id',
        height: el.bodyHeight - dataDiv,
        singleSelect: false,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        remoteSort: false,
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: false,
        showFooter: true,
        queryParams: {
            asId: $(el.id).val()
        },
        frozenColumns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                }
            ]
        ],
        columns: [
            [
                {
                    field: 'deleteFlag',
                    title: '删除标记',
                    width: 80,
                    formatter: function (value) {
                        if (value ===1) {
                            return '<span style="color: red;">已删除</span>';
                        }else {
                            return "未删除";
                        }
                    }
                },
                {
                    field: 'zlsdh',
                    title: 'SC订单号',
                    width: 90,
                    sortable: true
                },
                {
                    field: 'poCode',
                    title: 'SAP订单号',
                    width: 90,
                    sortable: true
                },
                {
                    field: 'receiveRowNo',
                    title: '行号',
                    width: 60,
                    sortable: true
                },
                {
                    field: 'receiveDate',
                    title: '入库日期',
                    width: 110,
                    sortable: true
                },
                {
                    field: 'materialCode',
                    title: '物料编码',
                    width: 90,
                    sortable: true
                },
                {
                    field: 'materialName',
                    title: '物料名称',
                    width: 180,
                    sortable: true
                },
                {
                    field: 'specs',
                    title: '规格',
                    width: 120
                },

                {
                    field: 'receiveNum',
                    title: '入库数量',
                    width: 70,
                    sortable: true,
                    formatter: function (value) {
                        if (value < 0) {
                            return '<span style="color: red;">' + value + '</span>';
                        }else {
                            return value;
                        }
                    }
                },
                {
                    field: 'materialUnit',
                    title: '单位',
                    width: 70,
                    sortable: true,
                    formatter: function (value) {
                        return getDicName('unit')
                    }
                },
                {
                    field: 'orderTaxPrice',
                    title: '订单含税单价',
                    width: 90,
                    sortable: true
                },

                {
                    field: 'poItemNo',
                    title: '订单行号',
                    width: 70,
                    sortable: true
                },

                {
                    field: 'paymentTermCode',
                    title: '付款条件',
                    width: 200,
                    sortable: true,
                    formatter: function (value) {
                        return getDicName('payment_method')
                    }
                },
                {
                    field: 'inOutFlag',
                    title: '出入库标识',
                    width: 85,
                    sortable: true
                },
                {
                    field: 'receiveCode',
                    title: '入库凭证',
                    width: 90,
                    sortable: true
                },
                {
                    field: 'itemNo',
                    title: '对账单行号',
                    width: 80,
                    sortable: true
                },
                {
                    field: 'asQuantity',
                    title: '本次对账数量',
                    width: 100,
                    sortable: true,
                    formatter: function (value) {
                        if (value < 0) {
                            return '<span style="color: red;">' + value + '</span>';
                        }else {
                            return value;
                        }
                    }
                },
                {
                    field: 'notTaxPrice',
                    title: '未税单价',
                    width: 70,
                    sortable: true
                },
                {
                    field: 'orderNotTaxPrice',
                    title: '订单未税单价',
                    width: 90,
                    sortable: true
                },
                {
                    field: 'taxAmount',
                    title: '对账含税金额',
                    width: 100,
                    sortable: true,
                    formatter: function (value) {
                        if (value < 0) {
                            return '<span style="color: red;">' + formatNumber(value, 2, 1) + '</span>';
                        }else {
                            return formatNumber(value, 2, 1);
                        }
                    }
                },
                {
                    field: 'diffTaxAmount',
                    title: '对账税额',
                    width: 90,
                    sortable: true,
                    formatter: function (value) {
                        if (!value) {
                            return '';
                        }
                        return formatNumber(value, 2, 1);
                    }
                },
                {
                    field: 'notTaxAmount',
                    title: '对账未税金额',
                    width: 100,
                    sortable: true,
                    formatter: function (value) {
                        if (value < 0) {
                            return '<span style="color: red;">' + formatNumber(value, 2, 1) + '</span>';
                        }else {
                            return formatNumber(value, 2, 1);
                        }
                    }
                },
                {
                    field: 'taxPrice',
                    title: '对账含税单价',
                    width: 90,
                    sortable: true
                },
                {
                    field: 'poType',
                    title: '订单类型名称',
                    width: 100,
                    formatter: function (value) {
                        return getDicName('po_type')
                    }
                },
                {
                    field: 'orderTaxCode',
                    title: '订单税率',
                    width: 160,
                    sortable: true,
                    formatter: function (value) {
                        return getNecessaryDataName('pc/sys/tax/rest/listAll',value)
                    }
                },
                {
                    field: 'taxCode',
                    title: '税率',
                    width: 160,
                    sortable: true,
                    formatter: function (value) {
                        return getNecessaryDataName('pc/sys/tax/rest/listAll',value)
                    }
                },
            ]
        ],
        toolbar: toolBar,
        onLoadSuccess: function (data) {
            if (optType===0){
                // 默认全部选中
                $(el.tbDetails).datagrid('selectAll');
            }
            var dataRows = data.rows;

            calculationAmount(dataRows);
        },
        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 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: {
            asId: $(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>';
                            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 getVoucherData(companyCode, factoryCode, supplierCode, currencyCode, inStockStartDate, inStockEndDate,purchaseGroup,poType,taxCode,voucherType) {
    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(!taxCode){
        topWin.layer.alert('请选择税率', {icon: 0});
        return false;
    }

    if(moment(inStockStartDate) > moment(inStockEndDate)){
        topWin.layer.alert('入库开始时间不能大于结束时间', {icon: 0});
        return false;
    }
    // 3.获取入库凭证数据
    findVoucherData(companyCode, factoryCode, supplierCode, currencyCode, inStockStartDate, inStockEndDate,purchaseGroup,poType,taxCode,voucherType);
    // findDeductionData(companyCode, supplierCode, inStockStartDate, inStockEndDate);
}

/**
 * 获取入库明细数据
 *
 * @param companyCode 公司编码
 * @param factoryCode 工厂编码
 * @param supplierCode 供应商编码
 * @param currencyCode 货币代码
 * @param inStockStartDate 入库开始时间
 * @param inStockEndDate 入库结束时间
 */
function findVoucherData(companyCode, factoryCode, supplierCode, currencyCode, inStockStartDate, inStockEndDate,purchaseGroup,poType,taxCode,voucherType) {
    var queryParams = $(el.tbDetails).datagrid('options').queryParams;
    queryParams.supplierCode = supplierCode;
    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;
    queryParams.voucherType = voucherType;
    queryParams.paymentTermCode = $(el.paymentTermCode).val();
    queryParams.accountStatementFlag = 1;
    $(el.tbDetails).datagrid('options').url = g.ctx + 'pc/finance/receipt/voucher/rest/provide/create/statement';
    $(el.tbDetails).datagrid('load');
}

/**
 * 入库明细全选
 */
function detailSelectAll() {
    $(el.tbDetails).datagrid('selectAll');
    var dataRows = $(el.tbDetails).datagrid('getRows');
    calculationAmount(dataRows);
}


/**
 * 入库明细取消全选
 */
function cancelSelectAll() {
    $(el.tbDetails).datagrid('unselectAll');
    var rows = $(el.tbDetails).datagrid('getSelections');
    calculationAmount(rows);
}

/**
 * 入库明细导出
 */
function detailExport() {
    var rows = $(el.tbDetails).datagrid('getRows');
    $(el.tbDetails).datagrid('toExcel', {
        filename: '入库明细数据.xls',
        rows: rows,
        worksheet: '入库明细'
    });
}


/**
 * 获取凭证数据
 */
function addVoucherData() {
    var companyCode = $(el.companyCode).val(), factoryCode = $(el.factoryCode).val(), currencyCode = $(el.currencyCode).val(),
        supplierCode = $(el.supplierCode).val(), inStockStartDate = $(el.inStockStartDate).datebox('getValue'),
        purchaseGroup = $('#purchaseGroup').val(), taxCode = $(el.taxCode).combobox('getValue'),voucherType = $(el.voucherType).combobox('getValue'),
        poType = getTextByJs($(el.poType).combobox('getValues')),
        inStockEndDate = $(el.inStockEndDate).datebox('getValue'), asNo = $(el.accountStatementNo).textbox('getValue'), orderType = $(el.orderType).val();
    if(!poType){
        topWin.layer.alert('请选择订单类型', {icon: 0});
        return false;
    }
    var rows = $(el.tbDetails).datagrid('getRows'), alreadyExistId = [];
    for(var i = 0; i < rows.length; i++){
        alreadyExistId.push(rows[i].receiveId);
    }

    var url = g.ctx + 'pc/finance/account/statement/chose/voucher/dialog?orderType=' + orderType +
        '&companyCode=' + companyCode + '&factoryCode=' + factoryCode + '&supplierCode=' + supplierCode + '&poType=' + poType + '&taxCode=' + taxCode + '&voucherType=' + voucherType +
        '&currencyCode=' + currencyCode + '&inStockStartDate=' + inStockStartDate +'&purchaseGroup='+purchaseGroup+
        '&inStockEndDate=' + inStockEndDate + '&alreadyExistId=' + alreadyExistId.join(',') +
        '&asId=' + $(el.id).val();

    el.addDetailDialog = openDialog('choseVoucherData', url, {
        title: '选择入库明细',
        width: '80%',
        height: '75%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.addDetailDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '确定',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['choseVoucherData'].confirmChose(function (data) {
                        for(var n = 0; n < data.length; n++){
                            var item = data[n], row = {}, vf = item.voucherFlag;
                            row.id = 0;
                            row.asId = $(el.id).val();
                            row.asNo = asNo;
                            row.asQuantity = item.asQuantity;
                            row.diffTaxAmount = item.diffTaxAmount;
                            row.materialCode = item.materialCode;
                            row.materialName = item.materialName;
                            row.materialUnit = item.materialUnit;
                            row.notTaxAmount = item.notTaxAmount;
                            row.taxAmount = item.taxAmount;
                            row.notTaxPrice = item.notTaxPrice;
                            row.taxPrice = item.taxPrice;
                            row.poCode = item.poCode;
                            row.poItemNo = item.poItemNo;
                            row.priceUnit = item.priceUnit;
                            row.taxValue = item.taxValue;
                            row.taxCode = item.taxCode;
                            row.taxDesc = item.taxDesc;
                            row.taxCodeDesc = item.taxCodeDesc;
                            row.receiveCode = item.receiveCode;
                            row.receiveRowNo = item.receiveRowNo;
                            row.receiveDate = item.receiveDate;
                            row.receiveId = item.receiveId;
                            row.receiveNum = item.receiveNum;
                            row.voucherFlag = vf;
                            row.sapMoveType = item.sapMoveType;
                            row.inOutFlag = item.inOutFlag;
                            row.paymentWayCode = item.paymentWayCode;
                            row.paymentWayDesc = item.paymentWayDesc;
                            row.paymentWayCodeDesc = item.paymentWayCodeDesc;
                            row.paymentTermCode = item.paymentTermCode;
                            row.paymentTermName = item.paymentTermName;
                            row.paymentTermCodeName = item.paymentTermCodeName;
                            row.seekPgCode = item.seekPgCode;
                            row.seekPgName = item.seekPgName;
                            row.seekPgCodeName = item.seekPgCodeName;
                            row.invoicedAmount = item.invoicedAmount;
                            row.surplusAmount = item.surplusAmount;
                            row.materialSupplierCode = item.materialSupplierCode;
                            row.materialSupplierName = item.materialSupplierName;
                            row.freightType = item.freightType;
                            row.editFlag = item.editFlag;
                            row.minStatementQuantity = item.minStatementQuantity;
                            row.jcPoCode = item.jcPoCode;
                            row.jcPoItemNo = item.jcPoItemNo;
                            row.jcFactoryCode = item.jcFactoryCode;
                            row.poTypeName = item.poTypeName;

                            $(el.tbDetails).datagrid('appendRow', row);
                        }
                        calculationAmount($(el.tbDetails).datagrid('getRows'));
                        el.addDetailDialog.dialog('close');
                    });
                }
            },
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.addDetailDialog.dialog('close');
                }
            }
        ]
    });
}

/**
 * 删除入库凭证数据
 */
function delStatementItem() {
    var rows = $(el.tbDetails).datagrid('getSelections');
    if(rows.length === 0){
        topWin.layer.alert('请选择您要删除的入库明细', {icon: 0});
        return false;
    }

    var surplusReceiveId = [];
    var allRows = $(el.tbDetails).datagrid('getRows');
    for(var n = 0; n < allRows.length; n++){
        surplusReceiveId.push(allRows[n].receiveId);
    }
    for(var m = 0; m < rows.length; m++){
        surplusReceiveId.remove(rows[m].receiveId);
    }

    if(surplusReceiveId.length === 0){
        topWin.layer.alert('明细不能全部删除', {icon: 0});
        return false;
    }

    // 校验选中的行是否可以删除
    var loading = topWin.layer.msg('校验选中的行是否可以删除, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    $.ajax({
        type: 'POST',
        url: g.ctx + 'pc/finance/receipt/voucher/rest/check/write/off',
        data: {
            supplierCode: $(el.supplierCode).textbox('getValue'),
            rvIds: JSON.stringify(surplusReceiveId),
            receiveType: $(el.orderType).val()
        },
        success: function () {
            topWin.layer.close(loading);
            topWin.layer.msg('删除成功', {icon: 1});

            for(var i = 0; i < rows.length; i++){
                var item = rows[i];

                // 入库明细ID为0表示手动添加的
                if(0 !== item.id){
                    el.delDetail.push(item);
                }
                var rowIndex = $(el.tbDetails).datagrid('getRowIndex', item);
                $(el.tbDetails).datagrid('deleteRow', rowIndex);
            }

            var dataRows = $(el.tbDetails).datagrid('getRows');
            calculationAmount(dataRows);
        },
        error: function (data) {
            topWin.layer.close(loading);
            var message = "以下入库凭证不能删除(原因:删除的凭证存在冲销的凭证仍然在明细中): </br>";
            topWin.layer.alert(message + data.responseJSON.message, {icon: 2});
        }
    });
}

function payableOutstanding() {

    var companyCode = $(el.companyCode).combobox('getValue');
    var  supplierCode = $(el.supplierCode).textbox('getValue');
    var  currencyCode = $(el.currencyCode).combobox('getValue');
    var  inStockEndDate = $(el.inStockEndDate).datebox('getValue');

    if(companyCode==''||supplierCode==''||currencyCode==''){
        topWin.layer.alert('请检查“公司”、“供应商”、“本币”是否已选', {icon: 0});
        return false;
    }
    $.ajax({
        type: 'POST',
        url: g.ctx + 'fin/account/statement/rest/payableOutstanding',
        async: false,
        data: {
            companyCode: companyCode,
            supplierCode: supplierCode,
            inStockEndDate: inStockEndDate,
            currency:currencyCode
        },
        success: function (data) {

            $(el.localCurrency).textbox('setValue',new BigNumber(data.apDmbtr).toFormat(2));
            $(el.originalCurrency).textbox('setValue',new BigNumber(data.apWrbtr).toFormat(2));
            $(el.advanceLocalCurrency).textbox('setValue',new BigNumber(data.ppDmbtr).toFormat(2));
            $(el.advanceOriginalCurrency).textbox('setValue',new BigNumber(data.ppWrbtr).toFormat(2));


        }
    });


}

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

    // 初始化工厂代码下拉框
    $(el.factoryCode).combobox({
        url: g.ctx + 'pc/sys/factory/rest/listAll',
        editable: false,
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        panelHeight: 'auto'
    });
    //采购组
    //采购组
    $(el.purchaseGroup).combobox({
        valueField: 'code',
        textField: 'codeWithDesc',
        limitToList: 'true',
        method: 'POST',
        prompt: '--- 请选择 ---',
        url: g.ctx + 'pc/sys/purchaseGroup/rest/listAll',
    });

    // 初始化公司代码下拉框
    $(el.companyCode).combobox({
        required: true,
        url: companyDataUrl,
        panelHeight: 'auto',
        valueField: 'companyCode',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        onSelect: function (data) {
            var oriCc = $(el.companyCode).combobox('getValue');
            if(oriCc !== data.companyCode){
                clearPageTableData();
            }

            $(el.companyName).val(data.companyName);
            findFactoryDataByCompanyCode(data.companyCode, isSupplier);
        }
    });
    $(el.currencyCode).combobox({
        url: g.ctx + 'pc/sys/dict/getDicByType?type=currency',
        panelHeight: 'auto',
        limitToList: 'true',
        prompt: '-- 请选择 --',
        method: 'GET',
        valueField: 'code',
        textField: 'codeWithDesc',
        onSelect: function (data) {
            getExchangeRate(data.code);
            clearPageTableData();
        },
        onLoadSuccess: function () { //加载完成后,设置选中第一项
            var val = $(this).combobox("getData");
            for (var item in val[0]) {
                if (item === "code") {
                    $(this).combobox("select", val[0][item]);
                    getExchangeRate(val[0][item]);
                }
            }
        }
    });
    if(Number(isSupplier) === 0){
        $(el.supplierCode).textbox({
            prompt: '请选择供应商',
            required: true,
            icons: [
                {
                    iconCls: 'icon-search',
                    handler: function () {
                        choseSupplier();
                    }
                }
            ]
        });
        $(el.supplierCode).textbox('textbox').css('cursor', 'pointer');
        $(el.supplierCode).textbox('textbox').bind('click', function () {
            choseSupplier();
        });
    }


    // 初始化入库凭证开始日期
    $(el.inStockStartDate).datebox({
        value: moment(new Date()).subtract(1, 'months').startOf('month').format("YYYY-MM-DD"),
        onSelect: function(date){
            var curr = $(this).datebox('getValue'), update = moment(date).format("YYYY-MM-DD");
            if(curr !== update){
                clearPageTableData();
            }
        }
    });

    // 初始化入库凭证结束日期
    $(el.inStockEndDate).datebox({
        value: moment(new Date()).subtract(1, 'months').endOf('month').format("YYYY-MM-DD"),
        onSelect: function(date){
            var curr = $(this).datebox('getValue'), update = moment(date).format("YYYY-MM-DD");
            if(curr !== update){
                clearPageTableData();
            }
        }
    });

    // 凭证类型
    $(el.voucherType).combobox({
        valueField: 'code',
        textField: 'name',
        limitToList: 'true',
        data: [
            {'name': '常规', 'code': '1'},
            {'name': '寄售', 'code': 2}
        ],
        editable: false,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
    });

    // 税率
    $(el.taxCode).combobox({
        required: true,
        panelHeight: 'auto',
        panelWidth: 200,
        limitToList: 'true',
        valueField: 'taxCode',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        url: g.ctx + 'pc/sys/tax/rest/listAll',
        onChange: function (data) {
            $(el.tbDetails).datagrid('loadData', { total: 0, rows: [] });
            var rows = $(el.tbDetails).datagrid('getSelections');
            calculationAmount(rows);
        }
    });

    // 采购组
    $(el.purchaseGroupCode).combobox({
        valueField: 'code',
        textField: 'codeWithDesc',
        method: 'POST',
        // panelHeight: 200,
        // panelWidth: 240,
        prompt: '--- 请选择 ---',
        url: g.ctx + 'pc/sys/purchaseGroup/rest/listAll'
    });

    // 付款条件
    $(el.paymentTermCode).combobox({
        panelHeight: 'auto',
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        method: 'GET',
        url: g.ctx + 'pc/sys/dict/getDicByType?type=payment_method',
    });
    // 订单类型
    $(el.poType).combobox({
        panelHeight: 'auto',
        panelWidth: 200,
        valueField: 'code',
        multiple: true,
        method: 'GET',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        url: g.ctx + 'pc/sys/dict/getDicByType?type=po_type',
        icons: [{
            iconCls: 'icon-delete',
            handler: function (e) {
                $(el.poType).combobox('clear');
                $(el.tbDetails).datagrid('loadData', { total: 0, rows: [] });
                var rows = $(el.tbDetails).datagrid('getSelections');
                calculationAmount(rows);
            }
        }],
        onChange: function (data) {
            $(el.tbDetails).datagrid('loadData', { total: 0, rows: [] });
            var rows = $(el.tbDetails).datagrid('getSelections');
            calculationAmount(rows);
        },
        onLoadSuccess: function (record) {
            //全选
            if (optType===0){
                var valueField = $(el.poType).combobox("options").valueField;
                var data = $(el.poType).combobox("getData");
                var selectVaues = [];
                data.reduce(function(prev, current, index, array){
                    selectVaues.push(current[valueField]);
                },selectVaues);
                $(el.poType).combobox('setValues', selectVaues);
            }
        }
    });
}


/**
 * 清空页面表格数据
 */
function clearPageTableData() {
    $(el.tbDetails).datagrid('loadData', {total: 0, rows: []});

    // 顺便清空页面输入的值
    $(el.bpPayableBalance).textbox('setValue', '');
    $(el.bpEstimateBalance).textbox('setValue', '');
    $(el.etPayableBalance).textbox('setValue', '');
    $(el.etEstimateBalance).textbox('setValue', '');
    $(el.beginPeriodTotal).textbox('setValue', '');
    $(el.endPeriodTotal).textbox('setValue', '');
}

/**
 * 根据公司编码获取工厂代码下拉框数据
 *
 * @param companyCode 公司编码
 * @param isSupplier 是否供应商账号 0:否 1是
 */
function findFactoryDataByCompanyCode(companyCode, isSupplier) {
    var factoryDataUrl = g.ctx + 'pc/sys/factory/rest/listAll';
    $(el.factoryCode).combobox({
        url: factoryDataUrl,
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        panelHeight: 300,
        panelWidth: 260,
        disabled: false,
        required: true,
        onLoadSuccess: function(data){
            for (var i = 0; i < data.length; i++) {
                if(data[i].companyCode === companyCode){
                    $(el.factoryCode).combobox('setValue', data[i].code);
                    $(el.factoryName).val(data[i].name);
                }
            }
        },
        onSelect: function (data) {
            var oriFc = $(el.factoryCode).combobox('getValue');
            if(oriFc !== data.code){
                clearPageTableData();
            }

            $(el.factoryName).val(data.name);
        }
    });
}

/**
 * 计算页面相关金额
 */
function calculationAmount(rows) {
    var taxAmount = new BigNumber(0), notTaxAmount = new BigNumber(0), invoicedAmount = new BigNumber(0),
        surplusAmount = new BigNumber(0), storageQuantity = new BigNumber(0), statementQuantity = new BigNumber(0);
    for (var j = 0; j < rows.length; j++) {
        var item = rows[j];
        taxAmount = taxAmount.plus(item.taxAmount);
        notTaxAmount = notTaxAmount.plus(item.notTaxAmount);
        invoicedAmount = invoicedAmount.plus(item.invoicedAmount);
        surplusAmount = surplusAmount.plus(item.surplusAmount);
        storageQuantity = storageQuantity.plus(item.receiveNum);
        statementQuantity = statementQuantity.plus(item.asQuantity);
    }

    $(el.taxAmount).textbox('setValue', taxAmount.toFormat(2));
    $(el.notTaxAmount).textbox('setValue',notTaxAmount.toFormat(2));

    if(0 !== rows.length){
        // 更新页脚行的值并刷新
        var footers = $(el.tbDetails).datagrid('getFooterRows');
        footers[0]['taxAmount'] = taxAmount.toFormat(2);
        footers[0]['notTaxAmount'] = notTaxAmount.toFormat(2);
        footers[0]['diffTaxAmount'] = taxAmount.minus(notTaxAmount).toFormat(2);
        footers[0]['invoicedAmount'] = invoicedAmount.toFormat(2);
        footers[0]['surplusAmount'] = surplusAmount.toFormat(2);
        footers[0]['receiveNum'] = storageQuantity.toFixed(3);
        footers[0]['asQuantity'] = statementQuantity.toFixed(3);
        $(el.tbDetails).datagrid('reloadFooter');
    }else {
        // 更新页脚行并载入新数据
        $(el.tbDetails).datagrid('reloadFooter', [
            {
                taxAmount: 0,
                notTaxAmount: 0,
                diffTaxAmount: 0,
                invoicedAmount: 0,
                surplusAmount: 0,
                receiveNum: 0,
                asQuantity: 0
            }
        ]);
    }
}

/**
 * 选择供应商
 */
function choseSupplier() {
    var url = g.ctx + "pc/supplier/supplierSelect?single=1";
    el.choseSupplierDialog = openDialog('choseSupplier', url, {
        title: '供应商选择',
        width: '700px',
        height: '560px',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.choseSupplierDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '确定',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['choseSupplier'].chooseRow(function (data) {
                        console.log(data)
                        var oriSupCode = $(el.supplierCode).textbox('getValue');
                        if(oriSupCode !== data.supplierCode){
                            clearPageTableData();
                        }

                        $(el.supplierCode).textbox('setValue', data.supplierCode);
                        $(el.supplierName).textbox('setValue', data.supplierName);
                        el.choseSupplierDialog.dialog('close');
                        //TODO
                        // initPaymentTermCode(data[0].supplierCode)
                    });
                }
            },
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.choseSupplierDialog.dialog('close');
                }
            }
        ]
    });
}


/**
 * 数据保存
 *
 * @param type 0:暂存 1：提交
 * @param callback 回调函数
 */
function dataSave(type,callback) {
    var id = $(el.id).val(), files = $(el.files).attr('data-fileIds'),orderType = $(el.orderType).val(), supplierCode = $(el.supplierCode).textbox('getValue'),
        supplierName = $(el.supplierName).textbox('getValue'), currencyCode = $(el.currencyCode).combobox('getValue'),voucherType = $(el.voucherType).combobox('getValue'),
        companyCode = $(el.companyCode).combobox('getValue'), companyName = $(el.companyName).val(),
        factoryCode = $(el.factoryCode).combobox('getValue'), factoryName = $(el.factoryName).val(),
        taxAmount = $(el.taxAmount).textbox('getValue'), notTaxAmount = $(el.notTaxAmount).val(),
        purchaseGroup = $('#purchaseGroup').combobox('getValue'),
        paymentTermCode = $(el.paymentTermCode).combobox('getValue'),
        poType = getTextByJs($(el.poType).combobox('getValues')),
        deductionAmount = "", rebateAmount = "",
        bpPayableBalance ="", bpEstimateBalance = "",
        etPayableBalance = "", etEstimateBalance = "",
        fileId = $(el.fileId).val(),
        inStockStartDate = $(el.inStockStartDate).datebox('getValue'), inStockEndDate = $(el.inStockEndDate).datebox('getValue'),
        remark = $(el.remark).textbox('getValue'), currPaymentAmount = "",
        localCurrency = $(el.localCurrency).textbox('getValue'),
        originalCurrency = $(el.originalCurrency).textbox('getValue'),
        advanceLocalCurrency = $(el.advanceLocalCurrency).textbox('getValue'),
        advanceOriginalCurrency = $(el.advanceOriginalCurrency).textbox('getValue');

    // if($.isEmptyObject(localCurrency)||$.isEmptyObject(originalCurrency)||$.isEmptyObject(advanceLocalCurrency)||$.isEmptyObject(advanceOriginalCurrency)){
    //     topWin.layer.alert('请获取“应清未付金额”', {icon: 0});
    //     return false;
    // }
    // localCurrency = Number(localCurrency.replace(/,/g,'')),
    //     originalCurrency = Number(originalCurrency.replace(/,/g,'')),
    //     advanceLocalCurrency = Number(advanceLocalCurrency.replace(/,/g,'')),
    //     advanceOriginalCurrency = Number(advanceOriginalCurrency.replace(/,/g,''));
    if (!companyCode) {
        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 (!currencyCode) {
        topWin.layer.alert('请选择币种', {icon: 0});
        return false;
    }
    if (!purchaseGroup) {
        topWin.layer.alert('请选择采购组', {icon: 0});
        return false;
    }
    if (!poType) {
        topWin.layer.alert('请选择订单类型', {icon: 0});
        return false;
    }
    if (!remark) {
        topWin.layer.alert('请填写备注', {icon: 0});
        return false;
    }

    var headData = {};
    headData.id = id;
    headData.files = files;
    headData.orderType = orderType;
    headData.companyCode = companyCode;
    headData.companyName = companyName;
    headData.factoryCode = factoryCode;
    headData.factoryName = factoryName;
    headData.inStockStartDate = inStockStartDate;
    headData.inStockEndDate = inStockEndDate;
    headData.currencyCode = currencyCode;
    headData.supplierCode = supplierCode;
    headData.taxCode = $(el.taxCode).combobox('getValue');
    headData.supplierName = supplierName;
    headData.paymentTermCode = paymentTermCode;
    headData.voucherType = voucherType;
    headData.poType = poType;
    headData.taxAmount = Number(taxAmount.replace(/,/g,''));
    headData.notTaxAmount = Number(notTaxAmount.replace(/,/g,''));
    headData.deductionAmount = deductionAmount;
    headData.rebateAmount = rebateAmount;
    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,''));
    headData.purchaseGroup = purchaseGroup;
    headData.remark = remark;
    headData.localCurrency = localCurrency;
    headData.originalCurrency = originalCurrency;
    headData.advanceLocalCurrency = advanceLocalCurrency;
    headData.advanceOriginalCurrency = advanceOriginalCurrency;
    headData.fileId = fileId;


    // 入库明细
    var detail = $(el.tbDetails).datagrid('getSelections'), statementItem = [];
    if (detail.length === 0) {
        topWin.layer.alert('请选择入库凭证明细', {icon: 0});
        return false;
    }
    //校验税码和付款条件
    let taxCode = "",payTermCode = "",pgCode = "";
    var itSumAmount = new BigNumber(0);
    for(var i = 0; i < detail.length; i++){
        if(i !== 0 && taxCode !== detail[i].taxCode){
            layer.msg("所选税率必须一致");
            return false;
        }
        if(i !== 0 && payTermCode !== detail[i].paymentTermCode){
            layer.msg("所选付款条件必须一致");
            return false;
        }
        // if(i !== 0 && pgCode !== detail[i].pgCode){
        //     layer.msg("所选采购组必须一致");
        //     return false;
        // }
        taxCode = detail[i].taxCode;
        payTermCode = detail[i].paymentTermCode;
        pgCode = detail[i].pgCode;
        // headData.purchaseGroup = pgCode;

        var row = detail[i], obj = {};

        obj.asId = id;
        obj.receiveId = row.receiveId;
        obj.receiveCode = row.receiveCode;
        obj.receiveRowNo = row.receiveRowNo;
        obj.receiveNum = row.receiveNum;
        obj.asQuantity = row.asQuantity;
        obj.taxCode = row.taxCode;
        obj.taxValue = row.taxValue;
        obj.notTaxPrice = row.notTaxPrice;
        obj.taxPrice = row.taxPrice;
        obj.notTaxAmount = row.notTaxAmount;
        obj.taxAmount = row.taxAmount;
        obj.diffTaxAmount = row.diffTaxAmount;
        obj.priceUnit = row.priceUnit;
        obj.editFlag = row.editFlag;
        obj.minStatementQuantity = row.minStatementQuantity;
        obj.subjectType_code = row.subjectTypeCode;
        obj.rowTypeCode = row.rowTypeCode;
        statementItem.push(obj);

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

    // 扣款数据
    // var deduction = $(el.tbDeduction).datagrid('getRows'), deductionIds = [];
    // for(var j = 0; j < deduction.length; j++){
    //     deductionIds.push(deduction[j].id);
    // }

    // 返利数据
    // var rebate = $(el.tbRebate).datagrid('getRows'), rebateIds = [];
    // for(var k = 0; k < rebate.length; k++){
    //     rebateIds.push(rebate[k].id);
    // }

    // 需要校验凭证汇总含税金额 - (扣款金额 + 返利金额) > 0
    // var diff = itSumAmount.plus(deductionAmount).plus(rebateAmount);
    // if(diff.lt(0)){
    //     topWin.layer.alert('选择入库凭证明细的含税金额汇总小于选择的扣款金额', {icon: 0});
    //     return false;
    // }

    let title;
    if(type === 0){
        title = "您确定要保存对账单?";
    }else{
        title ="您确定要保存对账单,并提交财务确认?"
    }
    topWin.layer.confirm(title, {icon: 3}, function (index) {
        topWin.layer.close(index);

        var loading = topWin.layer.msg('数据保存中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
        $.ajax({
            url: g.ctx + 'pc/finance/account/statement/rest/saveOrUpdate',
            type: 'POST',
            data: {
                optType: optType,
                headData: JSON.stringify(headData),
                statementItem: JSON.stringify(statementItem)
                // deductionIds: deductionIds.length === 0 ? '' : JSON.stringify(deductionIds),
                // rebateIds: rebateIds.length === 0 ? '' : JSON.stringify(rebateIds)
            },
            success: function (data) {
                topWin.layer.close(loading);
                callback(data.id);
            },
            error: function (data) {
                topWin.layer.close(loading);
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    });
}


/**
 * 主管确认
 *
 * @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;
    }
    // 检查对账单明细中付款条件是否都相同
    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;
    }
}