/**
 * 对账模块-开票申请单采购确认页面JS
 *
 * Created by li.kui on 2020/8/15.
 */
'use strict';
var el = {
    dataPanel: '#dataPanel',
    dataDiv: '#dataDiv',
    deductionAmountTotal: '#deductionAmountTotal',
    id: '#id',
    iaNo: '#invoiceApplyNo',
    orderType: '#orderType',
    supplierCode: '#supplierCode',
    supplierName: '#supplierName',
    localCurrency: '#localCurrency',
    originalCurrency: '#originalCurrency',
    advanceLocalCurrency: '#advanceLocalCurrency',
    advanceOriginalCurrency: '#advanceOriginalCurrency',
    companyCode: '#companyCode',
    companyName: '#companyNameDesc',
    factoryCode: '#factoryCode',
    currencyCode: '#currencyCode',
    dntAmount: '#dntAmount',
    deductionAmount: '#deductionAmount',
    rntAmount: '#rntAmount',
    rebateAmount: '#rebateAmount',
    invoiceNetAmount: '#invoiceNetAmount',
    strikePriceAmount: '#strikePriceAmount',
    remark: '#remark',
    actualUnpaidAmount: '#actualUnpaidAmount',
    invoiceTaxAmount: '#invoiceTaxAmount',
    invoiceNum: '#invoiceNum',
    invoiceNo: '#invoiceNo',
    approveRemark: '#approveRemark',
    dataTabs: '#dataTabs',
    tbDetails: '#tbDetails',
    tbFile: '#tbFile',
    tbDeduction: '#tbDeduction',
    diffAmount1: '#diffAmount1',
    tbRebate: '#tbRebate',
    tbIaApprove: '#tbIaApprove',
    addDetailDialog: null,
    addRebateDialog: null,
    addDeductionDialog: null,
    delRebate: [],
    delDeduction: [],
    editIndex: undefined,
    editAdvanceIndex: undefined,
    taxDict: [],
    tableColumns: [],
    userTableColumn: [],
    bodyHeight: document.documentElement.clientHeight,

    tbInvoice: '#tbInvoice',
    allBudInnerMoney: '#allBudInnerMoney',
    tbAdvance: '#tbAdvance',
    invoiceTotalAmount: '#invoiceTotalAmount',
    invoiceTaxTotalAmount: '#invoiceTaxTotalAmount',
    diffAmount: '#diffAmount',
    delInvoice: [],
    delDetail: [],
    typeName : 'purchase_confirm'
};


/**
 * 文档就绪
 */
$(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.tbApproveLog).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.tbApproveLog).datagrid('resize', {height: el.bodyHeight - dataDiv});
        }
    });
    initPageInput();
    // findUserTableColumn();

    findTaxDictData1();

    initTbIaApprove();

    // 以下三张表的加载顺序不能乱
    // 原因: 在计算扣款或者返利表格的页脚数据时首先需要将扣款或者返利的表格初始化出来
    // initTbRebate();

    // initTbDeduction();

    initTbDetails();

    initTbAdvance();

});
/**
 * 初始化页面输入框
 */
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 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: {invoiceApplyId:$(el.id).val()},
        url: g.ctx + 'pc/finance/invoiced/apply/pa/rest/find/paa/findPaaDetailByInvoiceApplyId',
        // url: g.ctx + 'fin/payment/advance/apply/rest/find/paa/findPaaDetailByPurchaseOrderDetailIds',
        frozenColumns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                },
                {
                    field: 'zlsdh',
                    title: 'SC订单号',
                    width:140
                },
                {
                    field: 'oldPoCode',
                    title: '旧订单号',
                    width:120
                },
                {
                    field: 'poCode',
                    title: '采购订单',
                    width: 200,
                    sortable: true
                },
                {
                    field: 'poItemNo',
                    title: '订单行号',
                    width: 200,
                    sortable: true
                }
            ]
        ],
        columns: [
            [
                {
                    field: 'applyPrice',
                    title: '预付款金额',
                    width: 200,
                    sortable: true,
                    formatter:function (value) {
                        if (!value) {
                            return '';
                        }
                        return  formatNumber(value, 4, 1).toString().replace(/(?:\.0*|(\.\d+?)0+)$/,'$1');
                    }
                },
                {
                    field: 'strikePrice',
                    title: '本次冲账金额',
                    width: 200,
                    sortable: true,
                    formatter:function (value) {
                        if (!value) {
                            return '';
                        }
                        return  formatNumber(value, 4, 1).toString().replace(/(?:\.0*|(\.\d+?)0+)$/,'$1');
                    },
                    editor: {
                        type: 'numberbox',
                        options: {
                            precision: 2,
                            onChange: function (nv, ov) {
                                console.log(nv)
                                console.log(ov)
                                if(nv){
                                    updateAdvanceRowData(nv, 'strikePrice');
                                }
                            }
                        }
                    }
                },
                {
                    field: 'yearNum',
                    title: '年度',
                    width:100
                },
                {
                    field: 'currencyCode',
                    title: '币种',
                    width:100
                },
                {
                    field: 'applyNo',
                    title: '预付款凭证号',
                    width:140
                },
                {
                    field: 'applyItemNo',
                    title: '预付款凭证行号',
                    width:120
                },
                {
                    field: 'remark',
                    title: '摘要',
                    width:200
                },

            ]
        ],
        toolbar: [
            {
                text: '添加',
                iconCls: 'icon-add',
                handler: function () {
                    addAdvanceItem();
                }
            },
            '-',
            {
                text: '删除',
                iconCls: 'icon-remove',
                handler: function () {
                    delAdvanceItem();
                }
            }
        ],
        rowStyler: function (index, row) {
            if (!checkAdvanceOrderNoExit(row.zlsdh)) {
                return 'background-color:#f8d594;';
            }
        },
        onClickRow: function (index, row) {
            if (el.editAdvanceIndex !== undefined) {
                if(endAdvanceEditor()){
                    beginAdvanceEditor(index, row);
                }
            }else {
                beginAdvanceEditor(index, row);
            }
        },
        onLoadSuccess: function () {
            $(el.tbAdvance).datagrid('selectAll');
            calculationAdvancePageAmount();
        }
    });
}

function addAdvanceItem() {
    var companyCode = $(el.companyCode).val(),invoiceApplyId = $(el.id).val(),
        supplierCode = $(el.supplierCode).textbox('getValue');
    var url = g.ctx + 'pc/finance/invoiced/apply/chose/advance/detail/dialog?companyCode=' + companyCode +
        '&supplierCode=' + supplierCode + '&invoiceApplyId=' + invoiceApplyId;
    el.addDetailDialog = openDialog('choseAdvanceDetail', url, {
        title: '选择预付款明细',
        width: '75%',
        height: '75%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.addDetailDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '确定',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['choseAdvanceDetail'].confirmChose(function (data) {
                        let old_advance = $(el.tbAdvance).datagrid('getRows');
                        for(var n = 0; n < data.length; n++){
                            var item = data[n], row = {};
                            //去重
                            let sameFlag = false;
                            for (let j = 0; j < old_advance.length; j++) {
                                if (item.poCode === old_advance[j].poCode&&item.poItemNo === old_advance[j].poItemNo&&item.applyNo === old_advance[j].applyNo&&item.applyItemNo === old_advance[j].applyItemNo) {
                                    sameFlag = true;
                                    break;
                                }
                            }
                            if (sameFlag) {
                                continue;
                            }
                            row.oldPoCode = item.oldPoCode;
                            row.poCode = item.poCode;
                            row.poItemNo = item.poItemNo;
                            row.applyPrice = item.applyPrice;
                            row.strikePrice = item.applyPrice;
                            row.yearNum = item.yearNum;
                            row.currencyCode = item.currencyCode;
                            row.applyNo = item.applyNo;
                            row.applyItemNo = item.applyItemNo;
                            row.sysInvoiceNo = item.sysInvoiceNo;
                            row.remark = item.remark;
                            row.zlsdh = item.zlsdh;
                            row.specialFlag = item.specialFlag;
                            $(el.tbAdvance).datagrid('appendRow', row);
                        }
                        el.addDetailDialog.dialog('close');
                        calculationAdvancePageAmount();
                    });
                }
            },
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.addDetailDialog.dialog('close');
                }
            }
        ]
    });
}
function delAdvanceItem() {
    var rows = $(el.tbAdvance).datagrid('getSelections');
    if(rows.length === 0){
        topWin.layer.alert('请选择您要删除的数据', {icon: 0});
        return false;
    }
    for(var i = 0; i < rows.length; i++){
        var item = rows[i];
        var rowIndex = $(el.tbAdvance).datagrid('getRowIndex', item);
        $(el.tbAdvance).datagrid('deleteRow', rowIndex);
    }
    calculationAdvancePageAmount();
}
function checkAdvanceOrderNoExit(zlsdh){
    var tbDetails = $(el.tbDetails).datagrid('getRows');
    var su = false;
    for (var i = 0; i < tbDetails.length; i++) {
        var item = tbDetails[i];
        if (item.zlsdh===zlsdh){
            su = true
        }
    }
    return su;
}
function  calculationAdvancePageAmount(){
    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.applyPrice);
    }
    $(el.allBudInnerMoney).val(allBudInnerMoney.toFormat(2));
    $(el.strikePriceAmount).textbox('setValue', allBudInnerMoney.toFormat(2));

    var detail = $(el.tbDetails).datagrid('getRows'), rebate = "", deduction = "";
    var itAmount = new BigNumber(0), ntAmount = new BigNumber(0), diffAmount = new BigNumber(0);
    for (var i = 0; i < detail.length; i++) {
        var item1 = detail[i];
        ntAmount = ntAmount.plus(item1.asNotTaxAmount);
        itAmount = itAmount.plus(item1.asTaxAmount);
        diffAmount = diffAmount.plus(item1.diffTaxAmount);
    }
    $(el.invoiceNetAmount).textbox('setValue', ntAmount.toFormat(2));
    $(el.invoiceTaxAmount).textbox('setValue', itAmount.toFormat(2));
    $(el.diffAmount).textbox('setValue', diffAmount.toFormat(2));

    var invoiceTaxAmount = $(el.invoiceTaxAmount).textbox('getValue');
    var deductionAmountTotal = new BigNumber(0)
    // if ($(el.deductionAmountTotal).textbox('getValue')){
    //     deductionAmountTotal = $(el.deductionAmountTotal).textbox('getValue').replace(/,/g,'');
    //     deductionAmountTotal = Math.abs(Number(deductionAmountTotal));
    //     deductionAmountTotal = new BigNumber(deductionAmountTotal);
    // }
    $(el.actualUnpaidAmount).textbox('setValue', new BigNumber(invoiceTaxAmount.replace(/,/g,'')).minus(allBudInnerMoney).minus(deductionAmountTotal).toFormat(2));
}
/**
 * 获取税率字典数据
 */
