/**
 * 对账模块-开票申请单编辑页面JS
 *
 * Created by li.kui on 2020/8/14.
 */
'use strict';
var el = {
    dataPanel: '#dataPanel',
    dataDiv: '#dataDiv',
    id: '#id',
    iaNo: '#invoiceApplyNo',
    orderType: '#orderType',
    supplierCode: '#supplierCode',
    companyCode: '#companyCode',
    factoryCode: '#factoryCode',
    currencyCode: '#currencyCode',
    deductionAmount: '#deductionAmount',
    dntAmount: '#dntAmount',
    rebateAmount: '#rebateAmount',
    rntAmount: '#rntAmount',
    invoiceNetAmount: '#invoiceNetAmount',
    invoiceTaxAmount: '#invoiceTaxAmount',
    allBudInnerMoney: '#allBudInnerMoney',
    invoiceNum: '#invoiceNum',
    invoiceNo: '#invoiceNo',
    remark: '#remark',
    dataTabs: '#dataTabs',
    tbFile: '#tbFile',
    tbDetails: '#tbDetails',
    tbDeduction: '#tbDeduction',
    tbAdvance: '#tbAdvance',
    diffAmount1: '#diffAmount1',
    tbRebate: '#tbRebate',
    addDetailDialog: null,
    addRebateDialog: null,
    addDeductionDialog: null,
    delDetail: [],
    delRebate: [],
    delDeduction: [],
    userTableColumn: [],
    bodyHeight: document.documentElement.clientHeight,
    supplierCurrencyCode: currencyCode,
    supplierTaxRate: taxCode,
    supplierBusinessRegisterNo: businessRegisterNo,
    companyName: '#companyNameDesc',
    supplierName: '#supplierName',
    tbInvoice: '#tbInvoice',
    invoiceTotalAmount: '#invoiceTotalAmount',
    invoiceTaxTotalAmount: '#invoiceTaxTotalAmount',
    diffAmount: '#diffAmount',
    delInvoice: [],
    typeName : 'add_fast'
};


/**
 * 文档就绪
 */
$(function () {
    $(el.dataPanel).panel({
        collapsible: true,
        onCollapse: function () {
            $(el.dataTabs).tabs('select', 0);

            $(el.tbDetails).datagrid('resize', {height: el.bodyHeight - 80});
            // $(el.tbRebate).datagrid('resize', {height: el.bodyHeight - 80});
            // $(el.tbDeduction).datagrid('resize', {height: el.bodyHeight - 80});
            // $(el.tbAdvance).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});
            // $(el.tbRebate).datagrid('resize', {height: el.bodyHeight - dataDiv});
            // $(el.tbDeduction).datagrid('resize', {height: el.bodyHeight - dataDiv});
            // $(el.tbAdvance).datagrid('resize', {height: el.bodyHeight - dataDiv});
        }
    });

    // 加载页面输入或下拉框数据
    initPageInput();
    // 获取当前用户在本页面中表格列配置
    // findUserTableColumn();
    // 订单类型
    $('#poType').combobox({
        required: false,
        limitToList: 'true',
        panelHeight: 'auto',
        panelWidth: 200,
        method: 'GET',
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        url: g.ctx + 'pc/sys/dict/getDicByType?type=po_type',
    });
    initTbDetails();
    // initTbAdvance();
    // initTbDeduction();
    // initTbRebate();

});

/**
 * 初始化页面输入框
 */
function initPageInput() {
    // 初始化税率代码下拉框
    $('#taxCode').combobox({
        required: true,
        panelHeight: 300,
        panelWidth: 340,
        limitToList: 'true',
        valueField: 'taxCode',
        method: 'GET',
        textField: 'codeWithDesc',
        url: g.ctx + 'pc/sys/tax/rest/listAll',
        prompt: '--- 请选择 ---'
    });
    // 付款条件
    $('#paymentTermCode').combobox({
        required: true,
        limitToList: 'true',
        panelHeight: 'auto',
        panelWidth: 200,
        method: 'GET',
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        url: g.ctx + 'pc/sys/dict/getDicByType?type=payment_method',
    });
    // 初始化币种下拉框
    getExchangeRate($(el.currencyCode).textbox('getValue'));
}
/**
 * 初始化开票申请明细表格
 */
