
function chooseGoods(id) {
    var chooseData = $('#chooseGoodsList').jqGrid('getRowData', id);
    var trStr = `<tr class="choosedGoodsTbody">
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;"></td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.supplier + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.goodsName + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.goodsFactory + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.goodsType + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.goodsUnit + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + (commaDelimiter(chooseData.goodsNum)) + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + (chooseData.salesPrice ? commaDelimiter(chooseData.salesPrice) : '') + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + (chooseData.salesPriceTotal ? commaDelimiter(chooseData.salesPriceTotal) : '') + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + (chooseData.purchasePrice ? commaDelimiter(chooseData.purchasePrice) : '') + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + (chooseData.purchasePriceTotal ? commaDelimiter(chooseData.purchasePriceTotal) : '') + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + (chooseData.assignedMoney ? commaDelimiter(chooseData.assignedMoney) : '') + `</td>
                        <td  style="display: none">` + (chooseData.unAssignedMoney ? commaDelimiter(chooseData.unAssignedMoney) : '') + `</td>
                        <td style="display: none">` + chooseData.acceptanceBusinessGoodsId + `</td>
                        <td style="display: none">` + chooseData.id + `</td>
                        <td style="display: none">` + chooseData.id + `</td>
                        <td style="display: none">` + chooseData.mortgageInformationId + `</td>
                        <td style="display: none">` + chooseData.supplierId + `</td>
                        <td style="display: none">` + chooseData.invoicedQuantity + `</td>
                        <td style="display: none">` + chooseData.mortgage + `</td>
                        <td style="display: none">` + chooseData.purchContractNumber + `</td>
                        <td width="10%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;border-right: 1px solid #E8F0F3;"><span class="relaseGoods" style="color: #5AC4FC;cursor: pointer">释放</span></td>
                    </tr>`
    $(".choosedGoodsList").append(trStr);
    $("#myModal-chooseGoods").resize();
    sortChooseGoodsInfo();
}

//paixu
function sortChooseGoodsInfo() {
    $(".choosedGoodsTbody").each(function (i, ele) {
        $(ele).find('td:first').text(i + 1);
    });
}

function handlerNullChangeGang(value) {
    if(value == null || value == 'null' || value == undefined || value == '') {
        return '/'
    }else {
        return value
    }
}

function handlerGangChangeEmpty(value) {
    if(value === '/') {
        return ''
    }else {
        return value
    }
}

// 复选框禁用
function checkBoxDisabled() {
    $('.goodsListTbody').each(function ( i, ele) {
        if($(ele).attr('id')){
            setTimeout(() => {
                var nameVal = `jqg_chooseGoodsList_${$(ele).attr('id')}`
                $(`[name=${nameVal}]`).attr('checked', false)
                $(`[name=${nameVal}]`).attr('disabled',true)
            }, 800);
        }
    })
}

function checkBoxDisabled3() {
    $('.goodsListTbody').each(function ( i, ele) {
        if($(ele).attr('id') && !$(ele).attr('sopAccountsReceivableId')){
            setTimeout(() => {
                var nameVal = `jqg_chooseGoodsList3_${$(ele).attr('id')}`
                $(`[name=${nameVal}]`).attr('checked', false)
                $(`[name=${nameVal}]`).attr('disabled',true)
            }, 800);
        }
    })
}

// 资金占用费 - 操作 - 开始
// 排序-资金占用费
function sortSupplier() {
    var totalPrice = 0;
    $(".supplierListTbody").each(function (i, ele) {
        $(ele).find('td:first span').text(i);
        totalPrice += Number($(ele).find('td').eq(1).find('input').val().split(',').join(''))
    });
    if ($(".supplierListTbody").length <= 1) {
        $('.supplierTable .negativeInformationReduce').hide();
    } else {
        $('.supplierTable .negativeInformationReduce').show();
    }
    if (totalPrice !== 'null') {
        $('.totalZijin').text(commaDelimiter(Math.round(totalPrice * 100) / 100))
        $('[name=totalZi]').val(commaDelimiter(Math.round(totalPrice * 100) / 100))
    } else {
        $('.totalZijin').text('0.00')
        $('[name=totalZi]').val('0.00')
    }
};

// 添加资金占用费
$("#addSupplier").click(function () {
    if($('.supplierListTbody').length === 1 &&  $('.supplierListTbody').eq(0).css('display') === 'none') {
        $('.supplierListTbody').eq(0).css({display: 'table-row'})
    }else {
        var supplierTr = $(".supplierListTbody:first").clone();
        supplierTr.find('.negativeInformationReduce').show();
        supplierTr.find('.error').hide();
        supplierTr.find('input').val('');
        supplierTr.find('select').val('');
        supplierTr.show();
        $('.supplierListTable').append(supplierTr);
    }

    sortSupplier();
});
// 删除行
$("#entryForm").on('click', '.supplierTable .deleteZijin', function () {
    if($('.supplierListTbody').length === 1)  {
        $(this).parents('.supplierListTbody').css({display: 'none'})
        $('[name=totalZi]').val('')
    }else {
        $(this).parents('.supplierListTbody').remove();
    }
    $('#getMoneyNumber').click()
    sortSupplier();
});

// 资金占用费 - 操作 - 结束

// 一键获取收款账号
$('#getMoneyNumber').on('click', function () {
    var postdata = new FormData();
    let ids = []
    if($('[name=goodsAssign]').val() == '1') {
        for (var i = 1; i < $(".goodsListTbody").length; i++) {
            if($(".goodsListTbody").eq(i).find('td').eq(1).attr('supplierId')) {
                ids.push($(".goodsListTbody").eq(i).find('td').eq(1).attr('supplierId'))
            }

        }
    }

    if($('[name=possessionCost]').val() == '1') {
        $('.supplierListTbody').each(function (i, ele) {
            if( $(ele).css('display') !== 'none') {
                for (var n = 0; n < $('.supplierListTbody').length; n++) {
                    if($('.supplierListTbody').eq(n).find('td').eq(0).find('select').val()) {
                        ids.push($('.supplierListTbody').eq(n).find('td').eq(0).find('select').val())
                    }
                }
            }
        })

    }


    let supplierIdList = Array.from(new Set(ids))
    if(!supplierIdList.length) {
        $('.collectionNumberListTable').empty()
        return
    }
    supplierIdList.forEach((item, index) => {
        postdata.append(`supplierIdList[${index}]`, item);
    })

    $.ajax({
        url: '/ledger/doFindSupplierBankInfoList',
        type: 'post',
        data: postdata,
        processData: false,
        contentType: false,
        success: function (data) {
            if (data.success) {
                $('.collectionNumberListTable').empty()
                let collectionNumberListTbody = data.data.map(item => {
                    let bankList = item.bankCardInfoList
                    let backStr = bankList.map(item => {
                        return (
                            `
                            <option value=${item.id} accountName=${item.accountName} accountNumber=${item.accountNumber}>${item.bankName}</option>
                            `
                        )
                    })
                    return (
                        `
                        <tr class="collectionNumberListTbody" supplierId=${item.supplierId}>
                            <td style="background-color:#fff;" class="enter" supplierId=${item.supplierId}>${item.supplierName}</td>
                            <td style="background-color:#fff;" class="enter">
                                <select class="form-control validInput bankName">
                                    ${backStr}
                                </select>
                                <span class="error" style="display:none;">请输入所属银行</span>
                            </td>
                            <td style="background-color:#fff;" class="enter">
                                ${bankList[0].accountName}
                            </td>
                            <td style="background-color:#fff;">
                             ${bankList[0].accountNumber}
                            </td>
                        </tr>
                        `
                    )
                })
                $('.collectionNumberListTable').append(collectionNumberListTbody)
            } else {
                changeFlag[1] = true;
                new $.zui.Messager('一键获取收款账号:' + data.msg, {
                    type: 'danger'
                }).show();
            }
        },
        error: function (status) {
            changeFlag[1] = true;
            new $.zui.Messager('一键获取收款账号:', {
                type: 'danger'
            }).show();
        }
    });
})


// 货物分配-是否分配
function goodsAssignStatus() {
    if($('[name=goodsAssign]').val() == '0' || $('[name=goodsAssign]').val() == '') {
        $('.goodsAssignStatus').hide()
        $('[name=goodsAssign]').parent().css({width: '85%'})
        $('.zoom-box').css({display: 'none'})
    }else {
        $('.goodsAssignStatus').show()
        $('[name=goodsAssign]').parent().css({width: '35%'})
        $('.zoom-box').css({display: 'block'})
        $('#entryForm .zoom-hide-box').click()

    }
}


$('[name=goodsAssign]').change(function (params) {
    goodsAssignStatus()
    $('#getMoneyNumber').click()
})

// 资金占用费- 是否分配资金占用费
function possessionCostStatus() {
    if($('[name=possessionCost]').val() == '0' || $('[name=possessionCost]').val() == '') {
        $('.possessionCostStatus').hide()
        $('[name=totalZi]').val('0')
    }else {
        sortSupplier()
        $('.possessionCostStatus').show()
        if($('.supplierListTbody').length > 1) {
            $('.supplierListTbody').eq(0).remove()
        }

    }
}

$('[name=possessionCost]').change(function (params) {
    possessionCostStatus()
    $('#getMoneyNumber').click()
})



$(function () {
    // 贸理通V3.1 - 开始
    goodsAssignStatus()
    $('[name=goodsAssign]').change()
    possessionCostStatus()
    $('[name=possessionCost]').change()
    // 资金占用费 - 排序
    sortSupplier();

    // 贸理通V3.1 - 结束
    $(".amountInput").each(function (i, ele) {
        $(ele).val(commaDelimiter($(this).val()))
    })
    $(".amountText").each(function (i, ele) {
        $(ele).text(commaDelimiter($(this).text()))
    })
    $('#entryForm').on("keyup", ".amountInput", function () {
        $(this).val(commaDelimiter($(this).val()))
    })
    // 隐藏贴现费用

    if( $('[name=ledgerTypeDict]').val() == '现金') {
        $('.tiexianMoney').hide()
    }

    //货款排序
    function sortIGoodsnfo() {
        let num = null
        var totalPrice = 0;
        var totalFinancingOverdueInterest = 0;
        var totalFinancingInterest = 0;
        var totalFinancingManagementFee = 0;
        var totalFinancingPrincipal = 0;
        var totalAccrualAmount = 0;
        var totalPlatformProfit = 0;
        var totalDiscountAmount = 0;
        var totalRefundManagementFee = 0;
        var totalRefundInterest = 0;
        $(".goodsListTbody").each(function (i, ele) {
            $(ele).find('td:first span').text(i);
            totalPrice += Number($(ele).find('td').eq(6).text().split(',').join(''))
            totalFinancingOverdueInterest += Number($(ele).find('td').eq(14).text().split(',').join(''))
            totalFinancingInterest += Number($(ele).find('td').eq(15).text().split(',').join(''))
            totalFinancingManagementFee += Number($(ele).find('td').eq(16).text().split(',').join(''))
            totalFinancingPrincipal += Number($(ele).find('td').eq(17).text().split(',').join(''))
            totalAccrualAmount += Number($(ele).find('td').eq(18).text().split(',').join(''))
            totalPlatformProfit += Number($(ele).find('td').eq(19).text().split(',').join(''))
            totalDiscountAmount += Number($(ele).find('td').eq(20).text().split(',').join(''))
            totalRefundManagementFee += Number($(ele).find('td').eq(21).text().split(',').join(''))
            totalRefundInterest += Number($(ele).find('td').eq(22).text().split(',').join(''))
            if($(ele).css('dispaly') !== 'none') {
                let str = $(ele).find('td').eq(11).find('input').val()
                if(str) {
                const moeny = Number(str.split(',').join(''))
                num += moeny
                }

            }
        });
        if ($(".goodsListTbody").length <= 1) {
            $('.goodsTable .negativeInformationReduce').hide();
        } else {
            $('.goodsTable .negativeInformationReduce').show();
        }
        ;
        if (totalPrice !== 'null') {
            // $('.totalAssignAmount').text(commaDelimiter(Math.round(totalPrice * 100) / 100))
        } else {
            $('.totalAssignAmount').text('0.00')
        }
        if(num){
            $('[name=goodsAmount]').val(commaDelimiter(num.toFixed(2)))
            $('[name=FrontgoodsAssignAmount]').val(commaDelimiter(num.toFixed(2)))
        }

        if(totalFinancingOverdueInterest!== 'null') {
            $('.financingOverdueInterest').show()
            $('.totalFinancingOverdueInterest').text(commaDelimiter((Math.round(totalFinancingOverdueInterest*10000)/10000).toFixed(2)))
            if(totalFinancingOverdueInterest == 0) {
                $('.financingOverdueInterest').hide()
            }else {
                $('.financingOverdueInterest').show()
            }
        }else {
            $('.totalFinancingOverdueInterest').text('0.00')
            $('.financingOverdueInterest').hide()
        }

        if(totalFinancingInterest!== 'null') {
            $('.financingInterest').show()
            $('.totalFinancingInterest').text(commaDelimiter((Math.round(totalFinancingInterest*10000)/10000).toFixed(2)))
            if(totalFinancingInterest == 0) {
                $('.financingInterest').hide()
            }else {
                $('.financingInterest').show()
            }
        }else {
            $('.totalFinancingInterest').text('0.00')
            $('.financingInterest').hide()
        }

        if(totalFinancingManagementFee!== 'null') {
            $('.financingManagementFee').show()
            $('.totalFinancingManagementFee').text(commaDelimiter((Math.round(totalFinancingManagementFee*10000)/10000).toFixed(2)))
            if(totalFinancingManagementFee == 0) {
                $('.financingManagementFee').hide()
            }else {
                $('.financingManagementFee').show()
            }
        }else {
            $('.totalFinancingManagementFee').text('0.00')
            $('.financingManagementFee').hide()
        }

        if(totalFinancingPrincipal!== 'null') {
            $('.financingPrincipal').show()
            $('.totalFinancingPrincipal').text(commaDelimiter((Math.round(totalFinancingPrincipal*10000)/10000).toFixed(2)))
            if(totalFinancingPrincipal == 0) {
                $('.financingPrincipal').hide()
            }else {
                $('.financingPrincipal').show()
            }
        }else {
            $('.totalFinancingPrincipal').text('0.00')
            $('.financingPrincipal').hide()
        }

        if(totalAccrualAmount!== 'null') {
            $('.accrualAmount').show()
            $('.totalAccrualAmount').text(commaDelimiter((Math.round(totalAccrualAmount*10000)/10000).toFixed(2)))
            if(totalAccrualAmount == 0) {
                $('.accrualAmount').hide()
            }else {
                $('.accrualAmount').show()
            }
        }else {
            $('.totalAccrualAmount').text('0.00')
            $('.accrualAmount').hide()
        }

        if(totalPlatformProfit!== 'null') {
            $('.platformProfit').show()
            $('.totalPlatformProfit').text(commaDelimiter((Math.round(totalPlatformProfit*10000)/10000).toFixed(2)))
            if(totalPlatformProfit == 0) {
                $('.platformProfit').hide()
            }else {
                $('.platformProfit').show()
            }
        }else {
            $('.totalPlatformProfit').text('0.00')
            $('.platformProfit').hide()
        }
        
        if(totalDiscountAmount!== 'null') {
            if(totalDiscountAmount == 0) {
                $('.discountAmount').hide()
            }else {
                $('.discountAmount').show()
                $('.totalDiscountAmount').text(commaDelimiter((Math.round(totalDiscountAmount*10000)/10000).toFixed(2)))
            }
        }else {
            $('.totalDiscountAmount').text('0.00')
            $('.discountAmount').hide()
        }

        if(totalRefundManagementFee!== 'null') {
            $('.refundManagementFee').show()
            $('.totalRefundManagementFee').text(commaDelimiter((Math.round(totalRefundManagementFee*10000)/10000).toFixed(2)))
            if(totalRefundManagementFee == 0) {
                $('.refundManagementFee').hide()
            }else {
                $('.refundManagementFee').show()
            }
        }else {
            $('.totalRefundManagementFee').text('0.00')
            $('.refundManagementFee').hide()
        }

        if(totalRefundInterest!== 'null') {
            $('.refundInterest').show()
            $('.totalRefundInterest').text(commaDelimiter((Math.round(totalRefundInterest*10000)/10000).toFixed(2)))
            if(totalRefundInterest == 0) {
                $('.refundInterest').hide()
            }else {
                $('.refundInterest').show()
            }
        }else {
            $('.totalRefundInterest').text('0.00')
            $('.refundInterest').hide()
        }

    };
    sortIGoodsnfo();
    //货款分配-删除
    $(".goodsListTable").on('click', '.negativeInformationReduce', function () {
        $(this).parents('.goodsListTbody').remove();

        $('#getMoneyNumber').click()
        sortIGoodsnfo()
    })

    /* $(".cancelBtn").on('click', function (params) {
        $("#myModal-chooseGoods").modal("hide");
        $(".choosedGoodsList").empty();
        if($('.goodsListTbody').length <= 1) {
            goodsChooseType = ''
        }
    })

    $(".cancelBtn3").on('click', function (params) {
        $("#myModal-chooseGoods3").modal("hide");
        $(".choosedGoodsList3").empty();
        if($('.goodsListTbody').length <= 1) {
            goodsChooseType = ''
        }
    }) */

    //货款分配-分配金额输入
    $(".goodsListTable").on('blur', '.assignAmount', function () {
        if ($(this).val() !== '') {
            $(this).next('.error').removeClass('.shows').hide();
            let _that = this;
            let assignAmount = $(this).val().split(',').join('');
            let goodsId = $(this).parent().prev().attr('acceptanceBusinessGoodsId');
            let mortgage = $(this).parent().prev().attr('mortgage');
            $.ajax({
                url: '/ledger/doCalculateAssign',
                type: 'get',
                data: {
                    'assignAmount': assignAmount,
                    'mortgage': mortgage,
                    'acceptanceBusinessGoodsId': goodsId
                },
                success: function (data) {
                    if (data.success) {
                        $(_that).parent().parent().find('td').eq(10).find('input').val(commaDelimiter(data.data.financeInterest))
                        $(_that).parent().parent().find('td').eq(11).find('input').val(commaDelimiter(data.data.financePrincipal))
                        $(_that).parent().parent().find('td').eq(12).find('input').val(commaDelimiter(data.data.platformProfit))
                        $(_that).parent().parent().find('td').eq(13).find('input').val(commaDelimiter(data.data.discountAmount))

                        $(_that).parent().parent().data('ledgerPlanFactoringAssignList',data.data.ledgerPlanFactoringAssignList)
                        if($(_that).parent().parent().find('td').find('.backGoodsUl').length) {
                            $(_that).parent().parent().find('td').find('.backGoodsUl').remove()
                        }
                         sortIGoodsnfo()
                    } else {
                        $(_that).parent().parent().find('td').eq(10).find('input').val('')
                        $(_that).parent().parent().find('td').eq(11).find('input').val('')
                        $(_that).parent().parent().find('td').eq(12).find('input').val('')
                        $(_that).parent().parent().find('td').eq(13).find('input').val('')

                        $(_that).parent().parent().data('ledgerPlanFactoringAssignList',[])
                        new $.zui.Messager(data.msg, {
                            type: 'danger'
                        }).show();
                    }
                },
                error: function (status) {
                    new $.zui.Messager('计算错误。' , {
                        type: 'danger'
                    }).show();
                }
            })

        } else {
            $(this).next('.error').addClass('shows').show();
        }
       
    });



    //金额输入
    $('.supplierListTable').on('keyup', '.fundPossessionCost', function () {
        sortSupplier();
    })


    //质保金分配 抵扣货款排序
    function sortRetent() {
        $(".retentionBox").each(function (i, ele) {
            $(ele).find('.retentionIndex').text(i);
            $(ele).find('.retentionGoods').find('.retenGoodsListTbody').each(function (index, element) {
                $(element).find('td:first span').text(index);
            })
        });
    };
    sortRetent()

    //质保金添加供应商
    $("#addRetention").click(function () {
        var reSupplierBox = $(".retentionBox:first").clone();
        reSupplierBox.find('.deleteReten').show();
        reSupplierBox.find('.error').hide();
        reSupplierBox.find('input').val('');
        reSupplierBox.find('select').val('');
        reSupplierBox.find('.retenGoodsListTable').remove();
        reSupplierBox.find('.totalAmount').text('');
        reSupplierBox.show();
        $('.retentionRow').append(reSupplierBox);
        sortRetent()
    });
    //质保金删除
    $("#entryForm").on('click', '.deleteReten', function () {
        $(this).parents('.retentionBox').remove();
        sortRetent()
    });
    //抵扣货款-分配金额输入
    $(".retentionRow").on('blur', '.assignAmount', function () {
        if ($(this).val() !== '') {
            let _that = this;
            let assignAmount = $(this).val().split(',').join('');
            let goodsId = $(this).parent().prev().attr('acceptanceBusinessGoodsId');
            let mortgage = $(this).parent().prev().attr('mortgage');
            $.ajax({
                url: '/ledger/doCalculateAssign',
                type: 'get',
                data: {
                    'assignAmount': assignAmount,
                    'mortgage': mortgage,
                    'acceptanceBusinessGoodsId': goodsId
                },
                success: function (data) {
                    if (data.success) {
                        $(_that).parent().parent().find('td').eq(10).find('input').val(commaDelimiter(data.data.financeInterest))
                        $(_that).parent().parent().find('td').eq(11).find('input').val(commaDelimiter(data.data.financePrincipal))
                        $(_that).parent().parent().find('td').eq(12).find('input').val(commaDelimiter(data.data.platformProfit))
                        $(_that).parent().parent().find('td').eq(13).find('input').val(commaDelimiter(data.data.discountAmount))

                        $(_that).parent().parent().data('ledgerPlanFactoringAssignList',data.data.ledgerPlanFactoringAssignList)
                        if($(_that).parent().parent().find('td').find('.backGoodsUl').length) {
                            $(_that).parent().parent().find('td').find('.backGoodsUl').remove()
                        }
                    } else {
                        $(_that).parent().parent().find('td').eq(10).find('input').val('')
                        $(_that).parent().parent().find('td').eq(11).find('input').val('')
                        $(_that).parent().parent().find('td').eq(12).find('input').val('')
                        $(_that).parent().parent().find('td').eq(13).find('input').val('')

                        $(_that).parent().parent().data('ledgerPlanFactoringAssignList',[])
                        new $.zui.Messager(data.msg, {
                            type: 'danger'
                        }).show();
                    }
                },
                error: function (status) {
                    new $.zui.Messager('计算错误。' , {
                        type: 'danger'
                    }).show();
                }
            })
            sortRetent()
        } else {
            $(this).parent().parent().find('td').eq(10).find('input').val('')
            $(this).parent().parent().find('td').eq(11).find('input').val('')
            $(this).parent().parent().find('td').eq(12).find('input').val('')
            $(this).parent().parent().find('td').eq(13).find('input').val('')
        }
    });
    //抵扣货款-供应商选择
    $(".retentionRow").on('change', '.supplierId', function () {
        if ($(this).val() !== '') {
            let _that = this;
            let supplierId = $(this).val();
            $.ajax({
                url: '/ledger/doCalculatePurchRetention',
                type: 'get',
                data: {
                    'businessNumber': $('[name=businessNumber]').val(),
                    'supplierId': supplierId
                },
                success: function (data) {
                    if (data.success) {
                        $(_that).parent().next().find('.surplusPurchRetentionAmount').val(commaDelimiter(data.data))

                    } else {
                        $(_that).parent().next().find('.surplusPurchRetentionAmount').val('')
                        new $.zui.Messager(data.msg, {
                            type: 'danger'
                        }).show();
                    }
                },
                error: function (status) {
                    new $.zui.Messager(':' + status.msg, {
                        type: 'danger'
                    }).show();
                }
            })
            sortRetent()
        } else {
            $(this).parent().next().find('.surplusPurchRetentionAmount').val('')
        }
    });

    //抵扣货款-货物删除
    $("#entryForm").on('click', '.retenDeleteGoods', function () {
        $(this).parents('.retenGoodsListTbody').remove();
        sortRetent()
    });

    //改变标识
    var changeFlag = [false, false, false]

    //切换分配项目
    $(".projectListTab li").click(function () {
        var _that = this;
        //当前显示的页签
        var orgIndex = $(".projectListTab li").index($(".projectListTab .active"))
        //点击的页签
        var indexlist = $(".projectListTab li").index($(this));

        if (orgIndex == indexlist) {
            return false;
        }

        if ($('[name=goodsAssignAmount]').val() == '' && $('[name=discountChargeAmount]').val() == '' && $('.goodsListTbody').length == 1) {
            $('.goodsRow').find('.error').hide();
            changeFlag[0] = false;
        } else {
            changeFlag[0] = true;
        }
        if ($('.supplierListTbody').length == 1) {
            $('.zijin').find('.error').hide();
            changeFlag[1] = false;
        } else {
            changeFlag[1] = true;
        }
        if ($('.retentionBox').length == 1 && $('[name=assignRetentionAmountTotal]').val() == '') {
            $('.retentionRow').find('.error').removeClass("shows").hide();
            changeFlag[2] = false;
        } else {
            changeFlag[2] = true;
        }
        //当前页签没保存过 或者有修改
        if (changeFlag[orgIndex]) {

            if (orgIndex == 0) {
                GoodsValid()
                if ($('.error.shows').length > 0) {
                    $('.error.shows:first').prev().focus();
                    return false;
                }
                ;

                var postdata = new FormData();

                postdata.append('visible', false);
                postdata.append('taskId', $("[name=taskId]").val());

                postdata.append('ledgerAccountManagement.id', $('[name=basicId]').val());
                //货款分配
                postdata.append('fundGoodsAssignTotal.goodsAssignAmount', $("[name=goodsAssignAmount]").val().split(',').join(''));
                postdata.append('fundGoodsAssignTotal.discountChargeAmount', $("[name=discountChargeAmount]").val().split(',').join(''));
                for (var i = 1; i < $(".goodsListTbody").length; i++) {
                    postdata.append('fundGoodsAssignTotal.fundGoodsAssignVoList[' + (i - 1) + '].acceptanceBusinessGoodsId', $(".goodsListTbody").eq(i).find('td').eq(1).attr('acceptanceBusinessGoodsId'));
                    //postdata.append('fundGoodsAssignTotal.fundGoodsAssignVoList['+(i-1)+'].id',$(".goodsListTbody").eq(i).find('td').eq(1).attr('id'));
                    postdata.append('fundGoodsAssignTotal.fundGoodsAssignVoList[' + (i - 1) + '].billGoodsInformationId', $(".goodsListTbody").eq(i).find('td').eq(1).attr('billGoodsInformationId'));
                    if ($(".goodsListTbody").eq(i).find('td').eq(1).attr('mortgageInformationId')) {
                        postdata.append('fundGoodsAssignTotal.fundGoodsAssignVoList[' + (i - 1) + '].mortgageInformationId', $(".goodsListTbody").eq(i).find('td').eq(1).attr('mortgageInformationId'));
                    }
                    postdata.append('fundGoodsAssignTotal.fundGoodsAssignVoList[' + (i - 1) + '].supplierId', $(".goodsListTbody").eq(i).find('td').eq(1).attr('supplierId'));
                    postdata.append('fundGoodsAssignTotal.fundGoodsAssignVoList[' + (i - 1) + '].purchContractNumber', $(".goodsListTbody").eq(i).find('td').eq(1).attr('purchContractNumber'));

                    postdata.append('fundGoodsAssignTotal.fundGoodsAssignVoList[' + (i - 1) + '].assignableAmount', $(".goodsListTbody").eq(i).find('td').eq(1).text().split(',').join(''));
                    postdata.append('fundGoodsAssignTotal.fundGoodsAssignVoList[' + (i - 1) + '].assignAmount', $(".goodsListTbody").eq(i).find('td').eq(2).find('input').val().split(',').join(''));
                    postdata.append('fundGoodsAssignTotal.fundGoodsAssignVoList[' + (i - 1) + '].supplierName', $(".goodsListTbody").eq(i).find('td').eq(3).text());
                    postdata.append('fundGoodsAssignTotal.fundGoodsAssignVoList[' + (i - 1) + '].financingInterest', $(".goodsListTbody").eq(i).find('td').eq(10).find('input').val().split(',').join(''));
                    postdata.append('fundGoodsAssignTotal.fundGoodsAssignVoList[' + (i - 1) + '].financingPrincipal', $(".goodsListTbody").eq(i).find('td').eq(11).find('input').val().split(',').join(''));
                    postdata.append('fundGoodsAssignTotal.fundGoodsAssignVoList[' + (i - 1) + '].platformProfit', $(".goodsListTbody").eq(i).find('td').eq(12).find('input').val().split(',').join(''));
                    postdata.append('fundGoodsAssignTotal.fundGoodsAssignVoList[' + (i - 1) + '].discountAmount', $(".goodsListTbody").eq(i).find('td').eq(13).find('input').val().split(',').join(''));

                    if($(".goodsListTbody").eq(i).find('.backGoodsUl').length) {
                        $(".goodsListTbody").eq(i).find('.backGoodsUl').find('span').each(function (v,element) {
                            postdata.append('fundGoodsAssignTotal.fundGoodsAssignVoList[' + (i - 1) + '].ledgerPlanFactoringAssignList['+v+'].actualAmount',$(element).find('i').eq(0).text())
                            postdata.append('fundGoodsAssignTotal.fundGoodsAssignVoList[' + (i - 1) + '].ledgerPlanFactoringAssignList['+v+'].actualDate',$(element).find('i').eq(1).text())
                            postdata.append('fundGoodsAssignTotal.fundGoodsAssignVoList[' + (i - 1) + '].ledgerPlanFactoringAssignList['+v+'].planAmount',$(element).find('i').eq(2).text())
                            postdata.append('fundGoodsAssignTotal.fundGoodsAssignVoList[' + (i - 1) + '].ledgerPlanFactoringAssignList['+v+'].planFactoringId',$(element).find('i').eq(3).text())
                            postdata.append('fundGoodsAssignTotal.fundGoodsAssignVoList[' + (i - 1) + '].ledgerPlanFactoringAssignList['+v+'].prepayment',$(element).find('i').eq(4).text())
                        })
                    }else {
                        var accountList = $(".goodsListTbody").eq(i).data('ledgerPlanFactoringAssignList');
                        if(accountList) {
                            for(var x=0; x<accountList.length; x++) {
                                postdata.append('fundGoodsAssignTotal.fundGoodsAssignVoList[' + (i - 1) + '].ledgerPlanFactoringAssignList['+x+'].actualAmount',accountList[x].actualAmount)
                                postdata.append('fundGoodsAssignTotal.fundGoodsAssignVoList[' + (i - 1) + '].ledgerPlanFactoringAssignList['+x+'].actualDate',accountList[x].actualDate)
                                postdata.append('fundGoodsAssignTotal.fundGoodsAssignVoList[' + (i - 1) + '].ledgerPlanFactoringAssignList['+x+'].planAmount',accountList[x].planAmount)
                                postdata.append('fundGoodsAssignTotal.fundGoodsAssignVoList[' + (i - 1) + '].ledgerPlanFactoringAssignList['+x+'].planFactoringId',accountList[x].planFactoringId)
                                postdata.append('fundGoodsAssignTotal.fundGoodsAssignVoList[' + (i - 1) + '].ledgerPlanFactoringAssignList['+x+'].prepayment',accountList[x].prepayment)
                            }
                            x=null;
                        }

                    }

                }
                i = null;
                var url = '/ledger/doAdd', tip = '分配';
                $.ajax({
                    url: url,
                    type: 'post',
                    data: postdata,
                    processData: false,
                    contentType: false,
                    success: function (data) {
                        if (data.success) {
                            changeFlag[0] = false;
                            $(".projectListTab .active").removeClass("active");
                            $(_that).addClass("active");
                            //可以直接换页签
                            $('.operateDiv').each(function (i, ele) {
                                if (i == indexlist) {
                                    $(ele).show()
                                } else {
                                    $(ele).hide();
                                }
                            })
                        } else {
                            changeFlag[0] = true;
                            new $.zui.Messager(tip + '失败:' + data.msg, {
                                type: 'danger'
                            }).show();
                            return false;
                        }
                    },
                    error: function (status) {
                        changeFlag[0] = true;
                        new $.zui.Messager(tip + '失败:', {
                            type: 'danger'
                        }).show();
                        return false;
                    }
                });

            } else if (orgIndex == 1) {
                zijinValid()
                if ($('.error.shows').length > 0) {
                    $('.error.shows:first').prev().focus();
                    return false;
                }
                ;

                var postdata = new FormData();

                postdata.append('visible', false);
                postdata.append('taskId', $("[name=taskId]").val());

                postdata.append('ledgerAccountManagement.id', $('[name=basicId]').val());

                //资金占用费
                for (var n = 1; n < $('.supplierListTbody').length; n++) {
                    postdata.append('ledgerFundPossessionCostList[' + (n - 1) + '].supplierId', $('.supplierListTbody').eq(n).find('td').eq(1).find('select').val())
                    postdata.append('ledgerFundPossessionCostList[' + (n - 1) + '].supplierName', $('.supplierListTbody').eq(n).find('td').eq(1).find('select option:selected').text())
                    postdata.append('ledgerFundPossessionCostList[' + (n - 1) + '].purchContractNumber', $('.supplierListTbody').eq(n).find('td').eq(1).find('select option:selected').attr('code'))
                    postdata.append('ledgerFundPossessionCostList[' + (n - 1) + '].fundPossessionCost', $('.supplierListTbody').eq(n).find('td').eq(2).find('input').val().split(',').join(''))
                    postdata.append('ledgerFundPossessionCostList[' + (n - 1) + '].assignReason', $('.supplierListTbody').eq(n).find('td').eq(3).find('input').val())
                    postdata.append('ledgerFundPossessionCostList[' + (n - 1) + '].ledgerAccountBasicInfoId', $('[name=basicId]').val())
                }
                n = null;
                var url = '/ledger/doAdd', tip = '分配';

                $.ajax({
                    url: url,
                    type: 'post',
                    data: postdata,
                    processData: false,
                    contentType: false,
                    success: function (data) {
                        if (data.success) {
                            changeFlag[1] = false;
                            $(".projectListTab .active").removeClass("active");
                            $(_that).addClass("active");
                            //可以直接换页签
                            $('.operateDiv').each(function (i, ele) {
                                if (i == indexlist) {
                                    $(ele).show()
                                } else {
                                    $(ele).hide();
                                }
                            })

                        } else {
                            changeFlag[1] = true;
                            new $.zui.Messager(tip + '失败:' + data.msg, {
                                type: 'danger'
                            }).show();
                        }
                    },
                    error: function (status) {
                        changeFlag[1] = true;
                        new $.zui.Messager(tip + '失败:', {
                            type: 'danger'
                        }).show();
                    }
                });

            } else {

                retenValid()
                if ($('.error.shows').length > 0) {
                    $('.error.shows:first').prev().focus();
                    return false;
                }
                ;

                var postdata = new FormData();

                postdata.append('visible', false);
                postdata.append('taskId', $("[name=taskId]").val());


                postdata.append('ledgerAccountManagement.id', $('[name=basicId]').val());
                //质保金
                postdata.append('fundRetentionMoneyTotal.surplusSalesRetentionAmount', $("[name=surplusSalesRetentionAmount]").val().split(',').join(''));
                postdata.append('fundRetentionMoneyTotal.assignRetentionAmountTotal', $("[name=assignRetentionAmountTotal]").val().split(',').join(''));
                for (var m = 1; m < $(".retentionBox").length; m++) {
                    postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].supplierId', $(".retentionBox").eq(m).find('.retentionBasic').find('tr').eq(1).find('td').eq(0).find('select').val())
                    postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].supplierName', $(".retentionBox").eq(m).find('.retentionBasic').find('tr').eq(1).find('td').eq(0).find('select option:selected').text())
                    postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].purchContractNumber', $(".retentionBox").eq(m).find('.retentionBasic').find('tr').eq(1).find('td').eq(0).find('select option:selected').attr('code'))
                    postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].surplusPurchRetentionAmount', $(".retentionBox").eq(m).find('.retentionBasic').find('tr').eq(1).find('td').eq(1).find('input').val().split(',').join(''))
                    postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].assignRetentionAmount', $(".retentionBox").eq(m).find('.retentionBasic').find('tr').eq(1).find('td').eq(2).find('input').val().split(',').join(''))
                    postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].cashDistribution', $(".retentionBox").eq(m).find('.retentionBasic').find('tr').eq(1).find('td').eq(3).find('input').val().split(',').join(''))
                    postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].offsetMoney', $(".retentionBox").eq(m).find('.retentionBasic').find('tr').eq(1).find('td').eq(4).find('input').val().split(',').join(''))

                    $(".retentionBox").eq(m).find('.retentionGoods').find('.retenGoodsListTbody').each(function (o, ele) {
                        if (o > 0) {
                            postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].acceptanceBusinessGoodsId', $(ele).find('td').eq(1).attr('acceptanceBusinessGoodsId'))
                            //postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o-1) + '].id', $(ele).find('td').eq(1).attr('id'))
                            postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].billGoodsInformationId', $(ele).find('td').eq(1).attr('billGoodsInformationId'))
                            if ($(ele).find('td').eq(1).attr('mortgageInformationId')) {
                                postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].mortgageInformationId', $(ele).find('td').eq(1).attr('mortgageInformationId'))
                            }
                            postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].supplierId', $(ele).find('td').eq(1).attr('supplierId'))
                            postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].purchContractNumber', $(ele).find('td').eq(1).attr('purchContractNumber'))

                            postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].assignableAmount', $(ele).find('td').eq(1).text().split(',').join(''));
                            postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].assignAmount', $(ele).find('td').eq(2).find('input').val().split(',').join(''));
                            postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].supplierName', $(ele).find('td').eq(3).text());
                            postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].financingInterest', $(ele).find('td').eq(10).find('input').val().split(',').join(''));
                            postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].financingPrincipal', $(ele).find('td').eq(11).find('input').val().split(',').join(''));
                            postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].platformProfit', $(ele).find('td').eq(12).find('input').val().split(',').join(''));
                            postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].discountAmount', $(ele).find('td').eq(13).find('input').val().split(',').join(''));

                            if($(ele).find('td.backGoodsUl').length) {
                                $(ele).find('td.backGoodsUl').find('span').each(function (v, element) {
                                    postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].ledgerPlanFactoringAssignList['+v+'].actualAmount',$(element).find('i').eq(0).text())
                                    postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].ledgerPlanFactoringAssignList['+v+'].actualDate',$(element).find('i').eq(1).text())
                                    postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].ledgerPlanFactoringAssignList['+v+'].planAmount',$(element).find('i').eq(2).text())
                                    postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].ledgerPlanFactoringAssignList['+v+'].planFactoringId',$(element).find('i').eq(3).text())
                                    postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].ledgerPlanFactoringAssignList['+v+'].prepayment',$(element).find('i').eq(4).text())
                                })
                            }else {
                                var accountList2 = $(ele).data('ledgerPlanFactoringAssignList');
                                if(accountList2) {
                                    for(var x=0; x<accountList2.length; x++) {
                                        postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].ledgerPlanFactoringAssignList['+x+'].actualAmount',accountList2[x].actualAmount)
                                        postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].ledgerPlanFactoringAssignList['+x+'].actualDate',accountList2[x].actualDate)
                                        postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].ledgerPlanFactoringAssignList['+x+'].planAmount',accountList2[x].planAmount)
                                        postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].ledgerPlanFactoringAssignList['+x+'].planFactoringId',accountList2[x].planFactoringId)
                                        postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].ledgerPlanFactoringAssignList['+x+'].prepayment',accountList2[x].prepayment)
                                    }
                                    x=null;
                                }

                            }

                        }
                    })
                }
                m = null;
                var url = '/ledger/doAdd', tip = '分配';

                $.ajax({
                    url: url,
                    type: 'post',
                    data: postdata,
                    processData: false,
                    contentType: false,
                    success: function (data) {
                        if (data.success) {
                            changeFlag[2] = false;
                            $(".projectListTab .active").removeClass("active");
                            $(_that).addClass("active");
                            //可以直接换页签
                            $('.operateDiv').each(function (i, ele) {
                                if (i == indexlist) {
                                    $(ele).show()
                                } else {
                                    $(ele).hide();
                                }
                            })

                        } else {
                            changeFlag[2] = true;
                            new $.zui.Messager(tip + '失败:' + data.msg, {
                                type: 'danger'
                            }).show();
                        }
                    },
                    error: function (status) {
                        changeFlag[2] = true;
                        new $.zui.Messager(tip + '失败:', {
                            type: 'danger'
                        }).show();
                    }
                });
            }

        } else {
            $(".projectListTab .active").removeClass("active");
            $(this).addClass("active");

            //可以直接换页签
            $('.operateDiv').each(function (i, ele) {
                if (i == indexlist) {
                    $(ele).show()
                } else {
                    $(ele).hide();
                }
            })
        }


    });

    //每个分配项目有变化 就改变标识
    $('.goodsRow').on('change', 'input', function () {
        changeFlag[0] = true;
    })
    $('.zijin').on('change', 'input,select', function () {
        changeFlag[1] = true;
    })
    $('.retentionRow').on('change', 'input,select', function () {
        changeFlag[2] = true;
    })

    //货款必填验证
    function GoodsValid() {
        if ($('[name=goodsAssignAmount]').val() == '') {
            $('[name=goodsAssignAmount]').next('span.error').addClass("shows").show();
        } else {
            $('[name=goodsAssignAmount]').next('span.error').removeClass("shows").hide();
        }
        if ($('[name=discountChargeAmount]').val() == '') {
            $('[name=discountChargeAmount]').next('span.error').addClass("shows").show();
        } else {
            $('[name=discountChargeAmount]').next('span.error').removeClass("shows").hide();
        }

        if ($('.goodsListTable .goodsListTbody').length) {
            $('.goodsListTable .goodsListTbody').each(function (i, ele) {
                if ($(ele).find('td').eq(2).find('input').val() == '') {
                    $(ele).find('td').eq(2).find('input').next('.error').addClass("shows").show();
                } else {
                    $(ele).find('td').eq(2).find('input').next('.error').removeClass("shows").hide();
                }
            })

        }
    }

    //资金占用费验证
    function zijinValid() {
        if ($('.supplierListTable .supplierListTbody').length) {
            $('.supplierListTable .validInput').change()
        }
    }

    //质保金校验
    function retenValid() {
        if ($('[name=assignRetentionAmountTotal]').val() == '') {
            $('[name=assignRetentionAmountTotal]').next('span.error').addClass("shows").show();
        } else {
            $('[name=assignRetentionAmountTotal]').next('span.error').removeClass("shows").hide();
        }
    }

    $('[name=goodsAssignAmount]').keyup(function () {
        if ($(this).val() == '') {
            $(this).next('.error').addClass("shows").show();
        } else {
            $(this).next('.error').removeClass("shows").hide();
        }
        $('[name=totalSale]').val(commaDelimiter($(this).val().split(',').join('')))
    })
    $('[name=discountChargeAmount]').keyup(function () {
        if ($(this).val() == '') {
            $(this).next('.error').addClass("shows").show();
        } else {
            $(this).next('.error').removeClass("shows").hide();
        }
        $('[name=totalTie]').val(commaDelimiter($(this).val().split(',').join('')))
    })
    $('[name=assignRetentionAmountTotal]').keyup(function () {
        if ($(this).val() == '') {
            $(this).next('.error').addClass("shows").show();
        } else {
            $(this).next('.error').removeClass("shows").hide();
        }
        $('[name=totalRe]').val(commaDelimiter($(this).val().split(',').join('')))
    })

    //资金占用bitian输入
    $('.supplierListTable').on('change', '.validInput', function () {
        if ($(this).val() == '') {
            $(this).next('.error').addClass('shows').show();
        } else {
            $(this).next('.error').removeClass('shows').hide();
        }
    })

    // 保存
    function submitFunction(type) {
        var postdata = new FormData();
        // 基础信息
        postdata.append('ledgerAccountBasicInfo.id', $('[name=basicId]').val());
        postdata.append('ledgerAccountBasicInfo.cashFlowManageBasicInfoId', $('[name=cashFlowManageBasicInfoId]').val());
        postdata.append('ledgerAccountBasicInfo.customerName', $('[name=customerName]').val());
        postdata.append('ledgerAccountBasicInfo.enterpriseCustomerInfoId', $('[name=enterpriseCustomerInfoId]').val());
        postdata.append('ledgerAccountBasicInfo.businessName', $('[name=businessName]').val());
        postdata.append('ledgerAccountBasicInfo.businessNumber', $('[name=businessNumber]').val());
        postdata.append('ledgerAccountBasicInfo.ledgerNumber', $('[name=ledgerNumber]').val());
        postdata.append('ledgerAccountBasicInfo.ledgerTypeDict.id', $('[name=ledgerType]').val());
        postdata.append('ledgerAccountBasicInfo.currencyDict.id', $('[name=currency]').val());
        postdata.append('ledgerAccountBasicInfo.ledgerAmount', $('[name=ledgerAmount]').val().split(',').join(''));
        postdata.append('ledgerAccountBasicInfo.ledgerDate', $('[name=ledgerDate]').val());
        postdata.append('ledgerAccountBasicInfo.discountCharge', $('[name=discountCharge]').val().split(',').join(''));
        postdata.append('ledgerAccountBasicInfo.remark', $('[name=remark]').val());
        postdata.append('ledgerAccountBasicInfo.possessionCost', $('[name=possessionCost]').val());
        postdata.append('ledgerAccountBasicInfo.goodsAmount', $('[name=goodsAmount]').val().split(',').join(''));
        postdata.append('ledgerAccountBasicInfo.goodsAssign', $('[name=goodsAssign]').val());

        // 货款分配
        if($('[name=goodsAssign]').val() == '1') {
            if ($('.goodsListTable .goodsListTbody').length) {
            for (var i = 1; i < $(".goodsListTbody").length; i++) {
                if(type == 'temp') {
                    if(!$(".goodsListTbody").eq(i).find('td').eq(12).find('input').val()) {
                        new $.zui.Messager('请输入本次分配金额', {
                            type: 'danger'
                        }).show();
                        return
                    }
                }else {
                    if($(".goodsListTbody").eq(i).find('td').eq(15).attr('ledgerPlanFactoringAssignList') == undefined) {
                        new $.zui.Messager('请点击一键计算后提交', {
                            type: 'danger'
                        }).show();
                        return
                    }
                }
                postdata.append('goodsAssignList[' + (i - 1) + '].id', $(".goodsListTbody").eq(i).find('td').eq(1).attr('id'));
                postdata.append('goodsAssignList[' + (i - 1) + '].billingFactoringBusinessLoanRecordId', $(".goodsListTbody").eq(i).find('td').eq(1).attr('billingFactoringBusinessLoanRecordId') ? $(".goodsListTbody").eq(i).find('td').eq(1).attr('billingFactoringBusinessLoanRecordId') : '');
                postdata.append('goodsAssignList[' + (i - 1) + '].sopAccountsReceivableId', $(".goodsListTbody").eq(i).find('td').eq(1).attr('sopAccountsReceivableId') ? $(".goodsListTbody").eq(i).find('td').eq(1).attr('sopAccountsReceivableId') : '');
                if($(".goodsListTbody").eq(i).find('td').eq(1).attr('sopAccountsReceivableId')) {
                    postdata.append('goodsAssignList[' + (i - 1) + '].receivablesNumber', $(".goodsListTbody").eq(i).find('td').eq(1).text());
                    postdata.append('goodsAssignList[' + (i - 1) + '].settlementNumber', '');
                    postdata.append('goodsAssignList[' + (i - 1) + '].latestCollDate', $(".goodsListTbody").eq(i).find('td').eq(1).attr('latestCollDate'));
                    postdata.append('goodsAssignList[' + (i - 1) + '].lastPlanDate', $(".goodsListTbody").eq(i).find('td').eq(1).attr('lastPlanDate'));
                    postdata.append('goodsAssignList[' + (i - 1) + '].payCollBasicId', $(".goodsListTbody").eq(i).find('td').eq(1).attr('payCollBasicId'));
                }else {
                    postdata.append('goodsAssignList[' + (i - 1) + '].receivablesNumber', '');
                    postdata.append('goodsAssignList[' + (i - 1) + '].settlementNumber', $(".goodsListTbody").eq(i).find('td').eq(1).text());
                }
                postdata.append('goodsAssignList[' + (i - 1) + '].underlyingAssetsNo', handlerGangChangeEmpty($(".goodsListTbody").eq(i).find('td').eq(2).text()));
                postdata.append('goodsAssignList[' + (i - 1) + '].contractNo',handlerGangChangeEmpty($(".goodsListTbody").eq(i).find('td').eq(3).text()) );
                postdata.append('goodsAssignList[' + (i - 1) + '].quotaDisburseBatch', handlerGangChangeEmpty($(".goodsListTbody").eq(i).find('td').eq(4).text()));
                postdata.append('goodsAssignList[' + (i - 1) + '].supplierId', $(".goodsListTbody").eq(i).find('td').eq(1).attr('supplierId'));
                // postdata.append('goodsAssignList[' + (i - 1) + '].purchaseTotalPrice', $(".goodsListTbody").eq(i).find('td').eq(1).attr('purchaseTotalPrice'));
                postdata.append('goodsAssignList[' + (i - 1) + '].supplierName', $(".goodsListTbody").eq(i).find('td').eq(5).text());
                postdata.append('goodsAssignList[' + (i - 1) + '].salesTotalPrice', $(".goodsListTbody").eq(i).find('td').eq(6).text().split(',').join(''));
                postdata.append('goodsAssignList[' + (i - 1) + '].purchaseTotalPrice', $(".goodsListTbody").eq(i).find('td').eq(7).text().split(',').join(''));
                postdata.append('goodsAssignList[' + (i - 1) + '].toAssignedAmount', $(".goodsListTbody").eq(i).find('td').eq(8).text().split(',').join(''));
                postdata.append('goodsAssignList[' + (i - 1) + '].loanDate', $(".goodsListTbody").eq(i).find('td').eq(9).text());
                postdata.append('goodsAssignList[' + (i - 1) + '].loanAmount', handlerGangChangeEmpty($(".goodsListTbody").eq(i).find('td').eq(10).text().split(',').join('')) );
                postdata.append('goodsAssignList[' + (i - 1) + '].returnedAmount', handlerGangChangeEmpty($(".goodsListTbody").eq(i).find('td').eq(11).text().split(',').join('')));
                postdata.append('goodsAssignList[' + (i - 1) + '].currentAssignAmount', $(".goodsListTbody").eq(i).find('td').eq(12).find('input').val().split(',').join(''));
                postdata.append('goodsAssignList[' + (i - 1) + '].accrual', $(".goodsListTbody").eq(i).find('td').eq(13).find('select').val());
                postdata.append('goodsAssignList[' + (i - 1) + '].financingOverdueInterest', $(".goodsListTbody").eq(i).find('td').eq(14).text().split(',').join(''));
                let  planFactoringAssignListStr = $(".goodsListTbody").eq(i).find('td').eq(15).attr('ledgerPlanFactoringAssignList') ? $(".goodsListTbody").eq(i).find('td').eq(15).attr('ledgerPlanFactoringAssignList') :  ''
                postdata.append('goodsAssignList[' + (i - 1) + '].financingInterest', $(".goodsListTbody").eq(i).find('td').eq(15).text().split(',').join(''));
                postdata.append('goodsAssignList[' + (i - 1) + '].financingManagementFee', $(".goodsListTbody").eq(i).find('td').eq(16).text().split(',').join(''));
                // if(planFactoringAssignListStr !== 'null') {
                    postdata.append('goodsAssignList[' + (i - 1) + '].planFactoringAssignListStr', planFactoringAssignListStr);
                // }
                postdata.append('goodsAssignList[' + (i - 1) + '].financingPrincipal', $(".goodsListTbody").eq(i).find('td').eq(17).text().split(',').join(''));
                postdata.append('goodsAssignList[' + (i - 1) + '].accrualAmount', $(".goodsListTbody").eq(i).find('td').eq(18).text().split(',').join(''));
                postdata.append('goodsAssignList[' + (i - 1) + '].platformProfit', $(".goodsListTbody").eq(i).find('td').eq(19).text().split(',').join(''));
                postdata.append('goodsAssignList[' + (i - 1) + '].discountAmount', $(".goodsListTbody").eq(i).find('td').eq(20).text().split(',').join(''));
                postdata.append('goodsAssignList[' + (i - 1) + '].refundManagementFee', $(".goodsListTbody").eq(i).find('td').eq(21).text().split(',').join(''));
                postdata.append('goodsAssignList[' + (i - 1) + '].refundInterest', $(".goodsListTbody").eq(i).find('td').eq(22).text().split(',').join(''));
            }
            i = null;
        }
        }


        //资金占用费
        if ($('[name=possessionCost]').val() == '1' && $('.supplierListTbody').length) {
            for (var n = 0; n < $('.supplierListTbody').length; n++) {
                postdata.append('ledgerFundPossessionCostList[' + (n) + '].supplierId', $('.supplierListTbody').eq(n).find('td').eq(0).find('select').val())
                postdata.append('ledgerFundPossessionCostList[' + (n) + '].supplierName', $('.supplierListTbody').eq(n).find('td').eq(0).find('select option:selected').text())
                postdata.append('ledgerFundPossessionCostList[' + (n) + '].fundPossessionCost', $('.supplierListTbody').eq(n).find('td').eq(1).find('input').val().split(',').join(''))
                postdata.append('ledgerFundPossessionCostList[' + (n) + '].assignReason', $('.supplierListTbody').eq(n).find('td').eq(2).find('input').val())
                postdata.append('ledgerFundPossessionCostList[' + (n) + '].ledgerAccountBasicInfoId', $('[name=basicId]').val())
            }
            n = null;
        }
        if($('.collectionNumberListTbody').length) {
            for (var j = 0; j < $('.collectionNumberListTbody').length; j++) {
                postdata.append('ledgerSupplierBankRefList[' + (j) + '].supplierBankCardInfoId', $('.collectionNumberListTbody').eq(j).find('td').eq(1).find('select').val())
                postdata.append('ledgerSupplierBankRefList[' + (j) + '].ledgerAccountBasicInfoId', $('[name=basicId]').val())
            }
            n = null;
        }

     /*    if ($('.retentionBox').length > 1) {
            //质保金
            postdata.append('fundRetentionMoneyTotal.surplusSalesRetentionAmount', $("[name=surplusSalesRetentionAmount]").val().split(',').join(''));
            postdata.append('fundRetentionMoneyTotal.assignRetentionAmountTotal', $("[name=assignRetentionAmountTotal]").val().split(',').join(''));
            for (var m = 1; m < $(".retentionBox").length; m++) {
                postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].supplierId', $(".retentionBox").eq(m).find('.retentionBasic').find('tr').eq(1).find('td').eq(0).find('select').val())
                postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].supplierName', $(".retentionBox").eq(m).find('.retentionBasic').find('tr').eq(1).find('td').eq(0).find('select option:selected').text())
                postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].purchContractNumber', $(".retentionBox").eq(m).find('.retentionBasic').find('tr').eq(1).find('td').eq(0).find('select option:selected').attr('code'))
                postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].surplusPurchRetentionAmount', $(".retentionBox").eq(m).find('.retentionBasic').find('tr').eq(1).find('td').eq(1).find('input').val().split(',').join(''))
                postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].assignRetentionAmount', $(".retentionBox").eq(m).find('.retentionBasic').find('tr').eq(1).find('td').eq(2).find('input').val().split(',').join(''))
                postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].cashDistribution', $(".retentionBox").eq(m).find('.retentionBasic').find('tr').eq(1).find('td').eq(3).find('input').val().split(',').join(''))
                postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].offsetMoney', $(".retentionBox").eq(m).find('.retentionBasic').find('tr').eq(1).find('td').eq(4).find('input').val().split(',').join(''))

                $(".retentionBox").eq(m).find('.retentionGoods').find('.retenGoodsListTbody').each(function (o, ele) {
                    if (o > 0) {
                        postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].acceptanceBusinessGoodsId', $(ele).find('td').eq(1).attr('acceptanceBusinessGoodsId'))
                        //postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o-1) + '].id', $(ele).find('td').eq(1).attr('id'))
                        postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].billGoodsInformationId', $(ele).find('td').eq(1).attr('billGoodsInformationId'))
                        if ($(ele).find('td').eq(1).attr('mortgageInformationId')) {
                            postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].mortgageInformationId', $(ele).find('td').eq(1).attr('mortgageInformationId'))
                        }
                        postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].supplierId', $(ele).find('td').eq(1).attr('supplierId'))
                        postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].purchContractNumber', $(ele).find('td').eq(1).attr('purchContractNumber'))

                        postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].assignableAmount', $(ele).find('td').eq(1).text().split(',').join(''));
                        postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].assignAmount', $(ele).find('td').eq(2).find('input').val().split(',').join(''));
                        postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].supplierName', $(ele).find('td').eq(3).text());
                        postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].financingInterest', $(ele).find('td').eq(10).find('input').val().split(',').join(''));
                        postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].financingPrincipal', $(ele).find('td').eq(11).find('input').val().split(',').join(''));
                        postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].platformProfit', $(ele).find('td').eq(12).find('input').val().split(',').join(''));
                        postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].discountAmount', $(ele).find('td').eq(13).find('input').val().split(',').join(''));

                        if($(ele).find('td.backGoodsUl').length) {
                            $(ele).find('td.backGoodsUl').find('span').each(function (v, element) {
                                postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].ledgerPlanFactoringAssignList['+v+'].actualAmount',$(element).find('i').eq(0).text())
                                postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].ledgerPlanFactoringAssignList['+v+'].actualDate',$(element).find('i').eq(1).text())
                                postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].ledgerPlanFactoringAssignList['+v+'].planAmount',$(element).find('i').eq(2).text())
                                postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].ledgerPlanFactoringAssignList['+v+'].planFactoringId',$(element).find('i').eq(3).text())
                                postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].ledgerPlanFactoringAssignList['+v+'].prepayment',$(element).find('i').eq(4).text())
                            })
                        }else {
                            var accountList2 = $(ele).data('ledgerPlanFactoringAssignList');
                            if(accountList2) {
                                for(var x=0; x<accountList2.length; x++) {
                                    postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].ledgerPlanFactoringAssignList['+x+'].actualAmount',accountList2[x].actualAmount)
                                    postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].ledgerPlanFactoringAssignList['+x+'].actualDate',accountList2[x].actualDate)
                                    postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].ledgerPlanFactoringAssignList['+x+'].planAmount',accountList2[x].planAmount)
                                    postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].ledgerPlanFactoringAssignList['+x+'].planFactoringId',accountList2[x].planFactoringId)
                                    postdata.append('fundRetentionMoneyTotal.fundRetentionMoneyVoList[' + (m - 1) + '].fundGoodsAssignVoList[' + (o - 1) + '].ledgerPlanFactoringAssignList['+x+'].prepayment',accountList2[x].prepayment)
                                }
                                x=null;
                            }

                        }


                    }
                })
            }
            m = null;
        } */

        // var url = '/ledger/doAdd', tip = '分配';
        if(type == 'temp'){
            tipword = '暂存';
            postdata.append('submit',false);
        }else{
            tipword = '添加';
            postdata.append('submit',true);
        }
        $.ajax({
            url: '/ledger/doAdd',
            type: 'post',
            data: postdata,
            processData: false,
            contentType: false,
            success: function (data) {
                if (data.success) {
                    new $.zui.Messager(tipword + '成功', {
                        type: 'success'
                    }).show();
                    $.get('/ledger/list', function (data) {
                        $(".yk_rightcontent").empty().append(data);
                    });
                } else {
                    new $.zui.Messager(tipword + '失败:' + data.msg, {
                        type: 'danger'
                    }).show();
                }
            },
            error: function (status) {
                new $.zui.Messager(tipword + '时发生错误:' + status, {
                    type: 'danger'
                }).show();
            }
        });
        return false;
    };

    var formRules = {
        remark: {
            required:true
        },

    };

    var formMessages = {
        remark: {
            required: '请输入说明'
        }
    };

    //表单验证
    function addNewCustomer(e) {
        $("#entryForm").validate({
            promptPosition: "bottomLeft",
            submitHandler: function (form) {
                // if ($(".goodsListTable .goodsListTbody").length) {
                //     $('.goodsListTable .validInput').keyup();
                // } else {
                //     new $.zui.Messager('请添加货物信息。', {
                //         type: 'danger'
                //     }).show();
                //     return false;
                // }

                if ($('.error.shows').length > 0) {
                    $('.error.shows:first').prev().focus();
                    return;
                }

                // 货款金额要小于入账金额
                if( Number($('[name=goodsAmount]').val().split(',').join('')) > Number($('[name=ledgerAmount]').val().split(',').join(''))) {
                    new $.zui.Messager('货款金额要小于入账金额', {
                        type: 'danger'
                    }).show();
                    return
                }

                if(!$('.collectionNumberListTbody').length) {
                    new $.zui.Messager('关联收款账号数据为空', {
                        type: 'danger'
                    }).show();
                    return
                }
                submitFunction(e);
            },
            rules: formRules,
            messages: formMessages
        });
    };

    //货物必填验证
    $(".goodsListTable").on("keyup", ".validInput", function (e) {
        if ($(this).parent().parent().css('display') !== 'none') {
            if ($(this).val() == '') {
                $(this).next().addClass('shows').show();
            } else {
                $(this).next().removeClass('shows').hide();
            }
        }

    })


    //提交按钮
    $(".yk_addNewMsg .submitBusiness").click(addNewCustomer);
    // 暂存-按钮
    $(".yk_addNewMsg .submitTemSave").click(function(){
        submitFunction('temp')
        return false
    })

    //关闭按钮
    $(".yk_addNewMsg .btn-cancel, .newBackBtn").click(function () {
        $.get('/ledger/list', function (data) {
            $(".yk_rightcontent").empty().append(data);
        });
        return false;
    });

    //释放
    $("#myModal-chooseGoods").on('click', '.chooseGoodsTable .relaseGoods', function () {
        $(this).parents('.choosedGoodsTbody').remove();
        sortChooseGoodsInfo();
        //return false;
    });

    function operate(cellValue, options, rowObject) {
        var btnstr = '';
        btnstr += '<p><span>选择</span><i class="icon-check" onclick="chooseGoods(' + rowObject.id + ')"></i></p>';
        return '<div class="operateIcon noHover">' + btnstr + '</div>';
    };

    function supplier(cellValue, options, rowObject) {
        return rowObject.customer.enterpriseName
    }

    function showAmount(cellValue, options, rowObject) {
        if (cellValue !== null && cellValue !== undefined ) {
            return commaDelimiter(cellValue)
        } else {
            return ''
        }
    }
    // var goodsChooseType = ''

    function tablefunction(tableid) {
        var tipword = '', pageid = '', pageNo = 1, postData = {};
        url = '', colNamesArray = [], colModelArray = [];
        switch (tableid) {
            case '#chooseGoodsList':
                tipword = '货物';
                pageid = '#chooseGoodsListPage';
                postData = {
                    'businessNumber': $("[name=businessNumber]").val(),
                    'fastSearch': $("#assignSearchName").val()
                };
                url = '/ledger/doFindUnderlyingGoodsList';
                colNamesArray = ['ID','底层编号', 'SOP底层资产编号', '保理合同编号', '批次号', '供应商名称', '放款日期', '放款金额','待回款金额', '销售总价', '待分配金额', 'RecordId', 'ReceivableId', 'supplierId', 'purchaseTotalPrice', 'returnedManagement', 'returnedInterest', 'latestCollDate', 'lastPlanDate', 'payCollBasicId'];
                colModelArray = [
                    {name: 'id', label: 'ID', hidedlg: true, hidden: true, sortable: false, title: false},
                    {name: 'receivablesNumber', label: '底层编号', sortable: false, title: false},
                    {name: 'underlyingAssetsNo', label: 'SOP底层资产编号',  sortable: false, title: false},
                    {name: 'contractNo', label: '保理合同编号', sortable: false, title: false},
                    {name: 'quotaDisburseBatch', label: '批次号', sortable: false, title: false},
                    {name: 'supplierName', label: '供应商名称',  sortable: false, title: false},
                    {name: 'loanDate', label: '放款日期', sortable: false, title: false},
                    {name: 'loanAmount',label: '放款金额', sortable: false, align: 'left', title: false, formatter: showAmount },
                    {name: 'returnedAmount',label: '待回款金额', sortable: false, align: 'left', title: false, formatter: showAmount },
                    {name: 'salesTotalPrice', label: '销售总价', hidedlg: true, hidden: true, sortable: false, title: false, formatter: showAmount},
                    {name: 'toAssignedAmount', label: '待分配金额', hidedlg: true, hidden: true, sortable: false, title: false, formatter: showAmount},
                    {name: 'billingFactoringBusinessLoanRecordId', label: 'RecordId', hidedlg: true, hidden: true, sortable: false, title: false},
                    {name: 'sopAccountsReceivableId', label: 'ReceivableId', hidedlg: true, hidden: true, sortable: false, title: false},
                    {name: 'supplierId', label: 'supplierId', hidedlg: true, hidden: true, sortable: false, title: false},
                    {name: 'purchaseTotalPrice', label: 'purchaseTotalPrice', hidedlg: true, hidden: true, sortable: false, title: false},
                    {name: 'returnedManagement', label: 'returnedManagement', hidedlg: true, hidden: true, sortable: false, title: false},
                    {name: 'returnedInterest', label: 'returnedInterest', hidedlg: true, hidden: true, sortable: false, title: false},
                    {name: 'latestCollDate', label: 'latestCollDate', hidedlg: true, hidden: true, sortable: false, title: false},
                    {name: 'lastPlanDate', label: 'lastPlanDate', hidedlg: true, hidden: true, sortable: false, title: false},
                    {name: 'payCollBasicId', label: 'payCollBasicId', hidedlg: true, hidden: true, sortable: false, title: false},
                    // {name: 'operate', label: '操作', sortable: false, align: 'left', title: false, formatter: operate},
                ];
                break;
        }
        ;
        sxUtil.jqGrid(tableid, {
            colNames: colNamesArray,
            colModel: colModelArray,
            height: 'auto',
            mtype: 'GET',
            url: url,
            // pager: pageid,
            rowNum: 0,
            rowList: [],
            multiselect: true,
            multiboxonly: true,
            beforeSelectRow: function (rowid, e) {
                var $myGrid = $(this),
                    i = $.jgrid.getCellIndex($(e.target).closest('td')[0]),
                    cm = $myGrid.jqGrid('getGridParam', 'colModel');
                return (cm[i].name == 'cb')
            },
            onSelectAll: function(aRowids,status) {
                checkBoxDisabled()
            },
            rownumbers: false,
            postData: postData,
            // page: pageNo,
            loadError: function () {
                // new $.zui.Messager(tipword+'列表加载失败', {
                //     type: 'warning'
                // }).show();
            }
        }, true);
        $(tableid).trigger('reloadGrid');

    };

    tablefunction('#chooseGoodsList');

    // 重新加载列表
    function assignReloadList(){
        $('#chooseGoodsList').setGridParam({
            mtype:'GET',
            url : '/ledger/doFindUnderlyingGoodsList',
            datatype : 'json',
            postData: {
                'fastSearch':$("#assignSearchName").val()
            },
            page : 1
        });
        $('#chooseGoodsList').trigger('reloadGrid');
    };

    //搜索
    $("#assignSearchBusiness").click(function () {
        assignReloadList();
    })

    var goodsFlag = '';
    // 货款分配-底层货物
    $("#chooseButton").click(function () {
        // if( goodsChooseType && $('.goodsListTbody').eq(1).attr('goodschoosetype') !== 'check') {
        //     new $.zui.Messager('请选择已结算货物', {
        //         type: 'danger'
        //     }).show();
        //     return
        // }
        // goodsChooseType = 'check'
        goodsFlag = 'goods';
        $('#chooseGoodsList').setGridParam({
            mtype: 'GET',
            url: '/ledger/doFindUnderlyingGoodsList',
            datatype: 'json',
            postData: {
                'businessNumber': $("[name=businessNumber]").val()
            },
            page: 1
        });
        $('#chooseGoodsList').trigger('reloadGrid');
        $("#myModal-chooseGoods").modal("show");
        $("#myModal-chooseGoods").on('shown.zui.modal', function () {
            $(".modal-dialog").css({'margin-top': '58px'})
            $(window).resize();
            $("#chooseGoodsList_cb").css({'width': '45', 'padding': '0 0.12rem'})
            $('#chooseGoodsList .jqgfirstrow td:first').css('width', '45')

            $(".choosedGoodsList").empty();
        })
        checkBoxDisabled()
        return false;

    });

    $(".chooseSure").click(function () {
        var ids = $('#chooseGoodsList').jqGrid('getGridParam', 'selarrrow');
        if (ids.length > 0) {
            for (var i = 0; i < ids.length; i++) {
                var chooseData = $('#chooseGoodsList').jqGrid('getRowData', ids[i]);
                var trStr = `<tr class="choosedGoodsTbody">
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;"></td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.receivablesNumber + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.underlyingAssetsNo + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.contractNo + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.quotaDisburseBatch + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.supplierName + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + (chooseData.salesTotalPrice ? commaDelimiter(chooseData.salesTotalPrice) : '') + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + (chooseData.purchaseTotalPrice ? commaDelimiter(chooseData.purchaseTotalPrice) : '') + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + (chooseData.toAssignedAmount ? commaDelimiter(chooseData.toAssignedAmount) : '') + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.loanDate + `</td>
                        <td  style="display: none">` + (chooseData.loanAmount ? commaDelimiter(chooseData.loanAmount) : '/') + `</td>
                        <td  style="display: none">` + (chooseData.returnedAmount ? commaDelimiter(chooseData.returnedAmount) : '/') + `</td>
                        <td style="display: none">` + chooseData.id + `</td>
                        <td style="display: none">` + chooseData.billingFactoringBusinessLoanRecordId + `</td>
                        <td style="display: none">` + chooseData.sopAccountsReceivableId + `</td>
                        <td style="display: none">` + chooseData.supplierId + `</td>
                        <td style="display: none">` + chooseData.purchaseTotalPrice + `</td>
                        <td style="display: none">` + chooseData.returnedManagement + `</td>
                        <td style="display: none">` + chooseData.returnedInterest + `</td>
                        <td style="display: none">` + chooseData.latestCollDate + `</td>
                        <td style="display: none">` + chooseData.lastPlanDate + `</td>
                        <td style="display: none">` + chooseData.payCollBasicId + `</td>

                        <td width="10%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;border-right: 1px solid #E8F0F3;"><span class="relaseGoods" style="color: #5AC4FC;cursor: pointer">释放</span></td>
                    </tr>`
                $(".choosedGoodsList").append(trStr);
            }
        }

        $(".choosedGoodsTbody").each(function (i, ele) {
            if (goodsFlag == 'goods') {
                var supplierTrClone = $(".goodsListTbody:first").clone();
                supplierTrClone.find('.negativeInformationReduce').show();
                supplierTrClone.find('.error').hide();
                supplierTrClone.find('input').val('');

                supplierTrClone.find('td').eq(1).text($(ele).find('td').eq(1).text())
                supplierTrClone.find('td').eq(1).attr('id', $(ele).find('td').eq(12).text())
                supplierTrClone.find('td').eq(1).attr('billingFactoringBusinessLoanRecordId', $(ele).find('td').eq(13).text())
                supplierTrClone.find('td').eq(1).attr('sopAccountsReceivableId', $(ele).find('td').eq(14).text())
                supplierTrClone.find('td').eq(1).attr('supplierId', $(ele).find('td').eq(15).text())
                supplierTrClone.find('td').eq(1).attr('purchaseTotalPrice', $(ele).find('td').eq(16).text())
                supplierTrClone.find('td').eq(1).attr('returnedManagement', $(ele).find('td').eq(17).text())
                supplierTrClone.find('td').eq(1).attr('returnedInterest', $(ele).find('td').eq(18).text())
                supplierTrClone.find('td').eq(1).attr('latestCollDate', $(ele).find('td').eq(19).text())
                supplierTrClone.find('td').eq(1).attr('lastPlanDate', $(ele).find('td').eq(20).text())
                supplierTrClone.find('td').eq(1).attr('payCollBasicId', $(ele).find('td').eq(21).text())
                supplierTrClone.find('td').eq(2).text($(ele).find('td').eq(2).text())
                supplierTrClone.find('td').eq(3).text($(ele).find('td').eq(3).text())
                supplierTrClone.find('td').eq(4).text($(ele).find('td').eq(4).text())
                supplierTrClone.find('td').eq(5).text($(ele).find('td').eq(5).text())
                supplierTrClone.find('td').eq(6).text($(ele).find('td').eq(6).text())
                supplierTrClone.find('td').eq(7).text($(ele).find('td').eq(7).text())
                supplierTrClone.find('td').eq(8).text($(ele).find('td').eq(8).text())
                supplierTrClone.find('td').eq(9).text($(ele).find('td').eq(9).text())
                supplierTrClone.find('td').eq(10).text($(ele).find('td').eq(10).text())
                supplierTrClone.find('td').eq(11).text($(ele).find('td').eq(11).text())
                supplierTrClone.attr('id',$(ele).find('td').eq(12).text())
                supplierTrClone.attr('sopAccountsReceivableId',$(ele).find('td').eq(14).text())
                // 合并一键计算
                // if(i === 0) {
                //     supplierTrClone.find('td').eq(13).attr('rowspan', $(".choosedGoodsTbody").length)
                // }else {
                //     supplierTrClone.find('td').eq(13).remove()
                // }
                // supplierTrClone.attr('goodsChooseType', goodsChooseType)
                supplierTrClone.show();

                $('.goodsListTable').append(supplierTrClone);
                sortIGoodsnfo()
            }
        })
        $("#myModal-chooseGoods").modal("hide");
    })

    //抵扣货款-选择货物
    $('.retentionRow').on('click', '.chooseGoods', function () {
        let _that = this;
        goodsFlag = $(_that).parent().parent().parent().parent().parent().find('.retentionIndex').text();
        let supplierId = $(_that).parent().parent().parent().parent().parent().find('.retentionBasic').find('tr').eq(2).find('selcect').val();
        $('#chooseGoodsList').setGridParam({
            mtype: 'GET',
            url: '/ledger/findAllUnAssignedGoods',
            datatype: 'json',
            postData: {
                'businessNumber': $("[name=businessNumber]").val()
            },
            page: 1
        });
        $('#chooseGoodsList').trigger('reloadGrid');
        $("#myModal-chooseGoods").modal("show");
        $("#myModal-chooseGoods").on('shown.zui.modal', function () {
            $(".modal-dialog").css({'margin-top': '58px'})
            $(window).resize();
            $("#chooseGoodsList_cb").css({'width': '45', 'padding': '0 0.12rem'})
            $('#chooseGoodsList .jqgfirstrow td:first').css('width', '45')

            $(".choosedGoodsList").empty();
        })
        return false;
    })

    // 货款分配-结算货物
    function tablefunction3(tableid) {
        var tipword = '', pageid = '', pageNo = 1, postData = {};
        url = '', colNamesArray = [], colModelArray = [];
        switch (tableid) {
            case '#chooseGoodsList3':
                tipword = '货物';
                pageid = '#chooseGoodsListPage3';
                postData = {
                    'businessNumber':  $("[name=businessNumber]").val(),
                    'fastSearch':$("#settleSearchName").val()
                };
                url = ' /ledger/doFindSettlementGoodsList'
                colNamesArray = ['ID', '结算单号', '供应商', '结算日期',  '待分配金额','supplierId', 'purchaseTotalPrice', '销售总价', '放款金额', '待回款金额'];
                colModelArray = [
                    {name: 'id', label: 'ID', hidedlg:true, hidden:true,sortable:false,title:false},
                    {name: 'settlementNumber', label: '结算单号', sortable:false, align:'left', title:false},
                    {name: 'supplierName', label: '供应商', sortable:false, align:'left', title:false},
                    {name: 'loanDate', label: '结算日期',sortable:false, align:'left', title:false},
                    {name: 'toAssignedAmount', label: '待分配金额', sortable:false, align:'left', title:false},
                    {name: 'supplierId', label: 'supplierId', hidedlg: true, hidden: true, sortable: false, title: false},
                    {name: 'purchaseTotalPrice', label: 'purchaseTotalPrice', hidedlg: true, hidden: true, sortable: false, title: false},
                    {name: 'salesTotalPrice', label: '销售总价', hidedlg: true, hidden: true, sortable: false, title: false},
                    {name: 'loanAmount',label: '放款金额', hidedlg: true, hidden: true, sortable: false, align: 'left', title: false, formatter: showAmount },
                    {name: 'returnedAmount',label: '待回款金额', hidedlg: true, hidden: true, sortable: false, align: 'left', title: false, formatter: showAmount },
                    // {name: 'operate', label: '操作', sortable: false, align: 'left', title: false, formatter: operate},
                ];
                break;
        }
        sxUtil.jqGrid(tableid, {
            colNames: colNamesArray,
            colModel: colModelArray,
            height: 'auto',
            mtype: 'GET',
            url: url,
            // pager: pageid,
            rowNum: 0,
            rowList: [],
            multiselect: true,
            multiboxonly: true,
            beforeSelectRow: function (rowid, e) {
                var $myGrid = $(this),
                    i = $.jgrid.getCellIndex($(e.target).closest('td')[0]),
                    cm = $myGrid.jqGrid('getGridParam', 'colModel');
                return (cm[i].name == 'cb')
            },
            onSelectAll: function(aRowids,status) {
                checkBoxDisabled3()
            },
            rownumbers: false,
            postData: postData,
            page: pageNo,
            loadError: function () {
                // new $.zui.Messager(tipword+'列表加载失败', {
                //     type: 'warning'
                // }).show();
            }
        }, true);

        $(tableid).trigger('reloadGrid');
    };

    tablefunction3('#chooseGoodsList3');

    // 重新加载列表
    function settleReloadList(){
        $('#chooseGoodsList3').setGridParam({
            mtype:'GET',
            url : '/ledger/doFindSettlementGoodsList',
            datatype : 'json',
            postData: {
                'fastSearch':$("#settleSearchName").val()
            },
            page : 1
        });
        $('#chooseGoodsList3').trigger('reloadGrid');
    };

    //搜索
    $("#settleSearchBusiness").click(function () {
        settleReloadList();
    })

    // 货款分配-结算货物-点击
    $("#chooseButton3").click(function () {
        // if( goodsChooseType && $('.goodsListTbody').eq(1).attr('goodschoosetype') !== 'settlement') {
        //     new $.zui.Messager('请选择已底层货物', {
        //         type: 'danger'
        //     }).show();
        //     return
        // }
        // goodsChooseType = 'settlement'
        goodsFlag = 'goods';
        $('#chooseGoodsList3').setGridParam({
            mtype: 'GET',
            url: '/ledger/doFindSettlementGoodsList',
            datatype: 'json',
            postData: {
                'businessNumber':  $("[name=businessNumber]").val()
            },
            page: 1
        });
        $('#chooseGoodsList3').trigger('reloadGrid');
        $("#myModal-chooseGoods3").modal("show");
        $("#myModal-chooseGoods3").on('shown.zui.modal', function () {
            $(".modal-dialog").css({'margin-top': '58px'})
            $(window).resize();
            $("#chooseGoodsList3_cb").css({'width': '45', 'padding': '0 0.12rem'})
            $('#chooseGoodsList3 .jqgfirstrow td:first').css('width', '45')

            $(".choosedGoodsList3").empty();
        })
        checkBoxDisabled3()
        return false;
    });

    // 货款分配-结算货物-确定
    $(".chooseSure3").click(function () {
        $('.numberType').find('span').text('结算编号')
        // $('.settmentDate').find('span').text('结算日期')
        var ids = $('#chooseGoodsList3').jqGrid('getGridParam', 'selarrrow');
        if (ids.length > 0) {
            for (var i = 0; i < ids.length; i++) {
                        var chooseData = $('#chooseGoodsList3').jqGrid('getRowData', ids[i]);
                        var trStr = `<tr class="choosedGoodsTbody3">
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;"></td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.settlementNumber + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + '/' + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + '/' + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + '/' + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.supplierName + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.salesTotalPrice + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.purchaseTotalPrice+ `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` +chooseData.toAssignedAmount + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.loanDate + `</td>
                        <td  style="display: none">` + handlerNullChangeGang(chooseData.loanAmount) + `</td>
                        <td  style="display: none">` + handlerNullChangeGang(chooseData.returnedAmount) + `</td>
                        <td style="display: none">` + chooseData.id + `</td>
                        <td style="display: none">` + ''  + `</td>
                        <td style="display: none">` + '' + `</td>
                        <td style="display: none">` + chooseData.supplierId + `</td>
                        <td style="display: none">` + chooseData.purchaseTotalPrice + `</td>
                        <td width="10%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;border-right: 1px solid #E8F0F3;"><span class="relaseGoods" style="color: #5AC4FC;cursor: pointer">释放</span></td>
                    </tr>`
                $(".choosedGoodsList3").append(trStr);
            }
        }

        $(".choosedGoodsTbody3").each(function (i, ele) {
            if (goodsFlag == 'goods') {

                var supplierTrClone = $(".goodsListTbody:first").clone();
                supplierTrClone.find('.negativeInformationReduce').show();
                supplierTrClone.find('.error').hide();
                supplierTrClone.find('input').val('');

                supplierTrClone.find('td').eq(1).text($(ele).find('td').eq(1).text())
                supplierTrClone.find('td').eq(1).attr('id', $(ele).find('td').eq(12).text())
                supplierTrClone.find('td').eq(1).attr('billingFactoringBusinessLoanRecordId', $(ele).find('td').eq(13).text())
                supplierTrClone.find('td').eq(1).attr('sopAccountsReceivableId', $(ele).find('td').eq(14).text())
                supplierTrClone.find('td').eq(1).attr('supplierId', $(ele).find('td').eq(15).text())
                supplierTrClone.find('td').eq(1).attr('purchaseTotalPrice', $(ele).find('td').eq(15).text())
                supplierTrClone.find('td').eq(2).text('/')
                supplierTrClone.find('td').eq(3).text('/')
                supplierTrClone.find('td').eq(4).text('/')
                supplierTrClone.find('td').eq(5).text($(ele).find('td').eq(5).text())
                supplierTrClone.find('td').eq(6).text( $(ele).find('td').eq(6).text() != 'null' ?commaDelimiter($(ele).find('td').eq(6).text()) : '')
                supplierTrClone.find('td').eq(7).text($(ele).find('td').eq(7).text() != 'null' ? commaDelimiter($(ele).find('td').eq(7).text()) : '')
                supplierTrClone.find('td').eq(8).text($(ele).find('td').eq(8).text() != 'null' ? commaDelimiter($(ele).find('td').eq(8).text()) : '')
                supplierTrClone.find('td').eq(9).text($(ele).find('td').eq(9).text())
                supplierTrClone.find('td').eq(10).text($(ele).find('td').eq(10).text() != '/' ? commaDelimiter($(ele).find('td').eq(10).text()) : '/' )
                supplierTrClone.find('td').eq(11).text($(ele).find('td').eq(11).text() != '/' ? commaDelimiter($(ele).find('td').eq(11).text()) : '/' )
                supplierTrClone.find('td').find('.viewPlan').hide()
                supplierTrClone.attr('id',$(ele).find('td').eq(12).text())
                supplierTrClone.attr('sopAccountsReceivableId', '')
                supplierTrClone.find('td').eq(13).find('select').val('false')
                supplierTrClone.find('td').eq(13).find('select').attr('disabled', true)
                // 合并一键计算
                // if(i === 0) {
                //     supplierTrClone.find('td').eq(13).attr('rowspan', $(".choosedGoodsTbody").length)
                // }else {
                //     supplierTrClone.find('td').eq(13).remove()
                // }
                // supplierTrClone.attr('goodsChooseType', goodsChooseType)
                supplierTrClone.show();

                $('.goodsListTable').append(supplierTrClone);
                sortIGoodsnfo()
            }
        })
        $("#myModal-chooseGoods3").modal("hide");
    })

    // 计算货款金额
    $('.goodsListTable').on('blur', '.goodsListTbody .distributionMoney', function () {
        let num = null;
        $('.goodsListTbody').each(function (i, ele) {
            if($(ele).css('dispaly') !== 'none') {
                let str = $(ele).find('td').eq(12).find('input').val()
                if(str){
                    const moeny = Number(str.split(',').join(''))
                    num += moeny
                }
            }
        })
        if(num){
            $('[name=goodsAmount]').val(commaDelimiter(num.toFixed(2)))
            $('[name=FrontgoodsAssignAmount]').val(commaDelimiter(num.toFixed(2)))
        }
        $('#entryForm .keyCalc').click()
    })

    // 计算贴现费用
    $('.supplierTable').on('change', '.supplierListTbody .fundPossessionCost', function () {
        sortSupplier()
    })

    //查看价格
    $('#entryForm').on('click', '.viewPrice', function () {
        var billId = $(this).parent().parent().find('td').eq(1).attr('billGoodsInformationId');
        $.ajax({
            url: '/ledger/doFindPriceDetail',
            type: 'get',
            data: {
                'billGoodsInformationId': billId
            },
            success: function (data) {
                if (data.success) {
                    $('.priceTr').empty();
                    var priceTr = `<tr>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + data.data.supplier + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + data.data.goodsName + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + data.data.goodsFactory + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + data.data.goodsType + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + data.data.goodsUnit + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + (commaDelimiter(data.data.goodsNum)) + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + (data.data.salesPrice ? commaDelimiter(data.data.salesPrice) : '') + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + (data.data.salesPriceTotal ? commaDelimiter(data.data.salesPriceTotal) : '') + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + (data.data.salesGuaranteeMoney ? commaDelimiter(data.data.salesGuaranteeMoney) : '') + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + (data.data.purchasePrice ? commaDelimiter(data.data.purchasePrice) : '') + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + (data.data.purchasePriceTotal ? commaDelimiter(data.data.purchasePriceTotal) : '') + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + (data.data.purchaseGuaranteeMoney ? commaDelimiter(data.data.purchaseGuaranteeMoney) : '') + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + (data.data.assignedMoney ? commaDelimiter(data.data.assignedMoney) : '') + `</td>
                    </tr>`

                    $('.priceTr').append(priceTr)

                } else {
                    $('.priceTr').empty();
                    new $.zui.Messager(data.msg, {
                        type: 'danger'
                    }).show();
                }
            },
            error: function (status) {
                $('.priceTr').empty();
                new $.zui.Messager(':' + status.msg, {
                    type: 'danger'
                }).show();
            }
        })
        $("#myModal-viewPrice").modal("show");
    })

    //查看收支计划
    $('#entryForm').on('click', '.viewPlan', function () {
        var sopAccountsReceivableId = $(this).parent().parent().find('td').eq(1).attr('sopAccountsReceivableId');
        var billingFactoringBusinessLoanRecordId = $(this).parent().parent().find('td').eq(1).attr('billingFactoringBusinessLoanRecordId');
        $('#planList').setGridParam({
            mtype: 'GET',
            url: '/ledger/doFindPayCollPlanFactoringList',
            datatype: 'json',
            postData: {
                'sopAccountsReceivableId': sopAccountsReceivableId,
                'billingFactoringBusinessLoanRecordId': billingFactoringBusinessLoanRecordId
            },
            page: 1
        });
        $('#planList').trigger('reloadGrid');
        $("#myModal-planBox").modal("show");
        $("#myModal-planBox").on('shown.zui.modal', function () {
            $(".modal-dialog").css({'margin-top': '58px'})
            $(window).resize();

        })
        return false;
    })

    function showAmountStard(cellValue, options, rowObject) {
        return '<span class="tableRowMultipleSpan" style="text-align:left;">' + handleListAmountFn(rowObject.amount, (rowObject.currencyType ? rowObject.currencyType.code : '')) + '</span>';
    };

    // 收放款执行(保理融资款)--显示约定日期
    function showPlanDate(cellValue, options, rowObject) {
        var planDateStr = '';
        if (rowObject.paymentCollectionType == '放款') {
            if (rowObject.paymentPlanDateList && rowObject.paymentPlanDateList.length > 0) {
                for (var i = 0; i < rowObject.paymentPlanDateList.length; i++) {
                    planDateStr += '<span class="tableRowMultipleSpan">' + getStandardDate(new Date(rowObject.paymentPlanDateList[i])) + '</span>'
                }
                ;
                i = null;
            }
        } else if (rowObject.paymentCollectionType == '收款') {
            planDateStr += '<span class="tableRowMultipleSpan">' + rowObject.planDate + '</span>'
        }
        ;
        return planDateStr;
    };

    // 收放款执行(保理融资款)--显示实收付日期
    function showSumDateAllocation(cellValue, options, rowObject) {
        var planDateStr = '';
        if( rowObject.paymentCollectionType == '放款' ){
            if (rowObject.loanRecordList && rowObject.loanRecordList.length > 0) {
                for (var i = 0; i < rowObject.loanRecordList.length; i++) {
                    planDateStr += '<span class="tableRowMultipleSpan" style="text-align:left;">' + getStandardDate(new Date(rowObject.loanRecordList[i].thisLoanDate)) + '</span>'
                }
                ;
                i = null;
            } else {
                planDateStr += '<span class="tableRowMultipleSpan" style="text-align:left;">' + '' + '</span>'
            }
        }
        if( rowObject.paymentCollectionType == '收款' ){
            if (rowObject.amountAllocationList && rowObject.amountAllocationList.length > 0) {
                for (var i = 0; i < rowObject.amountAllocationList.length; i++) {
                    planDateStr += '<span class="tableRowMultipleSpan" style="text-align:left;">' + getStandardDate(new Date(rowObject.amountAllocationList[i].actualDate)) + '</span>'
                }
                ;
                i = null;
            } else {
                planDateStr += '<span class="tableRowMultipleSpan" style="text-align:left;">' + '' + '</span>'
            }
        }
        return planDateStr;
    }

    // 收放款执行(保理融资款)--显示实收/付总金额
    function showSumAmountAllocation(cellValue, options, rowObject) {
        var sumAmount = '';
        if (rowObject.paymentCollectionType == '放款') {
            if (rowObject.loanRecordList && rowObject.loanRecordList.length > 0) {
                for (var i = 0; i < rowObject.loanRecordList.length; i++) {
                    sumAmount += '<span class="tableRowMultipleSpan" style="text-align:left;">' + handleListAmountFn(rowObject.loanRecordList[i].thisLoanAmount, (rowObject.currencyType ? rowObject.currencyType.code : '')) + '</span>'
                }
                ;
                i = null;
            } else {
                sumAmount += '<span class="tableRowMultipleSpan" style="text-align:left;">' + '' + '</span>'
            }
        }
        if (rowObject.paymentCollectionType == '收款') {
            if (rowObject.amountAllocationList && rowObject.amountAllocationList.length > 0) {
                for (var i = 0; i < rowObject.amountAllocationList.length; i++) {
                    sumAmount += '<span class="tableRowMultipleSpan" style="text-align:left;">' + handleListAmountFn(rowObject.amountAllocationList[i].actualAmount, (rowObject.currencyType ? rowObject.currencyType.code : '')) + '</span>'
                }
                ;
                i = null;
            } else {
                sumAmount += '<span class="tableRowMultipleSpan" style="text-align:left;">' + '' + '</span>'
            }
        }

        return sumAmount;
        //return '<span class="tableRowMultipleSpan" style="text-align:right;">'+handleListAmountFn(rowObject.sumAmountAllocation,(rowObject.currencyType?rowObject.currencyType.code:''))+'</span>';
    };


    function tablefunction2(tableid) {
        var tipword = '', pageid = '', pageNo = 1, postData = {};
        url = '', colNamesArray = [], colModelArray = [];
        switch (tableid) {
            case '#planList':
                tipword = '收放款计划';
                pageid = '#planListPage';
                pageNo = 1;
                postData = {'sopAccountsReceivableId': '', billingFactoringBusinessLoanRecordId: ''};
                url = '/ledger/doFindPayCollPlanFactoringList';

                colNamesArray = ['ID', '序号', '金额类型', '收放款类型', '收款主体', '约定日期', '<p style="text-align:left;margin:0;">应收/付金额</p>', '<p style="text-align:left;margin:0;">实收/付日期</p>', '<p style="text-align:left;margin:0;">实收/付总金额</p>','本次分配金额', '状态',];
                colModelArray = [
                    {name: 'id', label: 'ID', hidedlg: true, hidden: true, sortable: false, title: false},
                    {name: 'orderNumber', label: '序号', hidedlg: true, width: 60, sortable: false, title: false},
                    {name: 'amountType.name', label: '金额类型', sortable: false, align: 'left', width: 100, title: false},
                    {
                        name: 'paymentCollectionType',
                        label: '收放款类型',
                        sortable: false,
                        align: 'left',
                        width: 100,
                        title: false
                    },
                    {name: 'receivingSubject', label: '收款主体', sortable: false, align: 'left', width: 100, title: false},
                    {
                        name: 'planDate',
                        label: '约定日期',
                        sortable: false,
                        align: 'left',
                        width: 120,
                        title: false,

                    },
                    {
                        name: 'amount',
                        label: '应收/付金额',
                        sortable: false,
                        align: 'left',
                        width: 120,
                        title: false,
                        formatter: showAmountStard
                    },
                    {
                        name: 'sumDateAllocation',
                        label: '实收/付日期',
                        sortable: false,
                        align: 'left',
                        width: 120,
                        title: false,
                        classes: 'tableRowMultiple',
                        formatter: showSumDateAllocation
                    },
                    {
                        name: 'sumAmountAllocation',
                        label: '实收/付金额',
                        sortable: false,
                        align: 'left',
                        width: 120,
                        title: false,
                        classes: 'tableRowMultiple',
                        formatter: showSumAmountAllocation
                    },
                    {
                        name: 'sumDateAllocation',
                        label: '本次分配金额',
                        sortable: false,
                        align: 'left',
                        width: 120,
                        title: false,
                        formatter: showAmountStard
                    },
                    {name: 'status.name', label: '状态', sortable: false, align: 'left', width: 100, title: false},
                ];
                break;
        }
        ;
        sxUtil.jqGrid(tableid, {
            colNames: colNamesArray,
            colModel: colModelArray,
            height: 'auto',
            mtype: 'GET',
            url: url,
            pager: pageid,
            multiselect: false,
            rownumbers: false,
            postData: postData,
            page: pageNo,
            loadError: function () {
                // new $.zui.Messager(tipword + '列表加载失败', {
                //     type: 'warning'
                // }).show();
            }
        }, true);
        $(tableid).trigger('reloadGrid');
    };
    tablefunction2('#planList')



    // 一键计算
    $('#entryForm').on('click', '.keyCalc', function () {
        var postdata = new FormData();
        for(var i=1;i<$(".goodsListTbody").length;i++) {
            if(! $(".goodsListTbody").eq(i).find('td').eq(12).find('input').val()) {
                new $.zui.Messager('请输入本次分配金额', {
                    type: 'danger'
                }).show();
                return
            }
            if(! $(".goodsListTbody").eq(i).find('td').eq(13).find('select option:selected').val()) {
                new $.zui.Messager('请选择是否计提', {
                    type: 'danger'
                }).show();
                return
            }
            postdata.append(`goodsAssignList[${i-1}].id`, $(".goodsListTbody").eq(i).find('td').eq(1).attr('id'));
            postdata.append(`goodsAssignList[${i-1}].billingFactoringBusinessLoanRecordId`, $(".goodsListTbody").eq(i).find('td').eq(1).attr('billingFactoringBusinessLoanRecordId') ? $(".goodsListTbody").eq(i).find('td').eq(1).attr('billingFactoringBusinessLoanRecordId') : '');
            postdata.append(`goodsAssignList[${i-1}].sopAccountsReceivableId`, $(".goodsListTbody").eq(i).find('td').eq(1).attr('sopAccountsReceivableId') ? $(".goodsListTbody").eq(i).find('td').eq(1).attr('sopAccountsReceivableId') : '');
            // postdata.append(`goodsAssignList[${i-1}].purchaseTotalPrice`, $(".goodsListTbody").eq(i).find('td').eq(1).attr('purchaseTotalPrice'));

            if($(".goodsListTbody").eq(i).find('td').eq(1).attr('sopAccountsReceivableId')) {
                postdata.append(`goodsAssignList[${i-1}].receivablesNumber`, $(".goodsListTbody").eq(i).find('td').eq(1).text());
                postdata.append('goodsAssignList[' + (i - 1) + '].settlementNumber', '');
                // postdata.append(`goodsAssignList[${i-1}].returnedManagement`, $(".goodsListTbody").eq(i).find('td').eq(1).attr('returnedManagement'));
                // postdata.append(`goodsAssignList[${i-1}].returnedInterest`, $(".goodsListTbody").eq(i).find('td').eq(1).attr('returnedInterest'));
                postdata.append(`goodsAssignList[${i-1}].latestCollDate`, $(".goodsListTbody").eq(i).find('td').eq(1).attr('latestCollDate'));
                postdata.append(`goodsAssignList[${i-1}].lastPlanDate`, $(".goodsListTbody").eq(i).find('td').eq(1).attr('lastPlanDate'));
                postdata.append(`goodsAssignList[${i-1}].payCollBasicId`, $(".goodsListTbody").eq(i).find('td').eq(1).attr('payCollBasicId'));
            }else {
                postdata.append('goodsAssignList[' + (i - 1) + '].receivablesNumber', '');
                postdata.append('goodsAssignList[' + (i - 1) + '].settlementNumber', $(".goodsListTbody").eq(i).find('td').eq(1).text());
            }
            postdata.append(`goodsAssignList[${i-1}].underlyingAssetsNo`, handlerGangChangeEmpty($(".goodsListTbody").eq(i).find('td').eq(2).text()) );
            postdata.append(`goodsAssignList[${i-1}].contractNo`,handlerGangChangeEmpty($(".goodsListTbody").eq(i).find('td').eq(3).text()) );
            postdata.append(`goodsAssignList[${i-1}].quotaDisburseBatch`,handlerGangChangeEmpty($(".goodsListTbody").eq(i).find('td').eq(4).text()));
            postdata.append(`goodsAssignList[${i-1}].supplierName`, $(".goodsListTbody").eq(i).find('td').eq(5).text());
            postdata.append(`goodsAssignList[${i-1}].salesTotalPrice`, $(".goodsListTbody").eq(i).find('td').eq(6).text().split(',').join(''));
            postdata.append(`goodsAssignList[${i-1}].purchaseTotalPrice`, $(".goodsListTbody").eq(i).find('td').eq(7).text().split(',').join(''));
            postdata.append(`goodsAssignList[${i-1}].toAssignedAmount`, $(".goodsListTbody").eq(i).find('td').eq(8).text().split(',').join(''));
            postdata.append(`goodsAssignList[${i-1}].loanDate`, $(".goodsListTbody").eq(i).find('td').eq(9).text());
            postdata.append(`goodsAssignList[${i-1}].loanAmount`, handlerGangChangeEmpty($(".goodsListTbody").eq(i).find('td').eq(10).text().split(',').join('')) );
            postdata.append(`goodsAssignList[${i-1}].returnedAmount`, handlerGangChangeEmpty($(".goodsListTbody").eq(i).find('td').eq(11).text().split(',').join('')));
            postdata.append(`goodsAssignList[${i-1}].currentAssignAmount`, $(".goodsListTbody").eq(i).find('td').eq(12).find('input').val().split(',').join(''));
            postdata.append(`goodsAssignList[${i-1}].accrual`, $(".goodsListTbody").eq(i).find('td').eq(13).find('select option:selected').val());
        }
        postdata.append('ledgerAccountBasicInfo.businessNumber', $('[name=businessNumber]').val());
        postdata.append('ledgerAccountBasicInfo.ledgerDate', $('[name=ledgerDate]').val());
        $.ajax({
            url: '/ledger/doCalculateAssign',
            type: 'post',
            data: postdata,
            processData: false,
            contentType: false,
            success: function (data) {
                if (data.success) {
                    data.data.goodsAssignList.forEach((item, index) =>  {
                        $(".goodsListTbody").eq(index + 1).find('td').eq(15).attr('ledgerPlanFactoringAssignList', JSON.stringify(item.ledgerPlanFactoringAssignList))
                        $(".goodsListTbody").eq(index + 1).find('td').eq(14).text( item.financingOverdueInterest ?commaDelimiter(item.financingOverdueInterest) : '0')
                        $(".goodsListTbody").eq(index + 1).find('td').eq(15).text( item.financingInterest ?commaDelimiter(item.financingInterest) : '0')
                        $(".goodsListTbody").eq(index + 1).find('td').eq(16).text( item.financingManagementFee ?commaDelimiter(item.financingManagementFee) : '0')
                        $(".goodsListTbody").eq(index + 1).find('td').eq(17).text(item.financingPrincipal ?commaDelimiter(item.financingPrincipal) : '0')
                        $(".goodsListTbody").eq(index + 1).find('td').eq(18).text(item.accrualAmount ?commaDelimiter(item.accrualAmount) : '0')
                        $(".goodsListTbody").eq(index + 1).find('td').eq(19).text(item.platformProfit ? commaDelimiter(item.platformProfit) : '0')
                        $(".goodsListTbody").eq(index + 1).find('td').eq(20).text(item.discountAmount ?commaDelimiter(item.discountAmount) : '0')
                        $(".goodsListTbody").eq(index + 1).find('td').eq(21).text(item.refundManagementFee ?commaDelimiter(item.refundManagementFee) : '0')
                        $(".goodsListTbody").eq(index + 1).find('td').eq(22).text(item.refundInterest ?commaDelimiter(item.refundInterest) : '0')
                        $('#entryForm .zoom-box').click()
                        sortIGoodsnfo()
                    })
                } else {
                    changeFlag[1] = true;
                    new $.zui.Messager('一键计算失败:' + data.msg, {
                        type: 'danger'
                    }).show();
                }
            },
            error: function (status) {
                changeFlag[1] = true;
                new $.zui.Messager('一键计算失败:', {
                    type: 'danger'
                }).show();
            }
        });
        
    })

    // for(var i=1;i<$(".goodsListTbody").length;i++) {
    //     if($('[name=goodsAssign]').val() == '1' && i>0 && $('.goodsListTbody ').eq(i).find('td').eq(12).find('input').val() !== '') {
    //     $('#entryForm .keyCalc').click()
    //     }
    // }
    
    $('#entryForm').on('click',  '.zoom-box', function () {
        $('.calcHide').css({display: 'table-cell'})
        $('.goodsTableWidth').css({width: '170%'})
        $('.zoom-hide-box').css({display: 'block '})
        $('.zoom-box').css({display: 'none'})
    })
    $('#entryForm').on('click',  '.zoom-hide-box', function () {
        $('.calcHide').css({display: 'none'})
        $('.goodsTableWidth').css({width: '130%'})
        $('.zoom-hide-box').css({display: 'none '})
        if($('[name=goodsAssign]').val() == '1') {
            $('.zoom-box').css({display: 'block'})
        }
    })

    $('#entryForm .zoom-hide-box').click()


    $('.collectionNumberListTable').on('change', '.bankName', function () {
        let accountName = $(this).find("option:selected").attr('accountName')
        let accountNumber = $(this).find("option:selected").attr('accountNumber')
        $(this).parents('.collectionNumberListTbody').find('td').eq(2).text(accountName)
        $(this).parents('.collectionNumberListTbody').find('td').eq(3).text(accountNumber)
    })

})