function findTaxDictData1() {
    $.ajax({
        type: 'GET',
        url: g.ctx + 'pc/sys/tax/rest/listAll',
        async: false,
        success: function (data) {
            for(var i = 0; i < data.length; i++){
                var obj = {};
                obj.itemCode = data[i].taxCode;
                obj.itemName = data[i].taxName;
                obj.itemValue = data[i].taxValue;
                obj.itemRemark = data[i].taxName;
                el.taxDict.push(obj);
            }
        }
    });


}



/**
 * 初始化开票申请明细表格
 */
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: 1
        },
        frozenColumns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                }
            ]
        ],
        columns: [
            el.tableColumns
        ],
        toolbar: [
            {
                text: '添加',
                iconCls: 'icon-add',
                handler: function () {
                    addStatementItem();
                }
            },
            '-',
            {
                text: '删除',
                iconCls: 'icon-remove',
                handler: function () {
                    delStatementItem();
                }
            },
            '-',
            {
                text: '导出',
                iconCls: 'icon-download',
                handler: function () {
                    detailDataExport();
                }
            },
            '-',
            {
                text: '填充应付未清金额',
                iconCls: 'icon-ok',
                handler: function () {
                    payableOutstanding();
                }
            },  '-',{
                text: '      税率切换计算方式：<select type="number" id="taxSelect" style="width: 100px;height: 25px!important;"><option value="0" selected>含税不变</option><option value="1">未税不变</option></select>'
            }
            // '-',
            // {
            //     text: '调整布局',
            //     iconCls: 'icon-man',
            //     handler: function () {
            //         adjustTableColumn();
            //     }
            // }
        ],
        onClickRow: function (index, row) {
            if (el.editIndex !== undefined) {
                if(endEditor()){
                    beginEditor(index, row);
                }
            }else {
                beginEditor(index, row);
            }
        },
        onLoadSuccess: function () {
            // handleVoucherTail();
            // refreshAdvance();
            calculationPageAmount();

        }
    });
}

function payableOutstanding() {

    var companyCode = $(el.companyCode).val();
    var  supplierCode = $(el.supplierCode).textbox('getValue');
    var  currencyCode = $(el.currencyCode).textbox('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,
            currency:currencyCode
        },
        beforeSend: function () {
            topWin.layer.load(1);
        },
        complete: function () {
            topWin.layer.closeAll('loading');
        },
        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 refreshAdvance(){
//     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');
//     calculationAdvancePageAmount();
// }
/**
 * 计算表头金额
 */
function  calculationPageAmount() {
    // 需要处理统计行中 未税金额 != 含税金额 / (1 + 税率)
    var taxValue = new BigNumber(1), itSumAmount = new BigNumber(0), ntSumAmount = new BigNumber(0);
    var maxAmount = new BigNumber(0), maxAmountRowIndex = -1, maxAdtAmount = new BigNumber(0), maxAntAmount = new BigNumber(0);
    var rows = $(el.tbDetails).datagrid('getRows');
    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);
            maxAdtAmount = new BigNumber(item.asDiffTaxAmount);
            maxAntAmount = new BigNumber(item.asNotTaxAmount);
            maxAmountRowIndex = $(el.tbDetails).datagrid('getRowIndex', item);
        }
        if(!maxAmount.eq(0) && maxAmount.lt(item.asTaxAmount)){
            maxAmount = new BigNumber(item.asTaxAmount);
            maxAdtAmount = new BigNumber(item.asDiffTaxAmount);
            maxAntAmount = new BigNumber(item.asNotTaxAmount);
            maxAmountRowIndex = $(el.tbDetails).datagrid('getRowIndex', item);
        }
    }

    // 创建的时候不需要一下逻辑(下面的逻辑:保证表体合计含税金额=表体合计未税金额*(1+税率))
    // var tax = taxValue.div(100).plus(1);
    // // 表体明细相加的含税金额除以税率减去表体明细相加的未税金额, 如果差异超过±0.01(包含±0.01), 需要将差异加到表体含税金额最大一行中
    // var diff = itSumAmount.div(tax).sub(ntSumAmount);
    // var diffNum = Number(diff.abs().toFixed(2));
    // if(diffNum >= 0.01){
    //     var adtAmount = maxAdtAmount.sub(diff).toFixed(2);
    //     var antAmount = maxAntAmount.plus(diff).toFixed(2);
    //
    //     $(el.tbDetails).datagrid('updateRow', {
    //         index: maxAmountRowIndex,
    //         row: {
    //             asDiffTaxAmount: adtAmount,
    //             asNotTaxAmount: antAmount
    //         }
    //     });
    // }

    var detail = $(el.tbDetails).datagrid('getRows'), rebate = "", deduction = "";
    var itAmount = new BigNumber(0), ntAmount = new BigNumber(0), statementNum = new BigNumber(0);
    for (var i = 0; i < detail.length; i++) {
        var item1 = detail[i];
        ntAmount = ntAmount.plus(item1.asNotTaxAmount);
        itAmount = itAmount.plus(item1.asTaxAmount);
        statementNum = statementNum.plus(item1.statementNum);
    }

    // var advanceDetail = $(el.tbAdvance).datagrid('getSelections');
    // var allBudInnerMoney = new BigNumber(0);
    // for (var i = 0; i < advanceDetail.length; i++) {
    //     var item2 = advanceDetail[i];
    //     allBudInnerMoney = allBudInnerMoney.plus(item2.alreadyAdvanceAmount);
    // }

    // var rtAmount = new BigNumber(0), rntAmount = new BigNumber(0);
    // for(var j = 0; j < rebate.length; j++){
    //     var item2 = rebate[j];
    //     // 1:购方对供方返利 2:供方对购方返利
    //     if(Number(item2.rebateType) === 1){
    //         rtAmount = rtAmount.plus(item2.rebateAmount);
    //         rntAmount = rntAmount.plus(item2.rntAmount);
    //     }else {
    //         rtAmount = rtAmount.minus(item2.rebateAmount);
    //         rntAmount = rntAmount.minus(item2.rntAmount);
    //     }
    // }

    // var dtAmount = new BigNumber(0), dntAmount = new BigNumber(0);
    // for(var k = 0; k < deduction.length; k++){
    //     var item3 = deduction[k];
    //     dtAmount = dtAmount.plus(item3.deductionAmount);
    //     dntAmount = dntAmount.plus(item3.dntAmount);
    // }

    if(0 !== rows.length){
        // 更新页脚行的值并刷新
        var footers = $(el.tbDetails).datagrid('getFooterRows');
        footers[0]['asNotTaxAmount'] = ntAmount.toFormat(2);
        footers[0]['asTaxAmount'] = itAmount.toFormat(2);
        footers[0]['asDiffTaxAmount'] = itAmount.minus(ntAmount).toFormat(2);
        footers[0]['statementNum'] = statementNum.toNumber();
        $(el.tbDetails).datagrid('reloadFooter');
    }else {
        // 更新页脚行并载入新数据
        $(el.tbDetails).datagrid('reloadFooter', [
            {
                asNotTaxAmount: 0,
                asTaxAmount: 0,
                asDiffTaxAmount: 0,
                statementNum: 0
            }
        ]);
    }

    // ntAmount = ntAmount.plus(rntAmount).plus(dntAmount);
    // itAmount = itAmount.plus(rtAmount).plus(dtAmount);
    $(el.invoiceNetAmount).textbox('setValue', ntAmount);
    $(el.invoiceTaxAmount).textbox('setValue', itAmount);
    $(el.diffAmount).textbox('setValue', itAmount.minus(ntAmount));
    // $(el.allBudInnerMoney).textbox('setValue', allBudInnerMoney.toFormat(2));
    // $(el.rebateAmount).numberbox('setValue', Number(rtAmount.toFixed(2)));
    // $(el.rntAmount).val(Number(rntAmount.toFixed(2)));
    // $(el.deductionAmount).numberbox('setValue', Number(dtAmount.toFixed(2)));
    // $(el.dntAmount).val(Number(dntAmount.toFixed(2)));
}

/**
 * 初始化返利信息表格
 */