function initTbDetails() {
    var dataDiv = $(el.dataDiv).outerHeight() + 90, orderType = $(el.orderType).val();
    // var columns = dynamicColumns(orderType);

    $(el.tbDetails).datagrid({
        loadMsg: '数据加载中, 请耐心等待......',
        height: el.bodyHeight - dataDiv,
        url: g.ctx + 'pc/finance/invoiced/apply/detail/rest/find/by/apply/id',
        singleSelect: false,
        showFooter: true,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        remoteSort: false,
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: false,
        queryParams: {
            iaId: $(el.id).val(),
            becShare: 0
        },
        frozenColumns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                }
            ]
        ],
        columns: [
            tableColumns
        ],
        toolbar: [
            {
                text: '添加',
                iconCls: 'icon-add',
                handler: function () {
                    addStatementItem();
                }
            },
            '-',
            {
                text: '删除',
                iconCls: 'icon-remove',
                handler: function () {
                    delStatementItem();
                }
            },
            '-',
            {
                text: '导出',
                iconCls: 'icon-download',
                handler: function () {
                    detailDataExport();
                }
            }
        ],
        onLoadSuccess: function () {
            // handleVoucherTail();
            // refreshAdvance();

            // findDeductionDetail($(el.supplierCode).textbox('getValue'),$(el.companyCode).val());
        }
    });
}
function refreshAdvance(){
    var rows = $(el.tbDetails).datagrid('getRows'), purchaseOrderDetailIds = [];
    for(var i = 0; i < rows.length; i++){
        purchaseOrderDetailIds.push(rows[i].purchaseOrderDetailId);
    }
    var queryParams3 = $(el.tbAdvance).datagrid('options').queryParams;
    queryParams3.supplierCode = $(el.supplierCode).textbox('getValue');
    $(el.tbAdvance).datagrid('options').url = g.ctx + 'fin/payment/advance/apply/rest/find/paa/findPaaDetailBySupplierCode';
    $(el.tbAdvance).datagrid('load');
}

/**
 * 初始化预付款明细表格
 */
function initTbAdvance() {
    var dataDiv = $(el.dataDiv).outerHeight() + 90, orderType = $(el.orderType).val();
    $(el.tbAdvance).datagrid({
        loadMsg: '数据加载中, 请耐心等待......',
        height: el.bodyHeight - dataDiv,
        singleSelect: false,
        rownumbers: true,
        showFooter: true,
        pagination: true,
        queryParams: {},
        frozenColumns: [
            [
                // {
                //     field: 'ck',
                //     checkbox: true
                // },
                // {
                //     field: 'seekPgName',
                //     title: '业务员',
                //     width: 80,
                //     sortable: true
                // },
                {
                    field: 'poCode',
                    title: '采购订单',
                    width: 100,
                    sortable: true
                },
                {
                    field: 'poItemNo',
                    title: '订单行号',
                    width: 65,
                    sortable: true
                },
                {
                    field: 'poNum',
                    title: '订单数量',
                    width: 65,
                    sortable: true
                }
            ]
        ],
        columns: [
            [
                {
                    field: 'quantityRange',
                    title: '容差',
                    hidden:true
                },
                {
                    field: 'factoryCode',
                    title: '工厂',
                    width: 80,
                    sortable: true
                },
                {
                    field: 'materialDesc',
                    title: '物料描述',
                    width: 300,
                    sortable: true
                },
                {
                    field: 'taxCodeDesc',
                    title: '税码',
                    width: 160,
                    sortable: true
                },
                // {
                //     field: 'ntPrice',
                //     title: '不含税单价',
                //     width: 100,
                //     sortable: true
                // },
                {
                    field: 'itPrice',
                    title: '含税单价',
                    width: 100,
                    sortable: true,
                    formatter:function (value) {
                        if (!value) {
                            return '';
                        }
                        return  formatNumber(value, 4, 1);
                    }
                },
                {
                    field: 'itAmount',
                    title: '订单含税金额',
                    width: 100,
                    sortable: true,
                    formatter:function (value) {
                        if (!value) {
                            return '';
                        }
                        return  formatNumber(value, 4, 1);
                    }
                },
                {
                    field: 'applyAmount',
                    title: '可申请金额',
                    width: 100,
                    sortable: true,
                    formatter:function (value) {
                        if (!value) {
                            return '';
                        }
                        return  formatNumber(value, 4, 1);
                    }
                },
                {
                    field: 'budInnerMoney',
                    title: '申请金额',
                    width: 100,
                    sortable: true,
                    styler: function (value, row) {
                        if(row.poCode !== '合计'){
                            return 'background-color:#E1E1E1;';
                        }
                        return '';
                    },
                    editor: {
                        type: 'numberbox',
                        options: {
                            precision: 4,
                            onChange: function (nv) {
                                updateRowData(nv,'budInnerMoney');
                            }
                        }
                    }
                },
                {
                    field: 'alreadyApplyAmount',
                    title: '已申请金额',
                    width: 100,
                    sortable: true
                },
                {
                    field: 'alreadyAdvanceAmount',
                    title: '已预付金额',
                    width: 100,
                    sortable: true
                },
                {
                    field: 'pcCodeName',
                    title: '付款条件名称',
                    width: 200,
                    sortable: true
                },
                {
                    field: 'itemRemark',
                    title: '摘要',
                    width: 200,
                    styler: function (value, row) {
                        if(row.poCode !== '合计'){
                            return 'background-color:#E1E1E1;';
                        }
                        return '';
                    },
                    editor: {type: 'textbox'}
                },
                {
                    field: 'contractNo',
                    title: '合同号',
                    width:120
                },
                {
                    field: 'contractName',
                    title: '合同名称',
                    width:120
                },
                {
                    field: 'emptyColumn',
                    title: '',
                    width: 20
                }
            ]
        ],
    });
}
/**
 * 添加对账单明细数据
 */
