function chooseGoods(id) {
    var chooseData = $('#chooseGoodsList').jqGrid('getRowData',id);
    var trStr = `<tr class="choosedGoodsTbody">
                        <td width="5%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;"></td>
                        <td width="9%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+chooseData.acceptanceDate+`</td>
                        <td width="11%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+chooseData.enterpriseName+`</td>
                        <td width="9%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+chooseData.goodsName+`</td>
                        <td width="11%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+chooseData.goodsFactory+`</td>
                        <td width="11%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+chooseData.goodsType+`</td>
                        <td width="10%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+chooseData.goodsUnit+`</td>
                        <td width="10%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+chooseData.goodsNum+`</td>
                        <td width="10%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+(chooseData.salePrice?chooseData.salePrice:'')+`</td>
                        <td style="display: none">`+chooseData.supplierId+`</td>
                        <td style="display: none">`+chooseData.acceptanceBusinessGoodsId+`</td>
                        <td style="display: none">`+chooseData.salesRetentionPercent+`</td>
                        <td style="display: none">`+chooseData.purchRetentionPercent+`</td>
                        <td style="display: none">`+chooseData.purchasePrice+`</td>
                        <td style="display: none">`+chooseData.clear+`</td>
                        <td style="display: none" class="accrualMarginCalcMethod">` + chooseData.accrualMarginCalcMethod + `</td>
                        <td style="display: none" class="differAmount">` + chooseData.differAmount + `</td>
                        <td style="display: none" class="factoringFinanceDeadline">` + chooseData.factoringFinanceDeadline + `</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 chooseGoods2(id) {
    var chooseData = $('#chooseGoodsList2').jqGrid('getRowData',id);
    var trStr = `<tr class="choosedGoodsTbody2">
                        <td width="5%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;"></td>
                        <td width="9%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+chooseData.acceptanceDate+`</td>
                        <td width="11%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+chooseData.enterpriseName+`</td>
                        <td width="9%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+chooseData.goodsName+`</td>
                        <td width="11%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+chooseData.goodsFactory+`</td>
                        <td width="11%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+chooseData.goodsType+`</td>
                        <td width="10%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+chooseData.goodsUnit+`</td>
                        <td width="10%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+chooseData.goodsNum+`</td>
                        <td width="10%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+(chooseData.salePrice?chooseData.salePrice:'')+`</td>
                        <td style="display: none">`+chooseData.supplierId+`</td>
                        <td style="display: none">`+chooseData.acceptanceBusinessGoodsId+`</td>
                        <td style="display: none">`+chooseData.salesRetentionPercent+`</td>
                        <td style="display: none">`+chooseData.purchRetentionPercent+`</td>
                        <td style="display: none">`+chooseData.purchasePrice+`</td>
                        <td style="display: none">`+chooseData.clear+`</td>
                        <td style="display: none" class="monthlyinterestRate">`+chooseData.monthlyinterestRate+`</td>
                        <td style="display: none" class="accrualMarginCalcMethod">` + chooseData.accrualMarginCalcMethod + `</td>
                        <td style="display: none" class="differAmount">` + chooseData.differAmount + `</td>
                        <td style="display: none" class="factoringFinanceDeadline">` + chooseData.factoringFinanceDeadline + `</td>
                        <td width="10%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;border-right: 1px solid #E8F0F3;"><span class="relaseGoods2" style="color: #5AC4FC;cursor: pointer">释放</span></td>
                    </tr>`
    $(".choosedGoodsList2").append(trStr);
    $("#myModal-chooseGoods2").resize();
    sortChooseGoodsInfo2();
}
//paixu
function sortChooseGoodsInfo2() {
    $(".choosedGoodsTbody2").each(function(i,ele){
        $(ele).find('td:first').text(i+1);
    });
}


$(function () {
    //初始化日期
    function setDate(select,startDate,endDate){
        $(select).datetimepicker(
            {
                weekStart: 1,
                autoclose: 1,
                todayHighlight: 0,
                startView: 2,
                minView: 2,
                forceParse: 0,
                showMeridian: 1,
                startDate:startDate,
                endDate:endDate,
                format: "yyyy-mm-dd"
            }
        );
        $(select).datetimepicker('setStartDate',startDate);
        $(select).datetimepicker('setEndDate',endDate);
    };
    setDate('[name=settlementDate],[name=settlementDateBegin],[name=settlementDateEnd],.paybackDate','1970-01-01','2116-12-31');

    $(".amountInput").each(function (i, ele) {
        $(ele).val(commaDelimiter($(this).val()))
    })
    $('#entryForm').on("keyup",".amountInput",function(){
        $(this).val(commaDelimiter($(this).val()))
    })

    // 附件相关dom
    var deleteFileIdArr = []
    var fileWrapperbasic = '<div class="file-wrapper"><div class="file-icon" style="color: #5AC4FC;"><div class="file-icon-image"></div></div>'+
        '<div class="content"><div class="file-name"></div><div class="file-size small text-muted"></div></div>'+
        '<div class="actions" style="width:0.5rem"><a class="btn btn-link btn-delete-file">'+
        '<em>删除</em><i class="operateIconfont operateIcon-shanchu"></i></a></div></div>';

    // 在附件元素的data上存放选择的附件数据,初始为空
    $('.addFileList').each(function(i,ele){
        $(ele).data('filearray',[]);
        $(ele).data('deletefileid',[]);
    });

    // 展示原先有的附件
    function showOriginalFile(source, insert) {
        for (var j = 0; j < $(source).length; j++) {
            var originalFileWrapper = $(fileWrapperbasic).clone();
            originalFileWrapper.find('.file-name').text($(source).eq(j).find('.originalName').val());
            originalFileWrapper.find('.file-name').attr('originalid', $(source).eq(j).find('.originalId').val());
            if (parseFloat($(source).eq(j).find('.originalSize').val()) < 1048576) {
                originalFileWrapper.find('.file-size').text(($(source).eq(j).find('.originalSize').val() / 1024).toFixed(2) + "KB");
            } else {
                originalFileWrapper.find('.file-size').text(($(source).eq(j).find('.originalSize').val() / 1024 / 1024).toFixed(2) + "MB");
            }
            ;
            var originaltype = $(source).eq(j).find('.originalType').val().toUpperCase();
            if (originaltype == '.JPG' || originaltype == '.JPEG' || originaltype == '.PNG' || originaltype == '.BMP') {
                originalFileWrapper.find('.file-icon-image').css('background-image', 'url(' + $(source).eq(j).find('.originalUrl').val() + ')');
            } else {
                originalFileWrapper.find('.file-icon-image').append('<i class="icon icon-file-pdf"></i>');
            }
            ;
            originalFileWrapper.find('.btn-delete-file').addClass('btn-delete-originalfile').removeClass("btn-delete-file");

            originalFileWrapper.find('.btn-yulan-file').attr('href', '/fileStorage/preview?fileId=' + $(source).eq(j).find('.originalId').val());
            originalFileWrapper.find('.btn-xiazai-file').attr('href', '/fileStorage/downloadFile?fileId=' + $(source).eq(j).find('.originalId').val());
            $(insert).find('.fileContent').append(originalFileWrapper)
        }
        ;
        j = null;
        if ($(insert).find('.file-wrapper').length > 0) {
            $(insert).find('.spanHolder').remove();
        }
        ;
    };

    // 展示原附件
    showOriginalFile('.file .fileInfoListOriginal', '.file .addFileList');
    showOriginalFile('.netPrice .fileInfoListOriginal', '.netPrice .addFileList');

    if($(".additional .fileInfoListOriginal")) {
        showOriginalFile('.additional .fileInfoListOriginal', '.additional .addFileList');
    }

    // 触发选择附件
    $('#entryForm').on("click",".fileInfoListBox .choiceFile",function(){
        if ( !window.FileReader ) {
            new $.zui.Messager('您的浏览器版本过低，请升级您的浏览器', {
                type: 'danger'
            }).show();
            return;
        };
        $(this).parent().find('.fileinput').click();
    });

    // 触发选择附件
    $('#entryForm').on("click",".fileInfoListBox .fileContent",function(){
        if ( !window.FileReader ) {
            new $.zui.Messager('您的浏览器版本过低，请升级您的浏览器', {
                type: 'danger'
            }).show();
            return;
        };
        if( $(this).find(".spanHolder").length>0 ){
            $(this).parent().prev().click();
        };
    });

    // 选择附件
    $("#entryForm").on("change",".fileInfoListBox .fileinput",function(e){
        var that = $(this);
        if(that.val() == '') {
            $(".addFileList .error").addClass('shows').show();
        }else {
            $(".addFileList .error").removeClass('shows').hide();
        }
        var choosefiles = e.target.files || e.dataTransfer.files;
        for( var i=0;i<choosefiles.length;i++ ){
            var file = e.target.files[i] || e.dataTransfer.files[i];//用于提交
            $(this).parent().data('filearray').push(file);
            fileWrapper = $(fileWrapperbasic).clone();
            var type = file.type;
            var indexof = type.indexOf("/"),fileType='';
            if( indexof != -1 ){
                var index = parseInt(indexof)+1;
                fileType = type.substring(index,type.length).toUpperCase();
            };
            fileWrapper.find('.file-name').text(file.name);
            if( parseFloat(file.size) < 1048576 ){
                fileWrapper.find('.file-size').text((file.size/1024).toFixed(2)+'KB');
            }else{
                fileWrapper.find('.file-size').text((file.size/1024/1024).toFixed(2)+'MB');
            };
            that.next().find(".fileContent").append(fileWrapper);
            // 有附件时去掉框框里的'上传附件'字样
            if( that.next().find('.file-wrapper').length>0 ){
                that.next().find('.spanHolder').remove();
            };
            detailpreview(fileType,fileWrapper,file);
        };
        i = null;
        function detailpreview(fileType,fileWrapper,file){
            var reader = new FileReader();
            reader.readAsDataURL(file);//转为base64(预览)
            reader.onload = function(e){
                e = e || window.event;
                if( fileType=='JPG' || fileType=='JPEG' || fileType=='PNG' || fileType=='BMP' || fileType=='JPG' ){
                    fileWrapper.find(".file-icon-image").css("backgroundImage",'url('+e.target.result+')')
                }else{
                    fileWrapper.find(".file-icon-image").append('<i class="icon icon-file-pdf"></i>')
                };
            };
        };
    });

    // 删除附件
    $("#entryForm").on("click",".btn-delete-file",function(){
        var deleteindex = $(this).parents('td').find('.btn-delete-file').index($(this));
        $(this).parents('td').data('filearray').splice(deleteindex,1);
        $(this).parents(".uploaderFile").prev().val(null);
        if( $(this).parents('td').find('.file-wrapper').length == 1 ){
            $(this).parents(".file-wrapper").before('<span class="spanHolder">上传附件</span>');
        };
        $(this).parents(".file-wrapper").remove();
        return false;
    });
    // 删除(原有的)附件
    $("#entryForm").on("click",".btn-delete-originalfile",function(){
        deleteFileIdArr.push($(this).parents('.file-wrapper').find('.file-name').attr('originalid'))
        $(this).parents('td').data('deletefileid').push($(this).parents('.file-wrapper').find('.file-name').attr('originalid'));
        $(this).parents(".uploaderFile").prev().val(null);
        if( $(this).parents('td').find('.file-wrapper').length == 1 ){
            $(this).parents(".file-wrapper").before('<span class="spanHolder">上传附件</span>');
        };
        $(this).parents(".file-wrapper").remove();
        return false;
    });


    // 排序-货物
    function sortIGoodsnfo(){
        var totalNum = 0,totalPrice = 0;
        $(".goodsListTbody").each(function(i,ele){
            $(ele).find('td:first span').text(i);
            totalNum += Number($(ele).find('td').eq(7).text())
            totalPrice += Number($(ele).find('td').eq(9).find('input').val().split(',').join(''))
        });
        if( $(".goodsListTbody").length <= 1 ){
            $('.goodsTable .negativeInformationReduce').hide();
        }else{
            $('.goodsTable .negativeInformationReduce').show();
        };
        if(totalNum !== 'null') {
            $('.totalNum').text(Math.round(totalNum*100)/100)
        }else {
            $('.totalNum').text('0.00')
        }
        if(totalPrice!== 'null') {
            $('.totalPrice').text(commaDelimiter(Math.round(totalPrice*100)/100))
        }else {
            $('.totalPrice').text('0.00')
        }

        settlementAmount()
    };
    sortIGoodsnfo();

    // 删除行-货物
    $("#entryForm").on('click','.goodsTable .negativeInformationReduce',function(){
        var _this = this;
        if($(_this).parents('.goodsListTbody').hasClass('goodsListTbodyBack')) {
            bootbox.confirm({
                title : '提示',
                message : '<div style="text-align:left;font-size:0.12rem">是否从该结算单中删除此货物？</div>',
                size : 'small',
                buttons : {
                    cancel : {
                        label : '取消',
                        className:'btn-white btn-info'
                    },
                    confirm : {
                        label : '确定',
                        className:'btn-white btn-info colorbtn'
                    }
                },
                callback:function(result){
                    if (result) {
                        var acceptanceGoodsId = $(_this).parents('.goodsListTbody').find('td').eq(1).attr('acceptanceBusinessGoodsId')
                        $.ajax({
                            url: '/bill/deleteGoods',
                            type: 'get',
                            data: {
                                'acceptanceGoodsId': acceptanceGoodsId,
                            },
                            success: function (data) {
                                if (data.success) {
                                    new $.zui.Messager('删除成功。' , {
                                        type: 'success'
                                    }).show();
                                    $(_this).parents('.goodsListTbody').remove();
                                    sortIGoodsnfo();

                                } else {
                                    new $.zui.Messager('删除失败：' + data.msg , {
                                        type: 'danger'
                                    }).show();
                                }
                            },
                            error: function (status) {
                                new $.zui.Messager('删除失败。' , {
                                    type: 'danger'
                                }).show();
                            }
                        })
                    };
                }
            })
        }else {
            $(_this).parents('.goodsListTbody').remove();
            sortIGoodsnfo();
        }
    });

    // 排序-资金占用费
    function sortIGoodsnfo2(){
        var totalFee= 0;
        $(".goodsListTbody2").each(function(i,ele){
            $(ele).find('td:first span').text(i);
            totalFee += Number($(ele).find('td').eq(8).find('input').val().split(',').join(''))
        });
        if( $(".goodsListTbody2").length <= 1 ){
            $('.goodsTable2 .negativeInformationReduce').hide();
        }else{
            $('.goodsTable2 .negativeInformationReduce').show();
        };
        if(totalFee!== 'null') {
            $('.totalFee').text(commaDelimiter(Math.round(totalFee*100)/100))
        }else {
            $('.totalFee').text('0.00')
        }
        settlementAmount()
    };
    sortIGoodsnfo2();

    // 删除行-资金占用费
    $("#entryForm").on('click','.goodsTable2 .negativeInformationReduce',function(){
        var _this = this;
        if($(_this).parents('.goodsListTbody2').hasClass('goodsListTbodyBack2')) {
            bootbox.confirm({
                title : '提示',
                message : '<div style="text-align:left;font-size:0.12rem">是否从该结算单中删除此货物？</div>',
                size : 'small',
                buttons : {
                    cancel : {
                        label : '取消',
                        className:'btn-white btn-info'
                    },
                    confirm : {
                        label : '确定',
                        className:'btn-white btn-info colorbtn'
                    }
                },
                callback:function(result){
                    if (result) {
                        var acceptanceGoodsId = $(_this).parents('.goodsListTbody2').find('td').eq(1).attr('acceptanceBusinessGoodsId')
                        $.ajax({
                            url: '/bill/deleteFee',
                            type: 'get',
                            data: {
                                'acceptanceBusinessGoodsId': acceptanceGoodsId,
                            },
                            success: function (data) {
                                if (data.success) {
                                    new $.zui.Messager('删除成功。' , {
                                        type: 'success'
                                    }).show();
                                    $(_this).parents('.goodsListTbody2').remove();
                                    sortIGoodsnfo2();

                                } else {
                                    new $.zui.Messager('删除失败：' + data.msg , {
                                        type: 'danger'
                                    }).show();
                                }
                            },
                            error: function (status) {
                                new $.zui.Messager('删除失败。' , {
                                    type: 'danger'
                                }).show();
                            }
                        })
                    };
                }
            })

        }else {
            $(_this).parents('.goodsListTbody2').remove();
            sortIGoodsnfo2();
        }
    });

    if($(".paymentListTbodyBack").length) {
        $(".paymentListTbody:first").remove();
    }

    //计算结算金额
    function settlementAmount() {
        $("[name=settlementAmount]").val(commaDelimiter(Math.round((Number($(".totalFee").text().split(',').join('')) + Number($('.totalPrice').text().split(',').join('')))*100)/100))
    }

    // 排序-回款计划
    function sortReceiptInfo(){
        var totalAmount = 0;
        $(".paymentListTbody").each(function(i,ele){
            $(ele).find('td:first span').text(i+1);
            totalAmount += Number($(ele).find('.paybackAmount').val().split(',').join(''))
        });
        if( $(".paymentListTbody").length <= 1 ){
            $('.paymentTable .negativeInformationReduce').hide();
        }else{
            $('.paymentTable .negativeInformationReduce').show();
        };
        if(totalAmount!=='null') {
            $(".totalPayback").text(commaDelimiter(Math.round(totalAmount*100)/100))
        }else {
            $(".totalPayback").text('0.00')
        }

    };
    sortReceiptInfo();

    // 添加行-回款计划
    $("#entryForm").on('click','.paymentTable .negativeInformationPlus',function(){
        var supplierTrClone = $(".paymentListTbody:first").clone();
        supplierTrClone.find('.negativeInformationReduce').show();
        supplierTrClone.find('.error').hide();
        supplierTrClone.find('input').val('');
        setDate(supplierTrClone.find('.paybackDate'),'1970-01-01','2116-12-31')
        $(this).parents('.paymentListTbody').after(supplierTrClone);
        sortReceiptInfo();
    });

    // 删除行
    $("#entryForm").on('click','.paymentTable .negativeInformationReduce',function(){
        $(this).parents('.paymentListTbody').remove();
        sortReceiptInfo();
    });

    //结算时间修改
    $('[name=settlementDate]').change(function () {
        if($(this).val() !== '') {
            $.ajax({
                url:'/bill/getExpectedSettlementDate',
                type:'get',
                data:{
                    'settlementDate': $(this).val(),
                    'businessNumber': $('[name=businessNumber]').val()
                },
                success:function(data){
                    if( data.success ){
                        $("[name=settlementDateBegin]").val(data.data.settlementDateBegin)
                        $("[name=settlementDateEnd]").val(data.data.settlementDateEnd)
                    }else{
                        $("[name=settlementDateBegin]").val('')
                        $("[name=settlementDateEnd]").val('')
                        new $.zui.Messager(data.msg, {
                            type: 'danger'
                        }).show();
                    }
                },
                error:function(status){
                    new $.zui.Messager(':'+status, {
                        type: 'danger'
                    }).show();
                }
            })
        }else {
            $("[name=settlementDateBegin]").val('')
            $("[name=settlementDateEnd]").val('')
        }
    })
    //保存
    function submitFunction(e){
        var postdata = new FormData();

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

        //货物信息
        for(var i=1;i<$(".goodsListTbody").length;i++) {
            postdata.append('billGoodsInformations['+(i-1)+'].acceptanceDate',$(".goodsListTbody").eq(i).find('td').eq(1).text());
            postdata.append('billGoodsInformations['+(i-1)+'].supplierId',$(".goodsListTbody").eq(i).find('td').eq(1).attr('supplierId'));
            postdata.append('billGoodsInformations['+(i-1)+'].acceptanceBusinessGoodsId',$(".goodsListTbody").eq(i).find('td').eq(1).attr('acceptanceBusinessGoodsId'));
            postdata.append('billGoodsInformations['+(i-1)+'].goodsName',$(".goodsListTbody").eq(i).find('td').eq(3).text());
            postdata.append('billGoodsInformations['+(i-1)+'].goodsFactory',$(".goodsListTbody").eq(i).find('td').eq(4).text());
            postdata.append('billGoodsInformations['+(i-1)+'].goodsType',$(".goodsListTbody").eq(i).find('td').eq(5).text());
            postdata.append('billGoodsInformations['+(i-1)+'].goodsUnit',$(".goodsListTbody").eq(i).find('td').eq(6).text());
            postdata.append('billGoodsInformations['+(i-1)+'].goodsNum',$(".goodsListTbody").eq(i).find('td').eq(7).text());
            postdata.append('billGoodsInformations['+(i-1)+'].salePrice',$(".goodsListTbody").eq(i).find('td').eq(8).find('input').val().split(',').join(''));
            postdata.append('billGoodsInformations['+(i-1)+'].totalSalePrice',$(".goodsListTbody").eq(i).find('td').eq(9).find('input').val().split(',').join(''));
            postdata.append('billGoodsInformations['+(i-1)+'].salesGuaranteeMoney',$(".goodsListTbody").eq(i).find('td').eq(10).find('input').val().split(',').join(''));
            postdata.append('billGoodsInformations['+(i-1)+'].purchasePrice',$(".goodsListTbody").eq(i).find('td').eq(11).find('input').val().split(',').join(''));
            postdata.append('billGoodsInformations['+(i-1)+'].totalPurchasePrice',$(".goodsListTbody").eq(i).find('td').eq(12).find('input').val().split(',').join(''));
            postdata.append('billGoodsInformations['+(i-1)+'].purchaseGuaranteeMoney',$(".goodsListTbody").eq(i).find('td').eq(13).find('input').val().split(',').join(''));
        }
        i=null;
        //资金占用费
        for(var i=1;i<$(".goodsListTbody2").length;i++) {
            postdata.append('billCapitalOccupationFees['+(i-1)+'].acceptanceDate',$(".goodsListTbody2").eq(i).find('td').eq(1).text());
            postdata.append('billCapitalOccupationFees['+(i-1)+'].supplierId',$(".goodsListTbody2").eq(i).find('td').eq(1).attr('supplierId'));
            postdata.append('billCapitalOccupationFees['+(i-1)+'].acceptanceBusinessGoodsId',$(".goodsListTbody2").eq(i).find('td').eq(1).attr('acceptanceBusinessGoodsId'));
            postdata.append('billCapitalOccupationFees['+(i-1)+'].goodsName',$(".goodsListTbody2").eq(i).find('td').eq(3).text());
            postdata.append('billCapitalOccupationFees['+(i-1)+'].goodsFactory',$(".goodsListTbody2").eq(i).find('td').eq(4).text());
            postdata.append('billCapitalOccupationFees['+(i-1)+'].goodsType',$(".goodsListTbody2").eq(i).find('td').eq(5).text());
            postdata.append('billCapitalOccupationFees['+(i-1)+'].goodsUnit',$(".goodsListTbody2").eq(i).find('td').eq(6).text());
            postdata.append('billCapitalOccupationFees['+(i-1)+'].goodsNum',$(".goodsListTbody2").eq(i).find('td').eq(7).text());
            postdata.append('billCapitalOccupationFees['+(i-1)+'].capitalOccupationFee',$(".goodsListTbody2").eq(i).find('td').eq(8).find('input').val().split(',').join(''));
        }
        i=null;

        postdata.append('tradingPlatformId',$("[name=platformId]").val());
        postdata.append('managerName',$("[name=managerName]").val());
        postdata.append('settlementDate',$("[name=settlementDate]").val());
        postdata.append('settlementAmount',$("[name=settlementAmount]").val().split(',').join(''));
        postdata.append('settlementDateBegin',$("[name=settlementDateBegin]").val());
        postdata.append('settlementDateEnd',$("[name=settlementDateEnd]").val());
        postdata.append('billInformationNumber',$("[name=billInformationNumber]").val());

        //回款计划
        for(var i=0;i<$(".paymentListTbody").length;i++) {
            postdata.append('billRepaymentPlans['+i+'].repaymentDate',$(".paymentListTbody").eq(i).find('.paybackDate').val());
            postdata.append('billRepaymentPlans['+i+'].repaymentAmount',$(".paymentListTbody").eq(i).find('.paybackAmount').val().split(',').join(''));
        }
        i=null;

        // 附件信息
        for( var m=0;m<$('.file .addFileList').data('filearray').length;m++ ){
            postdata.append('file['+m+']',$('.file .addFileList').data('filearray')[m]);
        };
        m = null;
        for( var m=0;m<$('.netPrice .addFileList').data('filearray').length;m++ ){
            postdata.append('netPrice['+m+']',$('.netPrice .addFileList').data('filearray')[m]);
        };
        m = null;

        postdata.append('supplement',$("[name=supplement]").val());
        for( var m=0;m<$('.additional .addFileList').data('filearray').length;m++ ){
            postdata.append('additional['+m+']',$('.additional .addFileList').data('filearray')[m]);
        };
        m = null;

        // 删除的附件信息
        // for( var m=0;m<$('.addFileList').data('deletefileid').length;m++ ){
        //     postdata.append('deleteFile['+m+']',$('.addFileList').data('deletefileid')[m]);
        // };
        // m = null;
        for(var m=0; m<deleteFileIdArr.length; m++) {
            postdata.append('deleteFileIds['+m+']',deleteFileIdArr[m]);
        }
        m = null;

        var url = '/bill/updateChangeBill',tip='变更';

        $.ajax({
            url:url,
            type:'post',
            data:postdata,
            processData:false,
            contentType:false,
            success:function(data){
                if( data.success ){
                    new $.zui.Messager( tip+'结算单成功', {
                        type: 'success'
                    }).show();
                    $.get('/bill/pendingList?businessBasicId='+settleQuery.detailId2,function(data){
                        $(".yk_rightcontent").empty().append(data);
                    });
                }else{
                    new $.zui.Messager(tip+'结算单失败:'+data.msg, {
                        type: 'danger'
                    }).show();
                }
            },
            error:function(status){
                new $.zui.Messager(tip+'结算单时发生错误:'+status, {
                    type: 'danger'
                }).show();
            }
        });
        return false;
    };

    var formRules = {
        'managerName':{
            required:true
        },
        'settlementDate':{
            required:true
        },
        'settlementDateBegin':{
            required:true
        },
        'settlementDateEnd':{
            required:true,
        },

    };

    var formMessages = {
        'managerName':{
            required:'请输入经办人',
        },
        'settlementDate':{
            required:'请选择结算时间'
        },
        'settlementDateBegin':{
            required:'请选择开始日期'
        },
        'settlementDateEnd':{
            required:'请选择结束日期'
        },
    };


    //表单验证
    function addNewCustomer(e){

        if($(".addFileList .fileinput").val() == '' && !$(".addFileList .content").length) {
            $(".addFileList .error").addClass('shows').show();
        }else {
            $(".addFileList .error").removeClass('shows').hide();
        }

        $("#entryForm").validate({
            promptPosition : "bottomLeft",
            submitHandler : function(form) {
                //货物必填验证
                if($(".goodsListTable .goodsListTbody").length) {
                    //$('.goodsListTable .validInput').keyup();
                }else {
                    new $.zui.Messager('请添加货物信息。' , {
                        type: 'danger'
                    }).show();
                    return false;
                }
                if($(".goodsListTable2 .goodsListTbody2").length) {
                    $('.goodsListTable2 .validInput').keyup();
                }else {
                    // new $.zui.Messager('请添加资金占用费。' , {
                    //     type: 'danger'
                    // }).show();
                    // return false;
                }
                //回款计划
                if($(".paymentListTbody").length) {
                    $('.paymentListTbody input').change();
                }else {
                    new $.zui.Messager('请添加回款计划。' , {
                        type: 'danger'
                    }).show();
                    return false;
                }
                if( $('.error.shows').length>0 ){
                    $('.error.shows:first').prev().focus();
                    return;
                };
                submitFunction(e);
            },
            rules:formRules,
            messages : formMessages
        });
    };

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

    })
    $(".goodsListTable2").on("keyup",".validInput",function(e){
        if($(this).parent().parent().attr('display') !== 'none') {
            if($(this).val() == '') {
                $(this).next().addClass('shows').show();
            }else {
                $(this).next().removeClass('shows').hide();
            }
        }

    })

    $(".paymentListTbody").on("change","input",function(e){
        if($(this).val() == '') {
            $(this).next().addClass('shows').show();
        }else {
            $(this).next().removeClass('shows').hide();
        }
    })



    //提交按钮
    $(".yk_addNewMsg .submitBusiness").click(addNewCustomer);

    //关闭按钮
    $(".yk_addNewMsg .btn-cancel, .newBackBtn").click(function(){
        $.get('/bill/pendingList?businessBasicId='+settleQuery.detailId2,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 operate2(cellValue,options,rowObject){
        var btnstr = '';
        btnstr += '<p><span>选择</span><i class="icon-check" onclick="chooseGoods2('+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) {
            return commaDelimiter(cellValue)
        }else {
            return ''
        }
    }
    function monthlyinterestRate(cellValue, options, rowObject) {
        if (rowObject.priceRule.monthlyinterestRate !== undefined && rowObject.priceRule.monthlyinterestRate !== null) {
            return rowObject.priceRule.monthlyinterestRate
        } else {
            return ''
        }

    }

    function accrualMarginCalcMethod(cellValue, options, rowObject) {
        if (rowObject.priceRule.accrualMarginCalcMethodDict !== undefined && rowObject.priceRule.accrualMarginCalcMethodDict !== null) {
            return rowObject.priceRule.accrualMarginCalcMethodDict.name
        } else {
            return ''
        }

    }

    function differAmount(cellValue, options, rowObject) {
        if (rowObject.priceRule.differAmount !== undefined && rowObject.priceRule.differAmount !== null) {
            return rowObject.priceRule.differAmount
        } else {
            return ''
        }

    }

    function factoringFinanceDeadline(cellValue, options, rowObject) {
        if (rowObject.priceRule.factoringFinanceDeadline !== undefined && rowObject.priceRule.factoringFinanceDeadline !== null) {
            return rowObject.priceRule.factoringFinanceDeadline
        } else {
            return ''
        }

    }

    function tablefunction(tableid){
        var tipword = '',pageid = '',pageNo = 1,postData = {};url = '',colNamesArray = [],colModelArray = [];
        switch( tableid ){
            case '#chooseGoodsList':tipword ='货物';pageid = '#chooseGoodsListPage';
                postData = {
                    // 'beginTime':settleQuery.startDate,
                    // 'endTime':settleQuery.endDate,
                    // 'status':settleQuery.status,
                    'condition':settleQuery.detailId
                };
                url = '/bill/getAcceptanceGoods';
                colNamesArray = ['ID','修改标识','月利率','利差计算方式','差额','保理融资期限', '编号','验收日期','供应商','供应商','供应商Id','货物Id','采购质保金比例','销售质保金比例','采购单价','名称','厂家','型号','单位','数量','销售单价'];
                colModelArray = [
                    {name: 'id', label: 'ID', hidedlg:true, hidden:true,sortable:false,title:false},
                    {name: 'clear', label: '修改标识', hidedlg: true, hidden: true, sortable: false, title: false},
                    {
                        name: 'monthlyinterestRate',
                        label: '月利率',
                        hidedlg: true,
                        hidden: true,
                        sortable: false,
                        title: false,
                        formatter: monthlyinterestRate
                    },
                    {name: 'accrualMarginCalcMethod', label: '利差计算方式', hidedlg: true, hidden: true, sortable: false, title: false, formatter:accrualMarginCalcMethod},
                    {name: 'differAmount', label: '差额', hidedlg: true, hidden: true, sortable: false, title: false, formatter:differAmount},
                    {name: 'factoringFinanceDeadline', label: '差额', hidedlg: true, hidden: true, sortable: false, title: false, formatter:factoringFinanceDeadline},
                    {name: 'orderNumber', label: '编号', hidedlg:true, width:55,sortable:false,title:false},
                    {name: 'acceptanceDate', label: '验收日期',sortable:false,align:'left',title:false},
                    {name: 'customer.enterpriseName', label: '供应商',sortable:false,align:'left',title:false},
                    {name: 'enterpriseName', label: '供应商',hidedlg:true, hidden:true,sortable:false,align:'left',title:false,formatter:supplier},
                    {name: 'supplierId', label: '供应商Id',hidedlg:true, hidden:true,sortable:false,align:'left',title:false},
                    {name: 'acceptanceBusinessGoodsId', label: '货物Id',hidedlg:true, hidden:true,sortable:false,align:'left',title:false},
                    {name: 'purchRetentionPercent', label: '采购质保金比例',hidedlg:true, hidden:true,sortable:false,align:'left',title:false},
                    {name: 'salesRetentionPercent', label: '销售质保金比例',hidedlg:true, hidden:true,sortable:false,align:'left',title:false},
                    {name: 'purchasePrice', label: '采购单价',hidedlg:true, hidden:true,sortable:false,align:'left',title:false,formatter:showAmount},
                    {name: 'goodsName', label: '名称',sortable:false,align:'left',title:false},
                    {name: 'goodsFactory', label: '厂家',sortable:false,align:'left',title:false},
                    {name: 'goodsType', label: '型号',sortable:false,align:'left',title:false},
                    {name: 'goodsUnit', label: '单位',sortable:false,align:'left',title:false},
                    {name: 'goodsNum', label: '数量',sortable:false,align:'left',title:false},
                    {name: 'salePrice', label: '销售单价',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,
            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')
            },
            rownumbers:false,
            postData: postData,
            page:pageNo,
            loadError:function(){
                // new $.zui.Messager(tipword+'列表加载失败', {
                //     type: 'warning'
                // }).show();
            }
        },true);
        $(tableid).trigger('reloadGrid');
    };
    function tablefunction2(tableid){
        var tipword = '',pageid = '',pageNo = 1,postData = {};url = '',colNamesArray = [],colModelArray = [];
        switch( tableid ){
            case '#chooseGoodsList2':tipword ='货物';pageid = '#chooseGoodsListPage2';
                postData = {
                    // 'beginTime':settleQuery.startDate,
                    // 'endTime':settleQuery.endDate,
                    // 'status':settleQuery.status,
                    'condition':settleQuery.detailId
                };
                url = '/bill/getFeeGoods';
                colNamesArray = ['ID','修改标识','月利率','利差计算方式','差额','保理融资期限', '编号','验收日期','供应商','供应商','供应商Id','货物Id','采购质保金比例','销售质保金比例','采购单价','名称','厂家','型号','单位','数量','销售单价'];
                colModelArray = [
                    {name: 'id', label: 'ID', hidedlg:true, hidden:true,sortable:false,title:false},
                    {name: 'clear', label: '修改标识', hidedlg: true, hidden: true, sortable: false, title: false},
                    {
                        name: 'monthlyinterestRate',
                        label: '月利率',
                        hidedlg: true,
                        hidden: true,
                        sortable: false,
                        title: false,
                        formatter: monthlyinterestRate
                    },
                    {name: 'accrualMarginCalcMethod', label: '利差计算方式', hidedlg: true, hidden: true, sortable: false, title: false, formatter:accrualMarginCalcMethod},
                    {name: 'differAmount', label: '差额', hidedlg: true, hidden: true, sortable: false, title: false, formatter:differAmount},
                    {name: 'factoringFinanceDeadline', label: '保理融资期限', hidedlg: true, hidden: true, sortable: false, title: false, formatter:factoringFinanceDeadline},
                    {name: 'orderNumber', label: '编号', hidedlg:true, width:55,sortable:false,title:false},
                    {name: 'acceptanceDate', label: '验收日期',sortable:false,align:'left',title:false},
                    {name: 'customer.enterpriseName', label: '供应商',sortable:false,align:'left',title:false},
                    {name: 'enterpriseName', label: '供应商',hidedlg:true, hidden:true,sortable:false,align:'left',title:false,formatter:supplier},
                    {name: 'supplierId', label: '供应商Id',hidedlg:true, hidden:true,sortable:false,align:'left',title:false},
                    {name: 'acceptanceBusinessGoodsId', label: '货物Id',hidedlg:true, hidden:true,sortable:false,align:'left',title:false},
                    {name: 'purchRetentionPercent', label: '采购质保金比例',hidedlg:true, hidden:true,sortable:false,align:'left',title:false},
                    {name: 'salesRetentionPercent', label: '销售质保金比例',hidedlg:true, hidden:true,sortable:false,align:'left',title:false},
                    {name: 'purchasePrice', label: '采购单价',hidedlg:true, hidden:true,sortable:false,align:'left',title:false,formatter:showAmount},
                    {name: 'goodsName', label: '名称',sortable:false,align:'left',title:false},
                    {name: 'goodsFactory', label: '厂家',sortable:false,align:'left',title:false},
                    {name: 'goodsType', label: '型号',sortable:false,align:'left',title:false},
                    {name: 'goodsUnit', label: '单位',sortable:false,align:'left',title:false},
                    {name: 'goodsNum', label: '数量',sortable:false,align:'left',title:false},
                    {name: 'salePrice', label: '销售单价',sortable:false,align:'left',title:false,formatter:showAmount},
                ];
                break;
        };
        sxUtil.jqGrid(tableid,{
            colNames:colNamesArray,
            colModel:colModelArray,
            height:'auto',
            mtype:'GET',
            url: url,
            pager : pageid,
            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')
            },
            rownumbers:false,
            postData: postData,
            page:pageNo,
            loadError:function(){
                // new $.zui.Messager(tipword+'列表加载失败', {
                //     type: 'warning'
                // }).show();
            }
        },true);
        $(tableid).trigger('reloadGrid');
    };

    tablefunction('#chooseGoodsList');
    tablefunction2('#chooseGoodsList2');

    var goodsFlag= '';
    //货物
    $("#chooseButton").click(function () {
        goodsFlag = 'goods';

        $('#chooseGoodsList').setGridParam({
            mtype:'GET',
            url : '/bill/getAcceptanceGoods',
            datatype : 'json',
            postData: {
                // 'beginTime':settleQuery.startDate,
                // 'endTime':settleQuery.endDate,
                // 'status':settleQuery.status,
                'condition':settleQuery.detailId
            },
            page : 1
        });
        $('#chooseGoodsList').trigger('reloadGrid');
        $("#myModal-chooseGoods").modal("show");
        $("#myModal-chooseGoods").on('shown.zui.modal',function () {
            $(window).resize();
            $("#chooseGoodsList_cb").css({'width': '45', 'padding': '0 0.12rem'})
            $('#chooseGoodsList .jqgfirstrow td:first').css('width', '45')

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

    });
    //资金占用
    $("#chooseButton2").click(function () {
        goodsFlag = 'amount';

        $('#chooseGoodsList2').setGridParam({
            mtype:'GET',
            url : '/bill/getFeeGoods',
            datatype : 'json',
            postData: {
                // 'beginTime':settleQuery.startDate,
                // 'endTime':settleQuery.endDate,
                // 'status':settleQuery.status,
                'condition':settleQuery.detailId
            },
            page : 1
        });
        $('#chooseGoodsList2').trigger('reloadGrid');
        $("#myModal-chooseGoods2").modal("show");
        $("#myModal-chooseGoods2").on('shown.zui.modal',function () {
            $(window).resize();
            $("#chooseGoodsList2_cb").css({'width': '45', 'padding': '0 0.12rem'})
            $('#chooseGoodsList2 .jqgfirstrow td:first').css('width', '45')

            $(".choosedGoodsList2").empty();
        })
        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 width="5%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;"></td>
                        <td width="9%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+chooseData.acceptanceDate+`</td>
                        <td width="11%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+chooseData.enterpriseName+`</td>
                        <td width="9%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+chooseData.goodsName+`</td>
                        <td width="11%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+chooseData.goodsFactory+`</td>
                        <td width="11%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+chooseData.goodsType+`</td>
                        <td width="10%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+chooseData.goodsUnit+`</td>
                        <td width="10%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+chooseData.goodsNum+`</td>
                        <td width="10%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+(chooseData.salePrice?chooseData.salePrice:'')+`</td>
                        <td style="display: none">`+chooseData.supplierId+`</td>
                        <td style="display: none">`+chooseData.acceptanceBusinessGoodsId+`</td>
                        <td style="display: none">`+chooseData.salesRetentionPercent+`</td>
                        <td style="display: none">`+chooseData.purchRetentionPercent+`</td>
                        <td style="display: none">`+chooseData.purchasePrice+`</td>
                        <td style="display: none">`+chooseData.clear+`</td>
                        <td style="display: none" class="monthlyinterestRate">`+chooseData.monthlyinterestRate+`</td>
                        <td style="display: none" class="accrualMarginCalcMethod">` + chooseData.accrualMarginCalcMethod + `</td>
                        <td style="display: none" class="differAmount">` + chooseData.differAmount + `</td>
                        <td style="display: none" class="factoringFinanceDeadline">` + chooseData.factoringFinanceDeadline + `</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('select').val('');

                supplierTrClone.find('td').eq(1).text($(ele).find('td').eq(1).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).find('input').val($(ele).find('td').eq(8).text())//销售单价
                supplierTrClone.find('td').eq(1).attr('supplierId',$(ele).find('td').eq(9).text())
                supplierTrClone.find('td').eq(1).attr('acceptanceBusinessGoodsId',$(ele).find('td').eq(10).text())

                supplierTrClone.find('td').eq(2).attr('salesRetentionPercent',$(ele).find('td').eq(11).text())
                supplierTrClone.find('td').eq(2).attr('purchRetentionPercent',$(ele).find('td').eq(12).text())
                supplierTrClone.find('td').eq(11).find('input').val($(ele).find('td').eq(13).text())//采购单价

                supplierTrClone.find('td').eq(2).attr('monthlyinterestRate',$(ele).find('td.monthlyinterestRate').text())
                supplierTrClone.find('td').eq(2).attr('accrualMarginCalcMethod',$(ele).find('td.accrualMarginCalcMethod').text())
                supplierTrClone.find('td').eq(2).attr('differAmount',$(ele).find('td.differAmount').text())
                supplierTrClone.find('td').eq(2).attr('factoringFinanceDeadline',$(ele).find('td.factoringFinanceDeadline').text())

                //如果有销售单价
                if($(ele).find('td').eq(8).text() !== '') {
                    var oneSale = Number($(ele).find('td').eq(8).text().split(',').join(''))
                    var num = Number($(ele).find('td').eq(7).text());
                    var totalSale = Math.round((oneSale * num)*100)/100;
                    supplierTrClone.find('td').eq(9).find('input').val(commaDelimiter(totalSale))

                    //如果有销售质保金比例
                    if($(ele).find('td').eq(11).text() !== '') {
                        var saleRetPct = Number($(ele).find('td').eq(11).text())
                        var saleRet = Math.round((oneSale * num * saleRetPct/100)*100)/100;
                        supplierTrClone.find('td').eq(10).find('input').val(commaDelimiter(saleRet))
                    }else {
                        supplierTrClone.find('td').eq(10).find('input').val(0.00)
                    }
                }else{
                    supplierTrClone.find('td').eq(8).find('input').val(0.00)
                    supplierTrClone.find('td').eq(9).find('input').val(0.00)
                    supplierTrClone.find('td').eq(10).find('input').val(0.00)
                }
                //如果有采购单价
                if($(ele).find('td').eq(13).text() !== '') {
                    var onePurch = Number($(ele).find('td').eq(13).text().split(',').join(''))
                    var num = Number($(ele).find('td').eq(7).text());
                    var totalPurch = Math.round((onePurch * num)*100)/100;
                    supplierTrClone.find('td').eq(12).find('input').val(commaDelimiter(totalPurch))

                    //如果有销售质保金比例
                    if($(ele).find('td').eq(12).text() !== '') {
                        var purchRetPct = Number($(ele).find('td').eq(12).text())
                        var purchRet = Math.round((onePurch * num * purchRetPct/100)*100)/100;
                        supplierTrClone.find('td').eq(13).find('input').val(commaDelimiter(purchRet))
                    }else {
                        supplierTrClone.find('td').eq(13).find('input').val(0.00)
                    }
                }else {
                    supplierTrClone.find('td').eq(11).find('input').val(0.00)
                    supplierTrClone.find('td').eq(12).find('input').val(0.00)
                    supplierTrClone.find('td').eq(13).find('input').val(0.00)
                }

                if($(ele).find('td').eq(14).text()=='true') {
                    supplierTrClone.find('td').eq(8).find('input').attr('readOnly',true)
                }

                supplierTrClone.show();

                $('.goodsListTable').append(supplierTrClone);

                sortIGoodsnfo();
            }else {

            }

        })
        $("#myModal-chooseGoods").modal("hide");
    })
    $(".chooseSure2").click(function () {
        var ids = $('#chooseGoodsList2').jqGrid('getGridParam', 'selarrrow');
        if (ids.length > 0) {
            for (var i = 0; i < ids.length; i++) {
                var chooseData = $('#chooseGoodsList2').jqGrid('getRowData', ids[i]);
                var trStr = `<tr class="choosedGoodsTbody2">
                        <td width="5%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;"></td>
                        <td width="9%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+chooseData.acceptanceDate+`</td>
                        <td width="11%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+chooseData.enterpriseName+`</td>
                        <td width="9%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+chooseData.goodsName+`</td>
                        <td width="11%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+chooseData.goodsFactory+`</td>
                        <td width="11%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+chooseData.goodsType+`</td>
                        <td width="10%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+chooseData.goodsUnit+`</td>
                        <td width="10%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+chooseData.goodsNum+`</td>
                        <td width="10%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">`+(chooseData.salePrice?chooseData.salePrice:'')+`</td>
                        <td style="display: none">`+chooseData.supplierId+`</td>
                        <td style="display: none">`+chooseData.acceptanceBusinessGoodsId+`</td>
                        <td style="display: none">`+chooseData.salesRetentionPercent+`</td>
                        <td style="display: none">`+chooseData.purchRetentionPercent+`</td>
                        <td style="display: none">`+chooseData.purchasePrice+`</td>
                        <td style="display: none">`+chooseData.clear+`</td>
                        <td style="display: none" class="monthlyinterestRate">`+chooseData.monthlyinterestRate+`</td>
                        <td style="display: none" class="accrualMarginCalcMethod">` + chooseData.accrualMarginCalcMethod + `</td>
                        <td style="display: none" class="differAmount">` + chooseData.differAmount + `</td>
                        <td style="display: none" class="factoringFinanceDeadline">` + chooseData.factoringFinanceDeadline + `</td>
                        <td width="10%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;border-right: 1px solid #E8F0F3;"><span class="relaseGoods2" style="color: #5AC4FC;cursor: pointer">释放</span></td>
                    </tr>`
                $(".choosedGoodsList2").append(trStr);
            }
        }

        $(".choosedGoodsTbody2").each(function (i, ele) {

            var supplierTrClone2 = $(".goodsListTbody2:first").clone();
            supplierTrClone2.find('.negativeInformationReduce').show();
            supplierTrClone2.find('.error').hide();
            supplierTrClone2.find('input').val('');
            supplierTrClone2.find('select').val('');

            supplierTrClone2.find('td').eq(1).text($(ele).find('td').eq(1).text())
            supplierTrClone2.find('td').eq(2).text($(ele).find('td').eq(2).text())
            supplierTrClone2.find('td').eq(3).text($(ele).find('td').eq(3).text())
            supplierTrClone2.find('td').eq(4).text($(ele).find('td').eq(4).text())
            supplierTrClone2.find('td').eq(5).text($(ele).find('td').eq(5).text())
            supplierTrClone2.find('td').eq(6).text($(ele).find('td').eq(6).text())
            supplierTrClone2.find('td').eq(7).text($(ele).find('td').eq(7).text())
            //supplierTrClone2.find('td').eq(8).find('input').val($(ele).find('td').eq(8).text())
            supplierTrClone2.find('td').eq(1).attr('supplierId',$(ele).find('td').eq(9).text())
            supplierTrClone2.find('td').eq(1).attr('acceptanceBusinessGoodsId',$(ele).find('td').eq(10).text())
            supplierTrClone2.show();

            $('.goodsListTable2').append(supplierTrClone2);

            sortIGoodsnfo2();

        })
        $("#myModal-chooseGoods2").modal("hide");
    })

    //销售单价输入
    $('.goodsTable').on('keyup', '.salePrice',function () {
        var oneSale = Number($(this).val().split(',').join(''))
        var num = Number($(this).parent().parent().find('td').eq(7).text());
        var totalSale = Math.round((oneSale * num)*100)/100;
        $(this).parent().siblings().find('.totalSalePrice').val(commaDelimiter(totalSale));

        //如果有质保金比例
        if($(this).parent().siblings().eq(2).attr('salesRetentionPercent')) {
            var saleRetPct = Number($(this).parent().siblings().eq(2).attr('salesRetentionPercent'))
            var saleRet = Math.round((oneSale * num * saleRetPct/100)*100)/100;
            $(this).parent().siblings().find('.salesGuaranteeMoney').val(commaDelimiter(saleRet));
        }

        //计算采购单价--根据利差计算规则
        var purchSale=0;
        if($(this).parent().siblings().eq(2).attr('accrualMarginCalcMethod') !== '' && $(this).parent().siblings().eq(2).attr('accrualMarginCalcMethod') !== undefined) {
            var accrualMarginCalcMethod = $(this).parent().siblings().eq(2).attr('accrualMarginCalcMethod');
            if(accrualMarginCalcMethod == '固定利率') {   //采购单价=销售单价-销售单价*(月利率)*（预估保理融资期限/30
                if($(this).parent().siblings().eq(2).attr('monthlyinterestRate') !== '' && $(this).parent().siblings().eq(2).attr('monthlyinterestRate') !== undefined) {
                    var monthlyinterestRate = Number($(this).parent().siblings().eq(2).attr('monthlyinterestRate'));
                    var factoringFinanceDeadline = Number($(this).parent().siblings().eq(2).attr('factoringFinanceDeadline'));
                    purchSale = Math.round((oneSale - oneSale *  monthlyinterestRate/100 * factoringFinanceDeadline/30)*100)/100
                }
            }else if(accrualMarginCalcMethod == '固定差额') {    //采购单价=销售单价-差额
                if($(this).parent().siblings().eq(2).attr('differAmount') !== '' && $(this).parent().siblings().eq(2).attr('differAmount') !== undefined) {
                    var differAmount = Number($(this).parent().siblings().eq(2).attr('differAmount'));
                    purchSale = Math.round((oneSale - differAmount)*100)/100
                }
            }

        }
        $(this).parent().siblings().find('.purchasePrice').val(commaDelimiter(purchSale));
        var totalPurch = Math.round((purchSale * num) * 100) / 100;
        $(this).parent().siblings().find('.totalPurchasePrice').val(commaDelimiter(totalPurch));
        //如果有质保金比例
        if ($(this).parent().siblings().eq(2).attr('purchRetentionPercent')) {
            var purchRetPct = Number($(this).parent().siblings().eq(2).attr('purchRetentionPercent'))
            var purchRet = Math.round((purchSale * num * purchRetPct / 100) * 100) / 100;
            $(this).parent().siblings().find('.purchaseGuaranteeMoney').val(commaDelimiter(purchRet));
        }

        sortIGoodsnfo();
    })
    //采购单价输入
    //$('.goodsTable').on('keyup', '.purchasePrice',function () {
        // var oneSale = Number($(this).val().split(',').join(''))
        // var num = Number($(this).parent().parent().find('td').eq(7).text());
        // var totalSale = Math.round((oneSale * num)*100)/100;
        // $(this).parent().siblings().find('.totalPurchasePrice').val(commaDelimiter(totalSale));
        //
        // //如果有质保金比例
        // if($(this).parent().siblings().eq(2).attr('purchRetentionPercent')) {
        //     var saleRetPct = Number($(this).parent().siblings().eq(2).attr('purchRetentionPercent'))
        //     var saleRet = Math.round((oneSale * num * saleRetPct/100)*100)/100;
        //     $(this).parent().siblings().find('.purchaseGuaranteeMoney').val(commaDelimiter(saleRet));
        // }
    //})

    //资金占用费输入
    $('.goodsTable2').on('keyup', '.billCapitalOccupationFee',function () {
        sortIGoodsnfo2();
    })

    //回款金额输入
    $('.paymentTable').on('keyup', '.paybackAmount',function () {
        sortReceiptInfo();
    })

})