// function initTbRebate() {
//     var dataDiv = $(el.dataDiv).outerHeight() + 90;
//
//     $(el.tbRebate).datagrid({
//         loadMsg: '数据加载中, 请耐心等待......',
//         height: el.bodyHeight - dataDiv,
//         url: g.ctx + 'fin/invoiced/apply/detail/rest/find/rebate/by/apply/id',
//         singleSelect: false,
//         showFooter: true,
//         rownumbers: true,
//         // 定义从服务器对数据进行排序
//         remoteSort: false,
//         // 定义是否允许多列排序
//         // multiSort: true,
//         pagination: false,
//         queryParams: {iaId: $(el.id).val()},
//         frozenColumns: [
//             [
//                 {
//                     field: 'ck',
//                     checkbox: true
//                 },
//                 {
//                     field: 'rebateId',
//                     title: '附件查看',
//                     width: 80,
//                     formatter: function (value) {
//                         if(value){
//                             return '<a href="javascript:void(0)" onclick="lookDrAttachment(this)" data-type="2" data-id="' + value + '">查看</a>';
//                         }
//                         return '';
//                     }
//                 },
//                 {
//                     field: 'asNo',
//                     title: '对账单号',
//                     width: 130,
//                     sortable: true
//                 },
//                 {
//                     field: 'rebateNo',
//                     title: '返利单号',
//                     width: 140,
//                     sortable: true
//                 },
//                 {
//                     field: 'rebateType',
//                     title: '返利类型',
//                     width: 120,
//                     sortable: true,
//                     formatter: function (value) {
//                         if(Number(value) === 1){
//                             return '购方对供方返利';
//                         }
//                         if(Number(value) === 2) {
//                             return '供方对购方返利';
//                         }
//                         return '';
//                     }
//                 },
//                 {
//                     field: 'rebateAmount',
//                     title: '含税返利金额(元)',
//                     width: 110,
//                     sortable: true,
//                     formatter: function (value) {
//                         if (!value) {
//                             return '';
//                         }
//                         return formatNumber(value, 2, 1);
//                     }
//                 },
//                 {
//                     field: 'taxCodeDesc',
//                     title: '税率',
//                     width: 160,
//                     sortable: true
//                 }
//             ]
//         ],
//         columns: [
//             [
//                 {
//                     field: 'rebateReason',
//                     title: '返利原因',
//                     width: 300
//                 },
//                 {
//                     field: 'rebateTime',
//                     title: '返利时间',
//                     width: 110,
//                     sortable: true,
//                     formatter: function (value) {
//                         if (value) {
//                             return moment(value).format("YYYY-MM-DD");
//                         }
//                         return '';
//                     }
//                 },
//                 {
//                     field: 'companyCode',
//                     title: '公司代码',
//                     width: 80
//                 },
//                 {
//                     field: 'companyName',
//                     title: '公司名称',
//                     width: 180
//                 },
//                 {
//                     field: 'supplierCode',
//                     title: '供应商编码',
//                     width: 90
//                 },
//                 {
//                     field: 'supplierName',
//                     title: '供应商名称',
//                     width: 270
//                 },
//                 {
//                     field: 'createTime',
//                     title: '创建时间',
//                     width: 140,
//                     sortable: true,
//                     formatter: function (value) {
//                         if (value) {
//                             return moment(value).format("YYYY-MM-DD HH:mm:ss");
//                         }
//                         return '';
//                     }
//                 }
//             ]
//         ],
//         toolbar: [
//             {
//                 text: '添加',
//                 iconCls: 'icon-add',
//                 handler: function () {
//                     addRebateData();
//                 }
//             },
//             '-',
//             {
//                 text: '删除',
//                 iconCls: 'icon-remove',
//                 handler: function () {
//                     delRebateData();
//                 }
//             }
//         ],
//         onLoadSuccess: function () {
//             refreshTbRebateFooter();
//         }
//     });
// }


/**
 * 初始化扣款信息表格
 */
// function initTbDeduction() {
//     var dataDiv = $(el.dataDiv).outerHeight() + 90;
//
//     $(el.tbDeduction).datagrid({
//         loadMsg: '数据加载中, 请耐心等待......',
//         height: el.bodyHeight - dataDiv,
//         url: g.ctx + 'fin/invoiced/apply/detail/rest/find/deduction/by/apply/id',
//         singleSelect: false,
//         showFooter: true,
//         rownumbers: true,
//         // 定义从服务器对数据进行排序
//         remoteSort: false,
//         // 定义是否允许多列排序
//         // multiSort: true,
//         pagination: false,
//         queryParams: {iaId: $(el.id).val()},
//         frozenColumns: [
//             [
//                 {
//                     field: 'ck',
//                     checkbox: true
//                 },
//                 {
//                     field: 'deductionId',
//                     title: '附件查看',
//                     width: 80,
//                     formatter: function (value) {
//                         if(value){
//                             return '<a href="javascript:void(0)" onclick="lookDrAttachment(this)" data-type="1" data-id="' + value + '">查看</a>';
//                         }
//                         return '';
//                     }
//                 },
//                 {
//                     field: 'asNo',
//                     title: '对账单号',
//                     width: 140,
//                     sortable: true
//                 },
//                 {
//                     field: 'deductionNo',
//                     title: '扣款编号',
//                     width: 140,
//                     sortable: true
//                 },
//                 {
//                     field: 'deductionTypeDesc',
//                     title: '扣款类型',
//                     width: 90,
//                     sortable: true
//                 },
//                 {
//                     field: 'deductionAmount',
//                     title: '含税扣款金额(元)',
//                     width: 110,
//                     sortable: true,
//                     formatter: function (value) {
//                         if (!value) {
//                             return '';
//                         }
//                         return formatNumber(value, 2, 1);
//                     }
//                 },
//                 {
//                     field: 'taxCodeDesc',
//                     title: '税率',
//                     width: 160,
//                     sortable: true
//                 }
//             ]
//         ],
//         columns: [
//             [
//                 {
//                     field: 'deductionReason',
//                     title: '扣款原因',
//                     width: 300
//                 },
//                 {
//                     field: 'deductionTime',
//                     title: '扣款时间',
//                     width: 90,
//                     sortable: true,
//                     formatter: function (value) {
//                         if (value) {
//                             return moment(value).format("YYYY-MM-DD");
//                         }
//                         return '';
//                     }
//                 },
//                 {
//                     field: 'associatedOaNo',
//                     title: 'OA流程单号',
//                     width: 120,
//                     sortable: true
//                 },
//                 {
//                     field: 'associatedNo',
//                     title: 'SRM业务单据',
//                     width: 140,
//                     formatter: function (value, row) {
//                         if(!row.associatedRowNo){
//                             return value;
//                         }else {
//                             return value + '|' + row.associatedRowNo;
//                         }
//                     }
//                 },
//                 {
//                     field: 'companyCode',
//                     title: '公司代码',
//                     width: 80
//                 },
//                 {
//                     field: 'companyName',
//                     title: '公司名称',
//                     width: 180
//                 },
//                 {
//                     field: 'supplierCode',
//                     title: '供应商编码',
//                     width: 90
//                 },
//                 {
//                     field: 'supplierName',
//                     title: '供应商名称',
//                     width: 270
//                 },
//                 {
//                     field: 'createTime',
//                     title: '创建时间',
//                     width: 140,
//                     sortable: true,
//                     formatter: function (value) {
//                         if (value) {
//                             return moment(value).format("YYYY-MM-DD HH:mm:ss");
//                         }
//                         return '';
//                     }
//                 }
//             ]
//         ],
//         toolbar: [
//             {
//                 text: '添加',
//                 iconCls: 'icon-add',
//                 handler: function () {
//                     addDeductionData();
//                 }
//             },
//             '-',
//             {
//                 text: '删除',
//                 iconCls: 'icon-remove',
//                 handler: function () {
//                     delDeductionData();
//                 }
//             }
//         ],
//         onLoadSuccess: function () {
//             refreshTbDeductionFooter();
//         }
//     });
// }


/**
 * 初始化审批信息表格
 */