function addStatementItem() {
    var companyCode = $(el.companyCode).val(), factoryCode = $(el.factoryCode).val(), currencyCode = $(el.currencyCode).val(),
        supplierCode = $(el.supplierCode).textbox('getValue'), iaNo = $(el.iaNo).val(), iaId = $(el.id).val(),
        orderType = $(el.orderType).val(),paymentTermCode = $('#paymentTermCode').combobox('getValue');

    var rows1 = $(el.tbDetails).datagrid('getRows'), asdIds = [], tempDelAsdId = [];
    for(var i = 0; i < rows1.length; i++){
        asdIds.push(rows1[i].asdId);
    }
    for(var j = 0; j < el.delDetail.length; j++){
        if(el.delDetail[j].id !== 0){
            tempDelAsdId.push(el.delDetail[j].asdId);
        }
    }

    var url = g.ctx + 'pc/finance/invoiced/apply/chose/statement/detail/dialog?companyCode=' + companyCode +
        '&factoryCode=' + factoryCode + '&supplierCode=' + supplierCode + '&currencyCode=' + currencyCode +'&paymentTermCode=' + paymentTermCode +
        '&orderType=' + orderType+ '&excludeAsdIds=' + asdIds.join(',') +
        '&tempDelAsdIds=' + tempDelAsdId.join(',');
    el.addDetailDialog = openDialog('choseStatementDetail', 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['choseStatementDetail'].confirmChose(function (data) {
                        for(var n = 0; n < data.length; n++){
                            var item = data[n], row = {};
                            row.id = 0;
                            row.iaId = iaId;
                            row.iaNo = iaNo;
                            row.asId = item.asId;
                            row.asNo = item.asNo;
                            row.asdId = item.asdId;
                            row.asdItemNo = item.asdItemNo;
                            row.statementNum = item.asQuantity;
                            row.asTaxValue = item.asTaxValue;
                            row.asTaxCode = item.asTaxCode;
                            row.asTaxDesc = item.asTaxDesc;
                            row.asTaxCodeDesc = item.asTaxCodeDesc;
                            row.asNotTaxPrice = item.asNotTaxPrice;
                            row.asTaxPrice = item.asTaxPrice;
                            row.asNotTaxAmount = item.asNotTaxAmount;
                            row.asTaxAmount = item.asTaxAmount;
                            row.asDiffTaxAmount = item.asDiffTaxAmount;
                            row.iaDiffPrice = 0;
                            row.iaDiffAmount = 0;
                            row.receiveId = item.receiveId;
                            row.receiveCode = item.receiveCode;
                            row.receiveRowNo = item.receiveRowNo;
                            row.receiveDate = item.receiveDate;
                            row.inOutFlag = item.inOutFlag;
                            row.poCode = item.poCode;
                            row.poItemNo = item.poItemNo;
                            row.materialCode = item.materialCode;
                            row.materialName = item.materialName;
                            row.shareFlag = item.shareFlag;
                            row.shareNum = item.shareNum;
                            row.materialSupplierCode = item.materialSupplierCode;
                            row.materialSupplierName = item.materialSupplierName;
                            row.freightType = item.freightType;
                            row.jcPoCode = item.jcPoCode;
                            row.zlsdh = item.zlsdh;
                            row.jcPoItemNo = item.jcPoItemNo;
                            row.jcFactoryCode = item.jcFactoryCode;

                            $(el.tbDetails).datagrid('appendRow', row);
                        }
                        // refreshAdvance();
                        // addRebateAndDeduction();
                        el.addDetailDialog.dialog('close');
                        let rows = $(el.tbDetails).datagrid('getRows');
                        calculationAmount(rows);
                    });
                }
            },
            {
                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);
            // 删除的对账单ID
            var delAsNo = [];
            for(var i = 0; i < rows.length; i++){
                var item = rows[i];
                delAsNo.push(item.asNo);

                // 入库明细ID为0表示手动添加的
                if(0 !== item.id){
                    el.delDetail.push(item);
                }
                var rowIndex = $(el.tbDetails).datagrid('getRowIndex', item);
                $(el.tbDetails).datagrid('deleteRow', rowIndex);
            }
            topWin.layer.msg('删除成功', {icon: 1});

            var dataRows = $(el.tbDetails).datagrid('getRows');
            calculationAmount(dataRows);

            // 重新获取返利和扣款数据
            // refreshRebateAndDeduction(dataRows, delAsNo);
        },
        error: function (data) {
            topWin.layer.close(loading);
            topWin.layer.alert('以下入库凭证不能删除(原因:删除的凭证存在冲销的凭证仍然在明细中): </br>' + data.responseJSON.message, {icon: 2});
        }
    });
}


/**
 * 数据保存
 */