function initTbIaApprove() {
    var dataDiv = $(el.dataDiv).outerHeight() + 90;

    $(el.tbIaApprove).datagrid({
        loadMsg: '数据加载中, 请耐心等待......',
        height: el.bodyHeight - dataDiv,
        url: g.ctx + 'pc/finance/invoiced/apply/detail/rest/find/ia/approve/log',
        singleSelect: false,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        remoteSort: false,
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: true,
        queryParams: {
            iaId: $(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 addStatementItem() {
    var companyCode = $(el.companyCode).val(), factoryCode = $(el.factoryCode).val(), currencyCode = $(el.currencyCode).val(),
        supplierCode = $(el.supplierCode).textbox('getValue'), iaNo = $(el.iaNo).textbox('getValue'), iaId = $(el.id).val(),
        orderType = $(el.orderType).val();
    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 +
        '&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) {
                        el.addDetailDialog.dialog('close');
                        if(data.length > 0){
                            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.taxCode = item.asTaxCode;
                                row.taxDesc = item.asTaxDesc;
                                row.taxValue = item.asTaxValue;
                                row.taxCodeDesc = item.asTaxCodeDesc;
                                row.notTaxPrice = item.asNotTaxPrice;
                                row.taxPrice = item.asTaxPrice;
                                row.notTaxAmount = item.asNotTaxAmount;
                                row.taxAmount = item.asTaxAmount;
                                row.diffTaxAmount = item.asDiffTaxAmount;
                                row.iaDiffPrice = 0;
                                row.iaDiffAmount = 0;
                                // 物料凭证相关
                                row.receiveId = item.receiveId;
                                row.receiveCode = item.receiveCode;
                                row.receiveRowNo = item.receiveRowNo;
                                row.receiveNum = item.receiveNum;
                                row.receiveDate = item.receiveDate;
                                row.receiveYear = item.receiveYear;
                                row.materialCode = item.materialCode;
                                row.materialName = item.materialName;
                                row.inOutFlag = item.inOutFlag;
                                // 对账单相关
                                row.asNotTaxPrice = item.asNotTaxPrice;
                                row.asTaxPrice = item.asTaxPrice;
                                row.asNotTaxAmount = item.asNotTaxAmount;
                                row.asTaxAmount = item.asTaxAmount;
                                row.asDiffTaxAmount = item.asDiffTaxAmount;
                                row.asDiffPrice = item.asDiffPrice;
                                row.asDiffAmount = item.asDiffAmount;
                                row.asTaxCode = item.asTaxCode;
                                row.asTaxDesc = item.asTaxDesc;
                                row.asTaxCodeDesc = item.asTaxCodeDesc;
                                row.asTaxValue = item.asTaxValue;
                                // 采购订单相关
                                row.poCode = item.poCode;
                                row.poItemNo = item.poItemNo;
                                row.paymentTermCode = item.paymentTermCode;
                                row.paymentTermName = item.paymentTermName;
                                row.paymentTermCodeName = item.paymentTermCodeName;
                                row.paymentWayCode = item.paymentWayCode;
                                row.paymentWayDesc = item.paymentWayDesc;
                                row.paymentWayCodeDesc = item.paymentWayCodeDesc;
                                row.pgCode = item.pgCode;
                                row.pgName = item.pgName;
                                row.pgCodeName = item.pgCodeName;
                                row.seekPgCode = item.seekPgCode;
                                row.seekPgName = item.seekPgName;
                                row.seekPgCodeName = item.seekPgCodeName;
                                row.poNotTaxPrice = item.poNotTaxPrice;
                                row.poTaxPrice = item.poTaxPrice;
                                row.poNotTaxAmount = item.poNotTaxAmount;
                                row.poTaxAmount = item.poTaxAmount;
                                row.asNtAmount = item.asNtAmount;
                                row.asItAmount = item.asItAmount;
                                row.asDtAmount = item.asDtAmount;
                                row.poTaxCode = item.poTaxCode;
                                row.poTaxDesc = item.poTaxDesc;
                                row.poTaxCodeDesc = item.poTaxCodeDesc;
                                row.poTaxValue = item.poTaxValue;
                                row.supplierCode = item.supplierCode;
                                row.supplierName = item.supplierName;
                                row.companyCode = item.companyCode;
                                row.companyName = item.companyName;
                                row.materialSupplierCode = item.materialSupplierCode;
                                row.materialSupplierName = item.materialSupplierName;
                                row.freightType = item.freightType;
                                row.shareFlag = item.shareFlag;
                                row.shareNum = item.shareNum;
                                // 分摊后金额
                                row.shareRntAmount = 0;
                                row.sraTaxAmount = 0;
                                row.shareRebateAmount = 0;
                                row.shareDntAmount = 0;
                                row.sdaTaxAmount = 0;
                                row.shareDeductionAmount = 0;
                                row.shareAfterNta = item.asNotTaxAmount;
                                row.shareAfterTa = item.asDiffTaxAmount;
                                row.shareAfterIta = item.asTaxAmount;

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


/**
 * 删除对账单明细数据
 */
function delStatementItem() {
    // 将el.editIndex设置为undefined
    el.editIndex = undefined;

    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++){
        var rowIndex = $(el.tbDetails).datagrid('getRowIndex', rows[n]);
        $(el.tbDetails).datagrid('endEdit', rowIndex);

        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], delAsNo = [];
                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);
            }

            // refreshRebateAndDeduction(delAsNo);

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


/**
 * 明细导出
 */
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 adjustTableColumn() {
    var url = g.ctx + 'fin/common/adjust/table/column?pageTable=3';
    el.adjustTableColumnDialog = openDialog('adjustTableColumn', url, {
        title: '调整表格列布局',
        width: '970px',
        height: '80%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.adjustTableColumnDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '确定并保存设置',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['adjustTableColumn'].confirmAndSaveSetUp(function (data) {
                        el.userTableColumn = [];
                        for(var i = 0; i < data.length; i++){
                            el.userTableColumn.push(data[i].columnField);
                        }

                        initTbDetails();
                        el.adjustTableColumnDialog.dialog('close');
                    });
                }
            },
            {
                text: '确定',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['adjustTableColumn'].confirmSetUp(function (data) {
                        el.userTableColumn = [];
                        for(var i = 0; i < data.length; i++){
                            el.userTableColumn.push(data[i].columnField);
                        }

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


/**
 * 添加返利数据
 */
function addRebateData() {
    var rows1 = $(el.tbDetails).datagrid('getRows'), asIds = [];
    for(var i = 0; i < rows1.length; i++){
        asIds.push(rows1[i].asId);
    }

    var rows2 = $(el.tbRebate).datagrid('getSelections'), aeSrIds = [];
    for(var j = 0; j < rows2.length; j++){
        aeSrIds.push(rows2[j].srId);
    }

    var tempDelSrId = [];
    for(var k = 0; k < el.delRebate.length; k++){
        tempDelSrId.push(el.delRebate[k].srId);
    }

    var asIdStr = asIds.length === 0 ? '' : asIds.join(',');
    var aeSrIdStr = aeSrIds.length === 0 ? '' : aeSrIds.join(',');
    var tdSrIdStr = tempDelSrId.length === 0 ? '' : tempDelSrId.join(',');

    var url = g.ctx + 'fin/invoiced/apply/chose/statement/rebate/dialog?asIds=' + asIdStr +
        '&alreadyExistSrIds=' + aeSrIdStr + '&tempDelSrId=' + tdSrIdStr;
    el.choseRebateDataDialog = openDialog('choseStatementRebate', url, {
        title: '对账返利信息选择',
        width: '1000px',
        height: '560px',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.choseRebateDataDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '确定',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['choseStatementRebate'].confirmChose(function (data) {
                        el.choseRebateDataDialog.dialog('close');
                        if(data.length > 0){
                            for(var n = 0; n < data.length; n++){
                                var item = data[n], row = {};
                                row.id = 0;
                                row.asNo = item.asNo;
                                row.srId = item.srId;
                                row.iaId = $(el.id).val();
                                row.companyCode = item.companyCode;
                                row.companyName = item.companyName;
                                row.createTime = item.createTime;
                                row.createUserCode = item.createUserCode;
                                row.createUserName = item.createUserName;
                                row.createUserId = item.createUserId;
                                row.rebateAmount = item.rebateAmount;
                                row.rntAmount = item.rntAmount;
                                row.rebateId = item.rebateId;
                                row.rebateNo = item.rebateNo;
                                row.rebateReason = item.rebateReason;
                                row.rebateType = item.rebateType;
                                row.rebateTime = item.rebateTime;
                                row.supplierCode = item.supplierCode;
                                row.supplierName = item.supplierName;
                                row.taxValue = item.taxValue;
                                row.taxCode = item.taxCode;
                                row.taxCodeDesc = item.taxCodeDesc;

                                $(el.tbRebate).datagrid('appendRow', row);
                            }
                            addOrDelDataAgainCountAmount();
                        }
                    });
                }
            },
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.choseRebateDataDialog.dialog('close');
                }
            }
        ]
    });
}


/**
 * 删除返利数据
 */
function delRebateData() {
    var rows = $(el.tbRebate).datagrid('getSelections');
    if(rows.length === 0){
        topWin.layer.alert('请选择您要删除的返利信息', {icon: 0});
        return false;
    }

    var srList = [];
    for(var i = 0; i < rows.length; i++){
        var item = rows[i], obj = {};
        obj.asNo = item.asNo;
        obj.rebateNo = item.rebateNo;

        srList.push(obj);
    }

    // 开票申请明细中的对账单明细ID
    var details = $(el.tbDetails).datagrid('getRows'), asdIdList = [];
    for(var j = 0; j < details.length; j++){
        asdIdList.push(details[j].asdId);
    }

    var loading = topWin.layer.msg('校验选中的行是否可以删除, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    $.ajax({
        type: 'POST',
        url: g.ctx + 'fin/invoiced/apply/detail/rest/check/statement/rebate/use',
        data: {
            srList: JSON.stringify(srList),
            iaAsdIdList: JSON.stringify(asdIdList)
        },
        success: function () {
            topWin.layer.close(loading);
            for(var n = 0; n < rows.length; n++){
                var row = rows[n];
                if(row.id){
                    el.delRebate.push(row);
                }
                var rowIndex = $(el.tbRebate).datagrid('getRowIndex', row);
                $(el.tbRebate).datagrid('deleteRow', rowIndex);
            }

            addOrDelDataAgainCountAmount();
        },
        error: function (data) {
            topWin.layer.close(loading);
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });
}


/**
 * 添加扣款
 */
function addDeductionData() {
    var rows1 = $(el.tbDetails).datagrid('getRows'), asIds = [];
    for(var i = 0; i < rows1.length; i++){
        asIds.push(rows1[i].asId);
    }

    var rows2 = $(el.tbDeduction).datagrid('getSelections'), aeSdIds = [];
    for(var j = 0; j < rows2.length; j++){
        aeSdIds.push(rows2[j].sdId);
    }

    var tempDelSdId = [];
    for(var k = 0; k < el.delDeduction.length; k++){
        tempDelSdId.push(el.delDeduction[k].sdId);
    }

    var asIdStr = asIds.length === 0 ? '' : asIds.join(',');
    var aeSdIdStr = aeSdIds.length === 0 ? '' : aeSdIds.join(',');
    var tdSdIdStr = tempDelSdId.length === 0 ? '' : tempDelSdId.join(',');

    var url = g.ctx + 'fin/invoiced/apply/chose/statement/deduction/dialog?asIds=' + asIdStr +
        '&alreadyExistSdIds=' + aeSdIdStr + '&tempDelSdId=' + tdSdIdStr;
    el.addDeductionDialog = openDialog('choseStatementDeduction', url, {
        title: '对账扣款信息选择',
        width: '1000px',
        height: '560px',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.addDeductionDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '确定',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['choseStatementDeduction'].confirmChose(function (data) {
                        el.addDeductionDialog.dialog('close');

                        if(data.length > 0){
                            for(var n = 0; n < data.length; n++){
                                var item = data[n], row = {};
                                row.id = 0;
                                row.asNo = item.asNo;
                                row.sdId = item.sdId;
                                row.iaId = $(el.id).val();
                                row.companyCode = item.companyCode;
                                row.companyName = item.companyName;
                                row.createTime = item.createTime;
                                row.deductionAmount = item.deductionAmount;
                                row.dntAmount = item.dntAmount;
                                row.deductionId = item.deductionId;
                                row.deductionNo = item.deductionNo;
                                row.deductionReason = item.deductionReason;
                                row.deductionType = item.deductionType;
                                row.deductionTypeDesc = item.deductionTypeDesc;
                                row.deductionTime = item.deductionTime;
                                row.supplierCode = item.supplierCode;
                                row.supplierName = item.supplierName;
                                row.associatedNo = item.associatedNo;
                                row.associatedRowNo = item.associatedRowNo;
                                row.taxValue = item.taxValue;
                                row.taxCode = item.taxCode;
                                row.taxCodeDesc = item.taxCodeDesc;

                                $(el.tbDeduction).datagrid('appendRow', row);
                            }
                            addOrDelDataAgainCountAmount();
                        }
                    });
                }
            },
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.addDeductionDialog.dialog('close');
                }
            }
        ]
    });
}


/**
 * 删除扣款
 */