function dataSave(callback) {
    endInvoiceEditor();
    // addOrDelInvoice();
    var id = $(el.id).val(), remark = $(el.remark).textbox('getValue'), invoiceTaxAmount = $(el.invoiceTaxAmount).textbox('getValue'),
        invoiceNetAmount = $(el.invoiceNetAmount).textbox('getValue'), rebateAmount = "",
        deductionAmount = "", invoiceNum = $(el.invoiceNum).numberbox('getValue'),taxCode = $('#taxCode').combobox('getValue'),paymentTermCode1 = $('#paymentTermCode').combobox('getValue'),
        invoiceNo = $(el.invoiceNo).textbox('getValue'), dntAmount = $(el.dntAmount).val(), rntAmount = $(el.rntAmount).val(),
        // allBudInnerMoney = $(el.allBudInnerMoney).textbox('getValue'),
        iaNo = $(el.iaNo).val(),
        poType = getTextByJs($('#poType').combobox('getValues')),
        invoiceTotalAmount = $(el.invoiceTotalAmount).textbox('getValue'),
        invoiceTaxTotalAmount = $(el.invoiceTaxTotalAmount).textbox('getValue') ;

    if (!taxCode) {
        topWin.layer.alert('请选择税率', {icon: 0});
        return false;
    }
    if (!paymentTermCode1) {
        topWin.layer.alert('请选择付款条件', {icon: 0});
        return false;
    }
    var headData = {};
    headData.id = id;
    // 开票净价总金额 = 净价总金额 + 返利金额
    headData.invoiceTaxAmount = Number(invoiceTaxAmount.replace(/,/g,'')) ;
    // headData.allBudInnerMoney = Number(allBudInnerMoney.replace(/,/g,''));
    headData.invoiceNetAmount = Number(invoiceNetAmount.replace(/,/g,'')) ;
    headData.invoiceTaxTotalAmount = Number(invoiceTaxTotalAmount.replace(/,/g,''));
    headData.invoiceTotalAmount = Number(invoiceTotalAmount.replace(/,/g,''));
    headData.rntAmount = rntAmount;
    headData.rebateAmount = rebateAmount;
    headData.poType = poType;
    headData.taxCode = taxCode;
    headData.paymentTermCode = paymentTermCode1;
    headData.dntAmount = dntAmount;
    headData.deductionAmount = deductionAmount;
    headData.invoiceNum = invoiceNum;
    headData.invoiceNo = invoiceNo;
    headData.remark = remark;
    headData.invoiceTotalAmount = invoiceTotalAmount;
    headData.invoiceTaxTotalAmount = invoiceTaxTotalAmount;

    // if(!invoiceNum){
    //     topWin.layer.alert('请填写发票张数', {icon: 0});
    //     return false;
    // }
    // if(!invoiceNo){
    //     topWin.layer.alert('请填写发票号', {icon: 0});
    //     return false;
    // }
    // 发票号填写的字符串长度不能超过30位字符
    // if(invoiceNo.length > 30){
    //     topWin.layer.alert('发票号填写的字符串长度不能超过30位字符', {icon: 0});
    //     return false;
    // }

    // 开票申请明细数据; 待删除开票申请明细ID delDetailIds
    var detail = $(el.tbDetails).datagrid('getRows'), invoicedReceipt = $(el.tbInvoice).datagrid('getRows'),detailDate = [], delDetailId = [];
    if (detail.length === 0) {
        topWin.layer.alert('请选择对账明细数据', {icon: 0});
        return false;
    }
    // SAP发票明细行不得超过999
    // if(detail.length > 900){
    //     topWin.layer.alert('由于系统原因, 开票申请明细不得超过900行', {icon: 0});
    //     return false;
    // }
    if (invoicedReceipt.length === 0) {
        topWin.layer.alert('请添加关联发票信息', {icon: 0});
        return false;
    }
    for (let i = 0 ; i < invoicedReceipt.length ; i ++){
        // if(!invoicedReceipt[i].deductionCodeType){
        //     layer.msg("关联发票信息：第"+ ++i+"行可抵扣编号不能为空");
        //     return false;
        // }
        if(!invoicedReceipt[i].invoiceDate){
            layer.msg("关联发票信息：第"+ ++i+"行发票日期不能为空");
            return false;
        }
        // if(!invoicedReceipt[i].invoiceCode){
        //     layer.msg("关联发票信息：第"+ ++i+"行发票代码不能为空");
        //     return false;
        // }
        if(!invoicedReceipt[i].invoiceNumber){
            layer.msg("关联发票信息：第"+ ++i+"行发票号码不能为空");
            return false;
        }
        if(!invoicedReceipt[i].dutyParagraph){
            layer.msg("关联发票信息：第"+ ++i+"行税号不能为空");
            return false;
        }
        if(!invoicedReceipt[i].taxRate){
            layer.msg("关联发票信息：第"+ ++i+"行税率不能为空");
            return false;
        }
        if(!invoicedReceipt[i].currencyCode){
            layer.msg("关联发票信息：第"+ ++i+"行币种不能为空");
            return false;
        }
        if(!invoicedReceipt[i].taxAmount){
            layer.msg("关联发票信息：第"+ ++i+"行含税金额不能为空");
            return false;
        }
        if(!invoicedReceipt[i].noTaxAmount&&invoicedReceipt[i].noTaxAmount!==0){
            layer.msg("关联发票信息：第"+ ++i+"行未税金额不能为空");
            return false;
        }
        // if(!invoicedReceipt[i].fileId){
        //     layer.msg("关联发票信息：第"+ ++i+"行发票附件不能为空");
        //     return false;
        // }
    }
    //校验发票
    // var tbInvoiceRows = $(el.tbInvoice).datagrid('getRows');
    // for(var i = 0; i < tbInvoiceRows.length; i++){
    //     if(tbInvoiceRows[i].invoiceStatusFlag != '0' && tbInvoiceRows[i].invoiceStatusFlag != '1'){
    //         topWin.layer.alert('第'+(i+1)+"行的发票状态非已生效票据，不能提交!", {icon: 0});
    //         return false;
    //     }
    //     if(tbInvoiceRows[i].isCheck != '1' && tbInvoiceRows[i].isCheck != '3' ){
    //         topWin.layer.alert('第'+(i+1)+"行的发票检查结果不通过，不能提交!", {icon: 0});
    //         return false;
    //     }
    // }

    // 对账数量合计
    var statementNum = 0, shareFlag = 0;
    for(var i1 = 0; i1 < detail.length; i1++){
        var row = detail[i1], obj = {};
        obj.id = row.id;
        obj.itemNo = '';
        obj.iaId = id;
        obj.iaNo = iaNo;
        obj.asId = row.asId;
        obj.asNo = row.asNo;
        obj.asdId = row.asdId;
        obj.asdItemNo = row.asdItemNo;
        obj.statementNum = row.statementNum;
        obj.taxCode = row.asTaxCode;
        obj.taxValue = row.asTaxValue;
        obj.notTaxPrice = row.asNotTaxPrice;
        obj.taxPrice = row.asTaxPrice;
        obj.notTaxAmount = row.asNotTaxAmount;
        obj.taxAmount = row.asTaxAmount;
        obj.diffTaxAmount = row.asDiffTaxAmount;
        obj.iaDiffPrice = 0;
        obj.iaDiffAmount = 0;
        obj.receiveId = row.receiveId;
        obj.shareFlag = row.shareFlag;
        obj.shareNum = row.shareNum;
        detailDate.push(obj);

        statementNum = Number(statementNum) + Number(row.statementNum);
        shareFlag = Number(shareFlag) + Number(row.shareFlag);
    }

    // 对账数量
    headData.statementNum = statementNum;

    for(var i2 = 0; i2 < el.delDetail.length; i2++){
        delDetailId.push(el.delDetail[i2].id);
    }

    // 新增对账单返利记录; 待删除的开票申请返利记录
    // var rebate = $(el.tbRebate).datagrid('getRows'), addSrId = [], delSrId = [];
    // for(var j1 = 0; j1 < rebate.length; j1++){
    //     if(0 === rebate[j1].id){
    //         addSrId.push(rebate[j1].srId);
    //     }
    // }
    // for(var j2 = 0; j2 < el.delRebate.length; j2++){
    //     delSrId.push(el.delRebate[j2].id);
    // }

    // 新增对账单扣款记录; 待删除的开票申请扣款记录
    // var deduction = $(el.tbDeduction).datagrid('getRows'), addSdId = [], delSdId = [];
    // for(var k1 = 0; k1 < deduction.length; k1++){
    //     if(0 === deduction[k1].id){
    //         addSdId.push(deduction[k1].sdId);
    //     }
    // }
    // for(var k2 = 0; k2 < el.delDeduction.length; k2++){
    //     delSdId.push(el.delDeduction[k2].id);
    // }

    // 新增关联发票记录; 待删除的关联发票记录
    // var invoice = $(el.tbInvoice).datagrid('getRows'), addInvoice = [], delInvoiceId = [], delInvoice = [];
    // for(var ii1 = 0; ii1 < invoice.length; ii1++){
    //     if('0' === invoice[ii1].id){
    //         addInvoice.push(invoice[i1]);
    //     }
    // }
    // for(var ii2 = 0; ii2 < el.delInvoice.length; ii2++){
    //     delInvoiceId.push(el.delInvoice[ii2].id);
    //     delInvoice.push(el.delInvoice[ii2]);
    // }
    // var advance = $(el.tbAdvance).datagrid('getRows'), paIds = [];
    // for(var k = 0; k < advance.length; k++){
    //     paIds.push(advance[k].id);
    // }
    var dataParams = {};
    dataParams.headData = headData;
    dataParams.detailDate = detailDate;
    dataParams.delDetailIds = delDetailId;
    // dataParams.addSdIds = addSdId;
    // dataParams.delSdIds = delSdId;
    // dataParams.addSrIds = addSrId;
    // dataParams.delSrIds = delSrId;
    // dataParams.addPaIds = paIds;

    // dataParams.delInvoiceId = delInvoiceId;
    // dataParams.delInvoice = delInvoice;
    // dataParams.addInvoice = addInvoice;
    dataParams.invoiceTotalAmount = invoiceTotalAmount;
    dataParams.invoiceTaxTotalAmount = invoiceTaxTotalAmount;
    dataParams.invoicedReceiptData = invoicedReceipt;
    // dataParams.deductionDetailData = getDeductionDetail();
    // endFileEditor();
    // var fileJson = $(el.tbFile).datagrid('getRows')
    // dataParams.fileJson = JSON.stringify(fileJson);
    // dataParams.isBindInvoice = isBindInvoice;

    var loading = topWin.layer.msg('数据保存中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    $.ajax({
        url: g.ctx + 'pc/finance/invoiced/apply/rest/edit',
        type: 'POST',
        data: JSON.stringify(dataParams),
        contentType: 'application/json',
        success: function (data) {
            topWin.layer.close(loading);
            callback(data.id);
        },
        error: function (data) {
            topWin.layer.close(loading);
            topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
        }
    });
}


/**
 * 计算页面相关金额
 */
function calculationAmount(rows) {
    var invoiceTaxAmount = new BigNumber(0), invoiceNetAmount = new BigNumber(0), statementNum = new BigNumber(0),
        rebateAmount = "", rntAmount = $(el.rntAmount).val(),
        deductionAmount = "", dntAmount = $(el.dntAmount).val();
    for (var j = 0; j < rows.length; j++) {
        invoiceTaxAmount = invoiceTaxAmount.plus(rows[j].asTaxAmount);
        invoiceNetAmount = invoiceNetAmount.plus(rows[j].asNotTaxAmount);
        statementNum = statementNum.plus(rows[j].statementNum);
    }

    if(!rebateAmount){
        rebateAmount = 0;
    }

    if(!rntAmount){
        rntAmount = 0;
    }

    if(!deductionAmount){
        deductionAmount = 0;
    }

    if(!dntAmount){
        dntAmount = 0;
    }
    // var advanceDetail = $(el.tbAdvance).datagrid('getRows');
    // var allBudInnerMoney = new BigNumber(0);
    // for (var i = 0; i < advanceDetail.length; i++) {
    //     var item2 = advanceDetail[i];
    //     allBudInnerMoney = allBudInnerMoney.plus(item2.alreadyAdvanceAmount);
    // }
    // 更新页脚行的值并刷新
    var footers = $(el.tbDetails).datagrid('getFooterRows');
    footers[0]['asNotTaxAmount'] = invoiceNetAmount.toFormat(2);
    footers[0]['asTaxAmount'] = invoiceTaxAmount.toFormat(2);
    footers[0]['asDiffTaxAmount'] = invoiceTaxAmount.minus(invoiceNetAmount).toFormat(2);
    footers[0]['statementNum'] = statementNum.toNumber();
    $(el.tbDetails).datagrid('reloadFooter');

    invoiceNetAmount = invoiceNetAmount.plus(dntAmount).plus(rntAmount);
    invoiceTaxAmount = invoiceTaxAmount.plus(deductionAmount).plus(rebateAmount);
    $(el.invoiceNetAmount).textbox('setValue', invoiceNetAmount.toFormat(2));
    $(el.invoiceTaxAmount).textbox('setValue', invoiceTaxAmount.toFormat(2));
    // $(el.allBudInnerMoney).textbox('setValue', allBudInnerMoney.toFormat(2));
}