function delDeductionData() {
    var rows = $(el.tbDeduction).datagrid('getSelections');
    if(rows.length === 0){
        topWin.layer.alert('请选择您要删除的扣款信息', {icon: 0});
        return false;
    }

    // 待删除的对账扣款数据
    var sdList = [];
    for(var i = 0; i < rows.length; i++){
        var item = rows[i], obj = {};
        obj.asNo = item.asNo;
        obj.deductionNo = item.deductionNo;

        sdList.push(obj);
    }

    // 开票申请明细中的对账单明细ID
    var details = $(el.tbDetails).datagrid('getRows'), asdIdList = [];
    for(var j = 0; j < details.length; j++){
        asdIdList.push(details[j].asdId);
    }


    var loading = topWin.layer.msg('校验选中的行是否可以删除, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    $.ajax({
        type: 'POST',
        url: g.ctx + 'fin/invoiced/apply/detail/rest/check/statement/deduction/use',
        data: {
            sdList: JSON.stringify(sdList),
            iaAsdIdList: JSON.stringify(asdIdList)
        },
        success: function () {
            topWin.layer.close(loading);
            for(var n = 0; n < rows.length; n++){
                var row = rows[n];
                if(row.id){
                    el.delDeduction.push(row);
                }
                var rowIndex = $(el.tbDeduction).datagrid('getRowIndex', row);
                $(el.tbDeduction).datagrid('deleteRow', rowIndex);
            }

            addOrDelDataAgainCountAmount();
        },
        error: function (data) {
            topWin.layer.close(loading);
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });
}


/**
 * 数据保存
 */
function dataSave(approveStatus,callback) {
    endAdvanceEditor();
    endInvoiceOtherEditor();
    var id = $(el.id).val(), invoiceTaxAmount = $(el.invoiceTaxAmount).textbox('getValue'),
        invoiceNetAmount = $(el.invoiceNetAmount).textbox('getValue'), rebateAmount = "",
        deductionAmount = "", invoiceNum = $(el.invoiceNum).numberbox('getValue'),
        invoiceNo = $(el.invoiceNo).textbox('getValue'),
        invoiceTaxTotalAmount = $(el.invoiceTaxTotalAmount).textbox('getValue'),
        strikePriceAmount = $(el.strikePriceAmount).textbox('getValue'),
        remark = $(el.remark).val(),
        actualUnpaidAmount = $(el.actualUnpaidAmount).textbox('getValue'),
        // deductionAmountTotal = $(el.deductionAmountTotal).textbox('getValue'),
        diffAmount1 = $(el.diffAmount1).textbox('getValue'),
        diffAmount = $(el.diffAmount).textbox('getValue'),
        approveRemark = $(el.approveRemark).val(), rntAmount = $(el.rntAmount).val(),allBudInnerMoney = $(el.allBudInnerMoney).val(),
        dntAmount = $(el.dntAmount).val(),
        localCurrency = $(el.localCurrency).textbox('getValue'),
        originalCurrency = $(el.originalCurrency).textbox('getValue'),
        advanceLocalCurrency = $(el.advanceLocalCurrency).textbox('getValue'),
        advanceOriginalCurrency = $(el.advanceOriginalCurrency).textbox('getValue');

    if (remark.length<1) {
        topWin.layer.alert('请填写备注', {icon: 0});
        return false;
    }
    // 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(!approveRemark){
        topWin.layer.alert('请输入审批意见', {icon: 0});
        return false;
    }



    var headData = {};
    headData.id = id;
    headData.invoiceTaxAmount = Number(invoiceTaxAmount.replace(/,/g,''));
    headData.invoiceNetAmount = Number(invoiceNetAmount.replace(/,/g,''));
    headData.rebateAmount = rebateAmount;
    headData.rntAmount = rntAmount;
    headData.deductionAmount = deductionAmount;
    headData.allBudInnerMoney = Number(allBudInnerMoney.replace(/,/g,''));
    headData.strikePriceAmount = Number(strikePriceAmount.replace(/,/g,''));
    headData.actualUnpaidAmount = Number(actualUnpaidAmount.replace(/,/g,''));
    // headData.deductionAmountTotal = Number(deductionAmountTotal.replace(/,/g,''));
    headData.dntAmount = dntAmount;
    headData.invoiceNum = invoiceNum;
    headData.remark = remark;
    headData.invoiceNo = invoiceNo;
    // headData.invoiceTotalAmount = $(el.invoiceTotalAmount).textbox('getValue');
    headData.invoiceTaxTotalAmount = $(el.invoiceTaxTotalAmount).textbox('getValue');
    headData.supplierName = $(el.supplierName).textbox('getValue');

    headData.localCurrency = localCurrency;
    headData.originalCurrency = originalCurrency;
    headData.advanceLocalCurrency = advanceLocalCurrency;
    headData.advanceOriginalCurrency = advanceOriginalCurrency;
    // 开票申请明细数据; 待删除开票申请明细ID delDetailIds
    var detail = $(el.tbDetails).datagrid('getRows'), detailDate = [], delDetailId = [],
        invoicedReceipt = $(el.tbInvoice).datagrid('getRows'),leshuiItem = []
        ,taxData = [],paymentTermCode =  [],is101Flag = false;
    if (approveStatus===1){
    if (detail.length === 0) {
        topWin.layer.alert('请选择对账明细数据', {icon: 0});
        return false;
    }
    if (invoicedReceipt.length === 0) {
        topWin.layer.alert('请添加关联发票信息', {icon: 0});
        return false;
    }
    }
    for(var i1 = 0; i1 < detail.length; i1++){
        var rowIndex = $(el.tbDetails).datagrid('getRowIndex', detail[i1]);
        $(el.tbDetails).datagrid('endEdit', rowIndex);

        detailDate.push(detail[i1]);
        taxData.push(detail[i1].taxCode);
        paymentTermCode.push(detail[i1].paymentTermCode);
        //是否包含101 102 122 123
        if(["101","102","122","123"].indexOf(detail[i1].sapMoveType) >= 0 && !is101Flag){
            is101Flag = true;
        }
    }
    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;
        // }
    }
    for(var i2 = 0; i2 < el.delDetail.length; i2++){
        delDetailId.push(el.delDetail[i2].id);
    }

    if (approveStatus===1){
        //发票凭证金额不允许为负数
        if(Number(invoiceTaxAmount) <= 0 && is101Flag){
            topWin.layer.alert('开票含税总金额必须大于零', {icon: 0});
            return false;
        }
        // 检查对账单明细中对账税率是否都相同
        if(!checkIsAllEqual(taxData)){
            topWin.layer.alert('明细中税率不相同', {icon: 0});
            return false;
        }
        // 检查对账单明细中付款条件是否都相同
        if(!checkIsAllEqual(paymentTermCode)){
            topWin.layer.alert('明细中付款条件不相同', {icon: 0});
            return false;
        }

        if(strikePriceAmount&&Number(strikePriceAmount.replace(/,/g,'')) > Number(invoiceTaxAmount.replace(/,/g,''))){
            if (Number(strikePriceAmount.replace(/,/g,''))!==0){
                topWin.layer.alert('冲账总金额不能大于开票含税总金额', {icon: 0});
                return false;
            }
        }

        if(Number(invoiceTaxTotalAmount.replace(/,/g,'')) !== Number(invoiceTaxAmount.replace(/,/g,''))){
            topWin.layer.alert('发票含税总金额必须等于开票含税总金额', {icon: 0});
            return false;
        }

        if(Number(diffAmount1.replace(/,/g,'')) !== Number(diffAmount.replace(/,/g,''))){
            topWin.layer.alert('发票税额必须等于开票税额', {icon: 0});
            return false;
        }
    }

    // 新增对账单返利记录; 待删除的开票申请返利记录
    // 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 advances = $(el.tbAdvance).datagrid('getRows'), paIds = [];
    for(var ii = 0; ii < advances.length; ii++){
            if(advances[ii].strikePrice > advances[ii].applyPrice){
                topWin.layer.alert('预付款信息：第'+(ii+1)+"行本次冲账金额不能大于预付款金额，不能提交!", {icon: 0});
                return false;
            }
    }


    // for(var i11 = 0; i11 < detail.length; i11++){
    //     for(var kk = 0; kk < advance.length; kk++){
    //         if ()
    //     }
    // }

    //校验发票
    // 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;
    //     }
    // }

    // endInvoiceEditor();
    var tbInvoiceRows = $(el.tbInvoice).datagrid('getRows');
   /* if (tbInvoiceRows.length<=0&&approveStatus===1){
        topWin.layer.alert('请添加发票信息', {icon: 0});
        return false;
    }*/

    var dataParams = {};
    dataParams.headData = headData;
    dataParams.detailDate = detailDate;
    dataParams.delDetailIds = delDetailId;
    dataParams.invoicedReceipts = JSON.stringify(tbInvoiceRows);
    dataParams.invoicedReceiptData = invoicedReceipt;
    // dataParams.deductionDetailData = getDeductionDetail();
    // dataParams.addSdIds = addSdId;
    // dataParams.delSdIds = delSdId;
    // dataParams.addSrIds = addSrId;
    // dataParams.delSrIds = delSrId;
    dataParams.approveRemark = approveRemark;
    dataParams.invoiceNetAmount =  Number($(el.invoiceNetAmount).textbox('getValue').replace(/,/g,''));
    dataParams.invoiceTaxAmount =  Number($(el.invoiceTaxAmount).textbox('getValue').replace(/,/g,''));
    // dataParams.isBindInvoice = isBindInvoice;
    // dataParams.invoiceTotalAmount = Number($(el.invoiceTotalAmount).textbox('getValue').replace(/,/g,''));
    // dataParams.invoiceTaxTotalAmount = Number($(el.invoiceTaxTotalAmount).textbox('getValue').replace(/,/g,''));
    dataParams.addPaIds = paIds;
    dataParams.addAdvances = advances;
    callback(dataParams);
}


/**
 * 启动行编辑
 */