/**
 * 计算返利金额
 *
 * @param data 返利表格数据
 */
// function calculationRebateAmount(data) {
//     var rebateAmount = new BigNumber(0), rntAmount = new BigNumber(0),
//         deductionAmount = $(el.deductionAmount).numberbox('getValue'), dntAmount = $(el.dntAmount).val(),
//         ntAmount = Number($(el.invoiceNetAmount).textbox('getValue').replace(/,/g,'')),
//         itAmount = Number($(el.invoiceTaxAmount).textbox('getValue').replace(/,/g,''));
//     for(var j = 0; j < data.length; j++){
//         var item = data[j];
//         // 1:购方对供方返利 2:供方对购方返利
//         if(Number(item.rebateType) === 1){
//             rebateAmount = rebateAmount.plus(item.rebateAmount);
//             rntAmount = rntAmount.plus(item.rntAmount);
//         }else {
//             rebateAmount = rebateAmount.minus(item.rebateAmount);
//             rntAmount = rntAmount.minus(item.rntAmount);
//         }
//     }
//
//     if(!deductionAmount){
//         deductionAmount = 0;
//     }
//
//     if(!dntAmount){
//         dntAmount = 0;
//     }
//
//     ntAmount = new BigNumber(ntAmount).plus(rntAmount).plus(dntAmount);
//     itAmount = new BigNumber(itAmount).plus(rebateAmount).plus(deductionAmount);
//     $(el.invoiceNetAmount).textbox('setValue', ntAmount.toFormat(2));
//     $(el.invoiceTaxAmount).textbox('setValue', itAmount.toFormat(2));
//     $(el.rebateAmount).numberbox('setValue', rebateAmount.toNumber());
//     $(el.rntAmount).val(rntAmount);
// }


/**
 * 计算扣款金额
 *
 * @param data 扣款表格数据
 */
// function calculationDeductionAmount(data) {
//     var dtAmount = new BigNumber(0), dntAmount = new BigNumber(0),
//         rebateAmount = $(el.rebateAmount).numberbox('getValue'), rntAmount = $(el.rntAmount).val(),
//         ntAmount = Number($(el.invoiceNetAmount).textbox('getValue').replace(/,/g,'')),
//         itAmount = Number($(el.invoiceTaxAmount).textbox('getValue').replace(/,/g,''));
//     for(var i = 0; i < data.length; i++){
//         var item = data[i];
//         dtAmount = dtAmount.plus(item.deductionAmount);
//         dntAmount = dntAmount.plus(item.dntAmount);
//     }
//
//     ntAmount = new BigNumber(ntAmount).plus(rntAmount).plus(dntAmount);
//     itAmount = new BigNumber(itAmount).plus(rebateAmount).plus(dtAmount);
//     $(el.invoiceNetAmount).textbox('setValue', ntAmount.toFormat(2));
//     $(el.invoiceTaxAmount).textbox('setValue', itAmount.toFormat(2));
//     $(el.deductionAmount).numberbox('setValue', dtAmount.toNumber());
//     $(el.dntAmount).val(dntAmount);
// }


/**
 * 刷新返利和扣款表格数据
 *
 * @param dataRows 剩余开票申请明细
 * @param delAsNo 删除的对账单号
 */
// function refreshRebateAndDeduction(dataRows, delAsNo) {
//     var del = unique(delAsNo);
//     for(var n = 0; n < dataRows.length; n++){
//         var asNo = dataRows[n].asNo;
//         if(del.indexOf(asNo) >= 0){
//             del.splice(del.indexOf(asNo), 1);
//         }
//     }
//
//     var rows1 = $(el.tbRebate).datagrid('getRows');
//     for(var i1 = rows1.length - 1; i1 >= 0; i1--){
//         var row1 = rows1[i1];
//         if(del.indexOf(row1.asNo) >= 0){
//             if(row1.id){
//                 el.delRebate.push(row1);
//             }
//             var rowIndex1 = $(el.tbRebate).datagrid('getRowIndex', row1);
//             $(el.tbRebate).datagrid('deleteRow', rowIndex1);
//         }
//     }
//     // calculationRebateAmount($(el.tbRebate).datagrid('getRows'));
//
//
//     var rows2 = $(el.tbDeduction).datagrid('getRows');
//     for(var i2 = rows2.length - 1; i2 >= 0; i2--){
//         var row2 = rows2[i2];
//         if(del.indexOf(row2.asNo) >= 0){
//             if(row2.id){
//                 el.delDeduction.push(row2);
//             }
//             var rowIndex2 = $(el.tbDeduction).datagrid('getRowIndex', row2);
//             $(el.tbDeduction).datagrid('deleteRow', rowIndex2);
//         }
//     }
//
//     calculationDeductionAmount($(el.tbDeduction).datagrid('getRows'));
// }


/**
 * 刷新返利和扣款表格数据
 */
function addRebateAndDeduction() {
    var rows1 = $(el.tbDetails).datagrid('getRows'), asIds = [], tdSdIds = [], tdSrIds = [];
    for(var i1 = 0; i1 < rows1.length; i1++){
        asIds.push(rows1[i1].asId);
    }

    for(var i3 = 0; i3 < el.delDeduction.length; i3++){
        tdSdIds.push(el.delDeduction[i3].sdId);
    }
    var queryParams1 = $(el.tbDeduction).datagrid('options').queryParams;
    queryParams1.asIds = JSON.stringify(asIds);
    queryParams1.aeSdIds = '';
    queryParams1.tdSdIds = tdSdIds.length === 0 ? '' : JSON.stringify(tdSdIds);
    $(el.tbDeduction).datagrid('options').url = g.ctx + 'fin/account/statement/detail/rest/cia/find/statement/deduction';
    $(el.tbDeduction).datagrid('load');


    for(var i5 = 0; i5 < el.delRebate.length; i5++){
        tdSrIds.push(el.delRebate[i5].srId);
    }
    var queryParams2 = $(el.tbRebate).datagrid('options').queryParams;
    queryParams2.asIds = JSON.stringify(asIds);
    queryParams2.aeSrIds = '';
    queryParams2.tdSrIds = tdSrIds.length === 0 ? '' : JSON.stringify(tdSrIds);
    $(el.tbRebate).datagrid('options').url = g.ctx + 'fin/account/statement/detail/rest/cia/find/statement/rebate';
    $(el.tbRebate).datagrid('load');

    calculationAmount(rows1);
}


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


/**
 * 查看扣款或返利附件
 *
 * @param ele 当前操作DOM节点
 */
function lookDrAttachment(ele) {
    var drId = $(ele).data('id'), attType = $(ele).data('type');
    var url = g.ctx + 'fin/common/look/dr/attachment?drId=' + drId + '&attType=' + attType;
    var lookDrAttDialog = openDialog('lookDrAtt', url, {
        title: '附件查看',
        width: '35%',
        height: '45%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            lookDrAttDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    lookDrAttDialog.dialog('close');
                }
            }
        ]
    });
}


/**
 * 处理凭证尾差
 */