function beginEditor(rowIndex, row) {
    var dntAmount = $(el.dntAmount).val(), rntAmount = $(el.rntAmount).val();
    // if(Number(row.shareFlag) === 0){
    //     topWin.layer.msg('该行不可以编辑');
    //     return false;
    // }
    $(el.tbDetails).datagrid('beginEdit', rowIndex);
    el.editIndex = rowIndex;

    var editors = $(el.tbDetails).datagrid('getEditors', rowIndex);
    if(Number(rntAmount) === 0){
        editors[4].target.numberbox('disable');
        editors[5].target.numberbox('disable');
    }
    if(Number(dntAmount) === 0){
        editors[6].target.numberbox('disable');
        editors[7].target.numberbox('disable');
    }
}


/**
 * 启动行编辑
 */
function beginAdvanceEditor(rowIndex, row) {

    $(el.tbAdvance).datagrid('beginEdit', rowIndex);
    el.editAdvanceIndex = rowIndex;
}

/**
 * 结束编辑
 *
 * @return {boolean}
 */
function endEditor() {
    // 结束行编辑
    $(el.tbDetails).datagrid('endEdit', el.editIndex);
    $(el.tbDetails).datagrid('unselectRow', el.editIndex);
    el.editIndex = undefined;
    return true;
}

function endAdvanceEditor() {
    // 结束行编辑
    $(el.tbAdvance).datagrid('endEdit', el.editAdvanceIndex);
    $(el.tbAdvance).datagrid('unselectRow', el.editAdvanceIndex);
    el.editAdvanceIndex = undefined;
    return true;
}


/**
 * 更新行数数据
 *
 * @param data 修改后的数据
 * @param editColumn 编辑的列名
 */
function updateRowData(data, editColumn) {
    var row = {}, rows = $(el.tbDetails).datagrid('getRows');
    for(var i = 0; i < rows.length; i++){
        var rowIndex = $(el.tbDetails).datagrid('getRowIndex', rows[i]);
        if(rowIndex === el.editIndex){
            row = rows[i];
            break;
        }
    }

    // 税率转换: 1 + 税率
    var taxConvert = new BigNumber(1).plus(row.taxValue / 100);

    // 修改的字段 到票含税单价、到票未税金额、到票税额、到票税率

    // 到票含税单价 -> 联动变更的行数据: 到票不含税单价、到票差异含税单价、到票不含税金额、到票含税金额、到票差异含税金额、到票税额
    if('taxPrice' === editColumn){
        // 修改后的数据
        var ud1 = new BigNumber(data);

        // 到票含税金额 = 对账数量 * 到票含税单价
        var taxAmount1 = ud1.multipliedBy(row.statementNum);
        // 到票不含税单价 = 到票含税单价 / (1 + 税率)
        var notTaxPrice1 = ud1.div(taxConvert);
        // 到票差异含税单价 = 到票含税单价 - 对账含税单价
        var iaDiffPrice1 = ud1.minus(row.asTaxPrice);
        // 到票未税金额 = 含税金额 / (1 + 税率)
        var notTaxAmount1 = taxAmount1.div(taxConvert);
        // 到票差异含税金额 = 对账数量 * 到票差异含税单价
        var iaDiffAmount1 = iaDiffPrice1.multipliedBy(row.statementNum);
        // // 到票税额 = 到票含税金额 - 到票未税金额
        // var diffTaxAmount1 = taxAmount1.sub(notTaxAmount1);
        // 到票税额 = 到票含税金额(四舍五入保留2位) - 到票未税金额(四舍五入保留2位)
        var diffTaxAmount1 = Number(taxAmount1.toFixed(2)) - Number(notTaxAmount1.toFixed(2));

        // 更新Editor列数据(initValue 不触发numberBox的onChange事件)
        var notTaxAmountTarget1 = $(el.tbDetails).datagrid('getEditor', {index: el.editIndex,field: 'notTaxAmount'}).target;
        notTaxAmountTarget1.numberbox('initValue', Number(notTaxAmount1.toFixed(2)));

        // 更新Editor列数据(initValue 不触发numberBox的onChange事件)
        var diffTaxAmountTarget1 = $(el.tbDetails).datagrid('getEditor', {index: el.editIndex,field: 'diffTaxAmount'}).target;
        diffTaxAmountTarget1.numberbox('initValue', Number(diffTaxAmount1.toFixed(2)));

        // 更新非Editor列数据
        var columns1 = ['notTaxPrice', 'iaDiffPrice', 'taxAmount', 'iaDiffAmount'];
        var columnsData1 = [
            Number(notTaxPrice1.toFixed(6)), Number(iaDiffPrice1.toFixed(6)), Number(taxAmount1.toFixed(2)),
            Number(iaDiffAmount1.toFixed(2))
        ];
        var ed1 = $(el.tbDetails).datagrid('getEditor', {index: el.editIndex,field: 'taxPrice'});
        updatePageShowValue($(ed1.target).parents('td[field="taxPrice"]'), row, columns1, columnsData1);

        row.taxPrice = Number(ud1.toFixed(6));

        editDataAgainCountAmount();
    }

    // 到票未税金额 -> 联动变更的行数据 到票含税金额、到票差异含税金额、到票含税单价、到票不含税单价、到票差异含税单价
    if('notTaxAmount' === editColumn){
        // 修改后的数据
        var ud2 = new BigNumber(data);

        // 到票含税金额 = 到票未税金额 + 税额
        var taxAmount2 = ud2.plus(row.diffTaxAmount);
        // 到票含税单价 = 到票含税金额 / 对账数量
        var taxPrice2 = taxAmount2.div(row.statementNum);
        // 到票未税单价 = 到票未税金额 / 对账数量
        var notTaxPrice2 = ud2.div(row.statementNum);
        // 到票差异含税单价 = 到票含税单价 - 对账含税单价
        var iaDiffPrice2 = taxPrice2.minus(row.asTaxPrice);
        // 到票差异含税金额 = 对账数量 * 到票差异含税单价
        var iaDiffAmount2 = iaDiffPrice2.multipliedBy(row.statementNum);

        // 更新Editor列数据(initValue 不触发numberBox的onChange事件)
        var taxPriceTarget1 = $(el.tbDetails).datagrid('getEditor', {index: el.editIndex, field: 'taxPrice'}).target;
        taxPriceTarget1.numberbox('initValue', Number(taxPrice2.toFixed(6)));

        // 更新非Editor列数据
        var columns2 = ['taxAmount', 'iaDiffAmount', 'notTaxPrice', 'iaDiffPrice'];
        var columnsData2 = [
            Number(taxAmount2.toFixed(2)), Number(iaDiffAmount2.toFixed(2)), Number(notTaxPrice2.toFixed(6)),
            Number(iaDiffPrice2.toFixed(6))
        ];
        var ed2 = $(el.tbDetails).datagrid('getEditor', {index: el.editIndex,field: 'notTaxAmount'});
        updatePageShowValue($(ed2.target).parents('td[field="notTaxAmount"]'), row, columns2, columnsData2);

        row.notTaxAmount = Number(ud2.toFixed(2));

        // var loading = topWin.layer.msg('正在计算表体分摊金额, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
        editDataAgainCountAmount();
    }

    // 到票税额 -> 联动变更的行数据 到票含税金额、到票差异含税金额、到票含税单价、到票差异含税单价
    if('diffTaxAmount' === editColumn){
        // 修改后的数据
        var ud3 = new BigNumber(data);

        // 到票含税金额 = 税额 + 到票未税金额
        var taxAmount3 = ud3.plus(row.notTaxAmount);
        // 到票含税单价 = 到票含税金额 / 对账数量
        var taxPrice3 = taxAmount3.div(row.statementNum);
        // 到票差异含税单价 = 到票含税单价 - 对账含税单价
        var iaDiffPrice3 =taxPrice3.minus(row.asTaxPrice);
        // 到票差异含税金额 = 对账数量 * 到票差异含税单价
        var iaDiffAmount3 = iaDiffPrice3.multipliedBy(row.statementNum);

        // 更新Editor列数据(initValue 不触发numberBox的onChange事件)
        var taxPriceTarget3 = $(el.tbDetails).datagrid('getEditor', {index: el.editIndex,field: 'taxPrice'}).target;
        taxPriceTarget3.numberbox('initValue', Number(taxPrice3.toFixed(6)));

        // 更新非Editor列数据
        var columns3 = ['taxAmount', 'iaDiffAmount', 'iaDiffPrice'];
        var columnsData3 = [
            Number(taxAmount3.toFixed(2)), Number(iaDiffAmount3.toFixed(2)), Number(iaDiffPrice3.toFixed(6))
        ];
        var ed3 = $(el.tbDetails).datagrid('getEditor', {index: el.editIndex,field: 'diffTaxAmount'});
        updatePageShowValue($(ed3.target).parents('td[field="diffTaxAmount"]'), row, columns3, columnsData3);

        row.diffTaxAmount = Number(ud3.toFixed(2));

        editDataAgainCountAmount();
    }

    // 到票税率 -> 联动变更的行数据 到票未税单价、到票未税金额、到票税额
    if('taxCodeDesc' === editColumn){
        var taxData = {};
        for(var j = 0; j < el.taxDict.length; j++){
            if(el.taxDict[j].itemName === data){
                taxData = el.taxDict[j];
                break;
            }
        }
        // 税率转换 = 1 + 税率值
        // var tax = taxData.itemValue.replace('%', '');
        var tax = new BigNumber(taxData.itemName.match(/\d+/g)[0]);
        taxConvert = new BigNumber(1).plus(tax / 100);

        var taxAmount = new BigNumber(row.taxAmount);
        // 到票未税单价 = 到票含税单价 / (1 + 税率)
        var notTaxPrice4 = new BigNumber(row.taxPrice).div(taxConvert);
        // 到票未税金额 = 含税金额 / (1 + 税率)
        var notTaxAmount4 = taxAmount.div(taxConvert);
        // // 到票税额 = 到票含税金额 - 到票未税金额
        // var diffTaxAmount4 = taxAmount.sub(notTaxAmount4);
        // 到票税额 = 到票含税金额(四舍五入保留2位) - 到票未税金额(四舍五入保留2位)
        var diffTaxAmount4 = Number(taxAmount.toFixed(2)) - Number(notTaxAmount4.toFixed(2));

        // 更新非Editor列数据
        var columns4 = ['notTaxPrice'];
        var columnsData4 = [Number(notTaxPrice4.toFixed(6))];
        var ed4 = $(el.tbDetails).datagrid('getEditor', {index: el.editIndex, field: 'taxCodeDesc'});
        updatePageShowValue($(ed4.target).parents('td[field="taxCodeDesc"]'), row, columns4, columnsData4);

        var notTaxAmountTarget4 = $(el.tbDetails).datagrid('getEditor', {index: el.editIndex,field: 'notTaxAmount'}).target;
        notTaxAmountTarget4.numberbox('initValue', Number(notTaxAmount4.toFixed(2)));

        var diffTaxAmountTarget4 = $(el.tbDetails).datagrid('getEditor', {index: el.editIndex,field: 'diffTaxAmount'}).target;
        diffTaxAmountTarget4.numberbox('initValue', Number(diffTaxAmount4.toFixed(2)));

        // 更新非页面显示列数据
        row.taxCode = taxData.itemCode;
        row.taxValue = Number(tax);

        editDataAgainCountAmount();
    }

    if ('taxCodeDesc1' === editColumn) {
        var taxData = {};
        for (var j = 0; j < el.taxDict.length; j++) {
            if (el.taxDict[j].itemName === data) {
                taxData = el.taxDict[j];
                break;
            }
        }
        // 税率转换 = 1 + 税率值
        var tax = new BigNumber(taxData.itemName.match(/\d+/g)[0]);
        taxConvert = new BigNumber(1).plus(tax / 100);

        var taxAmount = new BigNumber(row.taxAmount);
        // 到票含税单价 = 到票未税单价 * (1 + 税率)
        var taxPrice4 = new BigNumber(row.notTaxPrice).multipliedBy(taxConvert);
        console.log(taxPrice4)
        // 到票含税金额 = 含税金额 / (1 + 税率)
        var taxAmount4 = taxPrice4.multipliedBy(row.statementNum);
        console.log(taxAmount4)
        // // 到票税额 = 到票含税金额 - 到票未税金额
        // var diffTaxAmount4 = taxAmount.sub(notTaxAmount4);
        // 到票税额 = 到票含税金额(四舍五入保留2位) - 到票未税金额(四舍五入保留2位)
        var diffTaxAmount4 = Number(taxAmount4.toFixed(2)) - Number(new BigNumber(row.notTaxAmount).toFixed(2));

        // 更新非Editor列数据
        var columns4 = ['taxAmount'];
        var columnsData4 = [Number(taxAmount4.toFixed(2))];
        var ed4 = $(el.tbDetails).datagrid('getEditor', {index: el.editIndex, field: 'taxCodeDesc'});
        updatePageShowValue($(ed4.target).parents('td[field="taxCodeDesc"]'), row, columns4, columnsData4);

        var taxPriceTarget4 = $(el.tbDetails).datagrid('getEditor', {
            index: el.editIndex,
            field: 'taxPrice'
        }).target;
        taxPriceTarget4.numberbox('initValue', Number(taxPrice4.toFixed(2)));

        var diffTaxAmountTarget4 = $(el.tbDetails).datagrid('getEditor', {
            index: el.editIndex,
            field: 'diffTaxAmount'
        }).target;
        diffTaxAmountTarget4.numberbox('initValue', Number(diffTaxAmount4.toFixed(2)));

        // 更新非页面显示列数据
        row.taxCode = taxData.itemCode;
        row.taxValue = Number(tax);

        editDataAgainCountAmount();
    }

    // 分摊返利未税金额 -> 联动变更的行数据 分摊返利税金
    // if('shareRntAmount' === editColumn){
    //     var srAmount1 = new BigNumber(row.shareRebateAmount), ud5 = new BigNumber(data);
    //     // 分摊返利税金 = 分摊返利含税 - 分摊返利未税
    //     var srt = srAmount1.sub(ud5);
    //     var srtTarget = $(el.tbDetails).datagrid('getEditor', {index: el.editIndex,field: 'sraTaxAmount'}).target;
    //     srtTarget.numberbox('initValue', Number(srt.toFixed(2)));
    //
    //     refreshRebShare(ud5, srAmount1, srt);
    // }

    // 分摊返利税金 -> 联动变更的行数据 分摊返利未税金额
    // if('sraTaxAmount' === editColumn){
    //     var srAmount2 = new BigNumber(row.shareRebateAmount), ud6 = new BigNumber(data);
    //     // 分摊返利未税 = 分摊返利含税 - 分摊返利税金
    //     var srn = srAmount2.sub(ud6);
    //     var srnTarget = $(el.tbDetails).datagrid('getEditor', {index: el.editIndex,field: 'shareRntAmount'}).target;
    //     srnTarget.numberbox('initValue', Number(srn.toFixed(2)));
    //
    //     refreshRebShare(srn, srAmount2, ud6);
    // }

    // 分摊扣款未税金额 -> 联动变更的行数据 分摊扣款税金
    // if('shareDntAmount' === editColumn){
    //     var sdAmount1 = new BigNumber(row.shareDeductionAmount), ud7 = new BigNumber(data);
    //     // 分摊扣款税金 = 分摊扣款含税 - 分摊扣款未税
    //     var sdt = sdAmount1.sub(ud7);
    //     var sdtTarget = $(el.tbDetails).datagrid('getEditor', {index: el.editIndex,field: 'sdaTaxAmount'}).target;
    //     sdtTarget.numberbox('initValue', Number(sdt.toFixed(2)));
    //
    //     refreshDedShare(ud7, sdAmount1, sdt);
    // }

    // 分摊扣款税金 -> 联动变更的行数据 分摊扣款未税金额
    // if('sdaTaxAmount' === editColumn){
    //     var sdAmount2 = new BigNumber(row.shareDeductionAmount), ud8 = new BigNumber(data);
    //     // 分摊扣款未税金额 = 分摊扣款含税 - 分摊扣款税金
    //     var sdn = sdAmount2.sub(ud8);
    //     var sdnTarget = $(el.tbDetails).datagrid('getEditor', {index: el.editIndex,field: 'shareDntAmount'}).target;
    //     sdnTarget.numberbox('initValue', Number(sdn.toFixed(2)));
    //
    //     refreshDedShare(sdn, sdAmount2, ud8);
    // }
}