function handleVoucherTail() {
    // 需要处理统计行中 未税金额 != 含税金额 / (1 + 税率)
    var taxValue = new BigNumber(1), itSumAmount = new BigNumber(0), ntSumAmount = new BigNumber(0);
    var rows = $(el.tbDetails).datagrid('getRows');
    var maxAmount = new BigNumber(0), maxAmountRowIndex = -1, maxAdtAmount = new BigNumber(0), maxAntAmount = new BigNumber(0);
    for (var n = 0; n < rows.length; n++) {
        var item = rows[n];
        ntSumAmount = ntSumAmount.plus(item.asNotTaxAmount);
        itSumAmount = itSumAmount.plus(item.asTaxAmount);
        taxValue = new BigNumber(item.asTaxValue);

        if(maxAmount.eq(0)){
            maxAmount = new BigNumber(item.asTaxAmount);
            maxAmount = new BigNumber(item.asTaxAmount);
            maxAdtAmount = new BigNumber(item.asDiffTaxAmount);
            maxAntAmount = new BigNumber(item.asNotTaxAmount);
        }
        if(!maxAmount.eq(0) && maxAmount.lt(item.asTaxAmount) && Number(item.shareFlag) === 1){
            maxAmount = new BigNumber(item.asTaxAmount);
            maxAdtAmount = new BigNumber(item.asDiffTaxAmount);
            maxAntAmount = new BigNumber(item.asNotTaxAmount);
            maxAmountRowIndex = $(el.tbDetails).datagrid('getRowIndex', item);
        }
    }

    var tax = taxValue.div(100).plus(1);
    // 表体明细相加的含税金额除以税率减去表体明细相加的未税金额, 如果差异超过±0.01(包含±0.01), 需要将差异加到表体含税金额最大一行中
    var diff = itSumAmount.div(tax).minus(ntSumAmount);
    var diffNum = Number(diff.abs().toFixed(2));
    if(diffNum >= 0.01){
        var adtAmount = maxAdtAmount.minus(diff).toFixed(2);
        var antAmount = maxAntAmount.plus(diff).toFixed(2);

        $(el.tbDetails).datagrid('updateRow', {
            index: maxAmountRowIndex,
            row: {
                asDiffTaxAmount: adtAmount,
                asNotTaxAmount: antAmount
            }
        });
    }
}


/**
 * 获取当前用户表格列布局
 */
function findUserTableColumn() {
    $.ajax({
        type: 'POST',
        url: g.ctx + 'fin/table/column/rest/user/setting?pageTable=3&isAuthority=0',
        async: false,
        success: function (data) {
            for(var i = 0; i < data.length; i++){
                el.userTableColumn.push(data[i].columnField);
            }
        }
    });
}


/**
 * 动态表格列
 */
// function dynamicColumns(orderType) {
//     var result = [];
//     for(var i = 0; i < el.userTableColumn.length; i++){
//         var columnField = el.userTableColumn[i];
//
//         for(var j = 0; j < tableColumns.length; j++){
//             var column =  tableColumns[j];
//             if(column.field === columnField){
//
//                 if(column.field === 'materialSupplierCode' || column.field === 'materialSupplierName' || column.field === 'freightType'){
//                     column.hidden = Number(orderType) === 1;
//                 }
//
//                 result.push(column);
//                 break;
//             }
//         }
//     }
//
//     return result;
// }


// 报表所有列
var tableColumns = [
    {
        field: 'statementNum',
        title: '对账数量',
        width: 70,
        sortable: true,
        formatter: function (value) {
            if(Number(value) < 0){
                return '<span style="color: red;">' + value + '</span>';
            }
            return value;
        }
    },
    {
        field: 'asTaxCodeDesc',
        title: '对账税率',
        width: 160,
        sortable: true
    },
    {
        field: 'asTaxPrice',
        title: '对账含税单价',
        width: 100,
        sortable: true
    },
    {
        field: 'asTaxAmount',
        title: '对账含税金额',
        width: 100,
        sortable: true,
        formatter: function (value) {
            if(Number(value) < 0){
                return '<span style="color: red;">' + formatNumber(value, 2, 1) + '</span>';
            }
            return formatNumber(value, 2, 1);
        }
    },
    {
        field: 'asNotTaxPrice',
        title: '对账未税单价',
        width: 100,
        sortable: true
    },
    {
        field: 'asNotTaxAmount',
        title: '对账未税金额',
        width: 100,
        sortable: true,
        formatter: function (value) {
            if(Number(value) < 0){
                return '<span style="color: red;">' + formatNumber(value, 2, 1) + '</span>';
            }
            return formatNumber(value, 2, 1);
        }
    },
    {
        field: 'asDiffTaxAmount',
        title: '对账税额',
        width: 100,
        sortable: true,
        formatter: function (value) {
            if(Number(value) < 0){
                return '<span style="color: red;">' + formatNumber(value, 2, 1) + '</span>';
            }
            return formatNumber(value, 2, 1);
        }
    },
    {
        field: 'zlsdh',
        title: 'SC订单号',
        width: 100,
        sortable: true
    },
    {
        field: 'poCode',
        title: 'SAP订单号',
        width: 100,
        sortable: true
    },
    {
        field: 'poItemNo',
        title: '订单行号',
        width: 70,
        sortable: true
    },
    {
        field: 'materialCode',
        title: '物料编码',
        width: 90,
        sortable: true
    },
    {
        field: 'materialName',
        title: '物料名称',
        width: 320,
        sortable: true
    },
    {
        field: 'specs',
        title: '规格',
        width: 120
    },
    {
        field: 'receiveCode',
        title: '入库凭证号',
        width: 100,
        sortable: true
    },
    {
        field: 'receiveRowNo',
        title: '凭证行号',
        width: 70,
        sortable: true
    },
    {
        field: 'receiveDate',
        title: '入库日期',
        width: 100,
        sortable: true
    },
    {
        field: 'inOutFlag',
        title: '出入库标识',
        width: 85,
        sortable: true
    },
    {
        field: 'asNo',
        title: '对账单号',
        width: 140,
        sortable: true
    },
    {
        field: 'asdItemNo',
        title: '对账单行号',
        width: 80,
        sortable: true
    },
    {
        field: 'contractNo',
        title: '合同号',
        width: 120
    }
];