function updateAdvanceRowData(data, editColumn) {
    var row = {}, rows = $(el.tbAdvance).datagrid('getRows');
    for(var i = 0; i < rows.length; i++){
        var rowIndex = $(el.tbAdvance).datagrid('getRowIndex', rows[i]);
        if(rowIndex === el.editAdvanceIndex){
            row = rows[i];
            break;
        }
    }
    if('strikePrice' === editColumn){

        var strikePriceAmount= new BigNumber(0)
        for (var i = 0; i < rows.length; i++) {
            var item = rows[i];
            var rowIndex = $(el.tbAdvance).datagrid('getRowIndex', item);

            var strikePrice = item.strikePrice?Number(item.strikePrice):0;
            if(el.editAdvanceIndex === rowIndex){
                var strikePriceEditor = $(el.tbAdvance).datagrid('getEditor', {index: el.editAdvanceIndex, field: 'strikePrice'}).target;
                strikePrice = strikePriceEditor.numberbox('getValue');
            }
            strikePriceAmount = strikePriceAmount.plus(strikePrice);
        }
        $(el.strikePriceAmount).textbox('setValue', strikePriceAmount.toFormat(2));
        var invoiceTaxAmount = $(el.invoiceTaxAmount).textbox('getValue');
        $(el.actualUnpaidAmount).textbox('setValue', new BigNumber(invoiceTaxAmount).minus(strikePriceAmount).toFormat(2));
    }
}
/**
 * 刷新返利和扣款表格数据
 *
 * @param delAsNo 删除的对账单号
 */
function refreshRebateAndDeduction(delAsNo) {
    var dataRows = $(el.tbDetails).datagrid('getRows');
    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);
        }
    }

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


/**
 * 新增或删除数据时重新计算表头、表体分摊和表体统计行中的金额
 *
 * 1.重新计算表头金额字段
 * 2.刷新表格页脚数据
 * 3.分摊逻辑
 */
function addOrDelDataAgainCountAmount() {
    // 结束行编辑
    endEditor();

    // 调用顺序不能乱(原因: 计算分摊金额时需要知道表头金额数据)
    // 计算表头金额
    countPageHeadAmount();

    // 计算表体分摊金额
    // calculationShare(0);

    // 刷新表体统计行金额
    refreshTbDetailFooter();
}



/**
 * 编辑明细行数据是重新计算表头、表体分摊和表体统计行中的金额
 *
 * 1.重新计算表头金额字段
 * 2.刷新表格页脚数据
 */
function editDataAgainCountAmount() {
    // 计算表头金额
    countPageHeadAmount();

    // 计算表体分摊金额
    // calculationShare(1);

    // 刷新表体统计行金额
    refreshTbDetailFooter();
}
// 报表所有列
el.tableColumns = [
    {
        field: 'itemNo',
        title: '行号',
        width: 70,
        sortable: true
    },
    {
        field: 'zlsdh',
        title: 'SC订单号',
        width: 140,
        sortable: true
    },
    // 开票申请相关
    {
        field: 'statementNum',
        title: '对账数量',
        width: 70,
        sortable: true,
        formatter: function (value) {
            if(Number(value) < 0){
                return '<span style="color: red;">' + value + '</span>';
            }
            return value;
        }
    },
    {
        field: 'notTaxPrice',
        title: '到票未税单价',
        width: 90,
        sortable: true
    },
    {
        field: 'taxPrice',
        title: '到票含税单价',
        width: 90,
        sortable: true,
        styler: function (value, row) {
            if(Number(row.shareFlag === 1)){
                return 'background-color:#E1E1E1;';
            }
            return '';
        },
        editor: {
            type: 'numberbox',
            options: {
                precision: 6,
                onChange: function (nv, ov) {
                    if(ov){
                        updateRowData(nv, 'taxPrice');
                    }
                }
            }
        }
    },
    {
        field: 'iaDiffPrice',
        title: '到票含税单价差异',
        width: 70,
        sortable: true
    },
    {
        field: 'taxCodeDesc',
        title: '到票税率',
        width: 160,
        sortable: true,
        styler: function (value, row) {
            if(Number(row.shareFlag === 1)){
                return 'background-color:#E1E1E1;';
            }
            return '';
        },
        editor: {
            type: 'combobox',
            options: {
                valueField: 'itemName',
                textField: 'itemRemark',
                data: el.taxDict,
                panelHeight: 200,
                onChange: function (nv, ov) {
                    if(ov && nv !== ov){
                        var taxSelect = $('#taxSelect').val();
                        console.log(taxSelect)
                        if (Number(taxSelect) === 0){
                            updateRowData(nv, 'taxCodeDesc');
                        }else {
                            updateRowData(nv, 'taxCodeDesc1');
                        }

                    }
                }
            }
        }
    },
    {
        field: 'notTaxAmount',
        title: '到票未税金额',
        width: 95,
        sortable: true,
        styler: function (value, row) {
            if(Number(row.shareFlag === 1)){
                return 'background-color:#E1E1E1;';
            }
            return '';
        },
        editor: {
            type: 'numberbox',
            options: {
                precision: 2,
                onChange: function (nv, ov) {
                    if(ov){
                        updateRowData(nv, 'notTaxAmount');
                    }
                }
            }
        }
    },
    {
        field: 'taxAmount',
        title: '到票含税金额',
        width: 95,
        sortable: true
    },
    {
        field: 'diffTaxAmount',
        title: '到票税额',
        width: 70,
        sortable: true,
        styler: function (value, row) {
            if(Number(row.shareFlag === 1)){
                return 'background-color:#E1E1E1;';
            }
            return '';
        },
        editor: {
            type: 'numberbox',
            options: {
                precision: 2,
                onChange: function (nv, ov) {
                    if(ov){
                        updateRowData(nv, 'diffTaxAmount');
                    }
                }
            }
        }
    },
    {
        field: 'iaDiffAmount',
        title: '到票含税金额差异',
        width: 70,
        sortable: true
    },
    // {
    //     field: 'shareRntAmount',
    //     title: '分摊未税返利金额',
    //     width: 70,
    //     sortable: true,
    //     styler: function (value, row) {
    //         if(Number(row.shareFlag === 1) && Number(rntAmount) !== 0){
    //             return 'background-color:#E1E1E1;';
    //         }
    //         return '';
    //     },
    //     editor: {
    //         type: 'numberbox',
    //         options: {
    //             precision: 2,
    //             onChange: function (nv, ov) {
    //                 if(ov){
    //                     updateRowData(nv, 'shareRntAmount');
    //                 }
    //             }
    //         }
    //     }
    // },
    // {
    //     field: 'sraTaxAmount',
    //     title: '分摊返利税金',
    //     width: 70,
    //     sortable: true,
    //     styler: function (value, row) {
    //         if(Number(row.shareFlag === 1) && Number(rntAmount) !== 0){
    //             return 'background-color:#E1E1E1;';
    //         }
    //         return '';
    //     },
    //     editor: {
    //         type: 'numberbox',
    //         options: {
    //             precision: 2,
    //             onChange: function (nv, ov) {
    //                 if(ov){
    //                     updateRowData(nv, 'sraTaxAmount');
    //                 }
    //             }
    //         }
    //     }
    // },
    // {
    //     field: 'shareRebateAmount',
    //     title: '分摊含税返利金额',
    //     width: 70,
    //     sortable: true
    // },
    // {
    //     field: 'shareDntAmount',
    //     title: '分摊未税扣款金额',
    //     width: 70,
    //     sortable: true,
    //     styler: function (value, row) {
    //         if(Number(row.shareFlag === 1) && Number(dntAmount) !== 0){
    //             return 'background-color:#E1E1E1;';
    //         }
    //         return '';
    //     },
    //     editor: {
    //         type: 'numberbox',
    //         options: {
    //             precision: 2,
    //             onChange: function (nv, ov) {
    //                 if(ov){
    //                     updateRowData(nv, 'shareDntAmount');
    //                 }
    //             }
    //         }
    //     }
    // },
    // {
    //     field: 'sdaTaxAmount',
    //     title: '分摊扣款税金',
    //     width: 70,
    //     sortable: true,
    //     styler: function (value, row) {
    //         if(Number(row.shareFlag === 1) && Number(dntAmount) !== 0){
    //             return 'background-color:#E1E1E1;';
    //         }
    //         return '';
    //     },
    //     editor: {
    //         type: 'numberbox',
    //         options: {
    //             precision: 2,
    //             onChange: function (nv, ov) {
    //                 if(ov){
    //                     updateRowData(nv, 'sdaTaxAmount');
    //                 }
    //             }
    //         }
    //     }
    // },
    // {
    //     field: 'shareDeductionAmount',
    //     title: '分摊含税扣款金额',
    //     width: 70,
    //     sortable: true
    // },
    // 分摊后未税金额|分摊后税金|分摊后含税金额
    // {
    //     field: 'shareAfterNta',
    //     title: '分摊后未税金额',
    //     width: 70,
    //     sortable: true
    // },
    // {
    //     field: 'shareAfterTa',
    //     title: '分摊后税金',
    //     width: 70,
    //     sortable: true
    // },
    // {
    //     field: 'shareAfterIta',
    //     title: '分摊后含税金额',
    //     width: 70,
    //     sortable: true
    // },
    // 对账相关
    {
        field: 'asNotTaxPrice',
        title: '对账未税单价',
        width: 65,
        sortable: true
    },
    {
        field: 'asNotTaxAmount',
        title: '对账未税金额',
        width: 95,
        sortable: true,
        formatter: function (value) {
            return formatNumber(value, 2, 1);
        }
    },
    {
        field: 'asTaxCodeDesc',
        title: '对账税率',
        width: 160,
        sortable: true
    },
    {
        field: 'asTaxPrice',
        title: '对账含税单价',
        width: 65,
        sortable: true
    },
    {
        field: 'asTaxAmount',
        title: '对账含税金额',
        width: 95,
        sortable: true,
        formatter: function (value) {
            return formatNumber(value, 2, 1);
        }
    },
    {
        field: 'asDiffTaxAmount',
        title: '对账税额',
        width: 70,
        sortable: true,
        formatter: function (value) {
            return formatNumber(value, 2, 1);
        }
    },
    {
        field: 'asDiffPrice',
        title: '对账差异含税单价',
        width: 80,
        sortable: true,
        formatter: function (value) {
            if(value === undefined){
                return '';
            }
            return formatNumber(value, 2, 1);
        }
    },
    {
        field: 'asDiffAmount',
        title: '对账差异含税金额',
        width: 80,
        sortable: true,
        formatter: function (value) {
            return formatNumber(value, 2, 1);
        }
    },
    // 凭证和订单相关
    {
        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: 'materialCode',
        title: '物料编码',
        width: 90,
        sortable: true
    },
    {
        field: 'materialName',
        title: '物料名称',
        width: 320,
        sortable: true
    },
    {
        field: 'specs',
        title: '物料规格',
        width: 320,
        sortable: true
    },
    {
        field: 'materialUnit',
        title: '单位',
        width: 65,
        sortable: true
    },
    {
        field: 'poCode',
        title: 'SAP订单号',
        width: 100,
        sortable: true
    },
    {
        field: 'poItemNo',
        title: '订单行号',
        width: 70,
        sortable: true
    },
    {
        field: 'poTaxCodeDesc',
        title: '订单税率',
        width: 160,
        sortable: true
    },
    {
        field: 'poNotTaxPrice',
        title: '订单未税单价',
        width: 65,
        sortable: true
    },
    {
        field: 'poTaxPrice',
        title: '订单含税单价',
        width: 65,
        sortable: true
    },
    {
        field: 'asNtAmount',
        title: '订单未税金额',
        width: 90,
        sortable: true
    },
    {
        field: 'asItAmount',
        title: '订单含税金额',
        width: 90,
        sortable: true
    },
    {
        field: 'asDtAmount',
        title: '订单税额',
        width: 90,
        sortable: true
    },
    {
        field: 'pgCodeName',
        title: '执行采购组',
        width: 110,
        sortable: true
    },
    // {
    //     field: 'seekPgCodeName',
    //     title: '询源采购组',
    //     width: 110,
    //     sortable: true
    // },
    {
        field: 'paymentTermCodeName',
        title: '付款条件',
        width: 200,
        sortable: true
    },
    // {
    //     field: 'paymentWayCodeDesc',
    //     title: '付款方式',
    //     width: 200,
    //     sortable: true
    // },
    {
        field: 'asNo',
        title: '对账单号',
        width: 120,
        sortable: true
    },
    {
        field: 'asdItemNo',
        title: '对账单行号',
        width: 80,
        sortable: true
    },
    {
        field: 'contractNo',
        title: '合同号',
        width: 120
    }
];

// /**
//  * 获取当前用户表格列布局
//  */
// function findUserTableColumn() {
//     var dntAmount = $(el.dntAmount).val(), rntAmount = $(el.rntAmount).val();
//
//
//     $.ajax({
//         type: 'POST',
//         url: g.ctx + 'fin/table/column/rest/user/setting?pageTable=3&isAuthority=1',
//         async: false,
//         success: function (data) {
//             for(var i = 0; i < data.length; i++){
//                 el.userTableColumn.push(data[i].columnField);
//             }
//         }
//     });
// }
/**
 * 检查数组元素是否都相同
 *
 * @param array 待检查数组
 * @returns {boolean} 结果
 */
function checkIsAllEqual(array) {
    if (array.length > 0) {
        return !array.some(function (value, index) {
            return value !== array[0];
        });
    } else {
        return true;
    }
}

/**
 * 动态表格列
 */
function dynamicColumns(orderType) {
    var result = [];
    for(var i = 0; i < el.userTableColumn.length; i++){
        var columnField = el.userTableColumn[i];

        for(var j = 0; j < el.tableColumns.length; j++){
            var column =  el.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;
}


function getNa() {
    var detail = $(el.tbDetails).datagrid('getRows'), snt = BigNumber(0);
    for(var i = 0; i < detail.length; i++){
        snt = snt.plus(detail[i].shareRntAmount);
    }
    console.log(snt.toNumber());
}
