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.acceptanceDate + `</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;">` + chooseData.goodsNum + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + (chooseData.salePrice ? commaDelimiter(chooseData.salePrice) : '') + `</td>
                        <td style="display: none">` + chooseData.acceptanceBusinessGoodsId + `</td>
                        <td 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 calcMoney(money) {
    return money == null ? '/' : money
}

function getSupplier() {
    var postdata = new FormData();
    $("[name=supplierId]").children().remove()
    postdata.append('businessNumber',  $("[name=businessNo]").val())
    $.ajax({
        url: '/customer/getSuppliersByUser',
        type: 'post',
        data: postdata,
        processData: false,
        contentType: false,
        success: function(data){
            var str = ''
            var list = data.data
            for (var i = 0; i < list.length; i++) {
                str += `<option value ="${list[i].id}">${list[i].enterpriseName}</option>`
            }
            $("[name=supplierId]").append(str)
            $("[name=supplierId]").each(function (i, ele) {
                if(i !== 0) {
                    $(ele).val($(ele).attr('supplierId'))
                }
            })
        },
        error: function(status){
            console.log(status, '获取供应商失败')
        }
    });
}

$(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=invoiceDate]', '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 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>';

    var fileWrapperbasic2 = '<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 target="_blank" class="btn-yulan-file">' +
        '<em style="font-style:normal">预览</em><i class="operateIconfont operateIcon-yulan"></i></a></div>' +
        '<div class="actions" style="width:0.5rem"><a class="btn-xiazai-file">' +
        '<em style="font-style:normal">下载</em><i class="operateIconfont operateIcon-xiazai"></i></a></div></div>';

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

    // 展示原先有的附件
    function showOriginalFile(source, insert,htmlStr) {
        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-delete-file').hide();
            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();
        }
        ;
    };
    function showOriginalFile2(source, insert,htmlStr) {
        for (var j = 0; j < $(source).length; j++) {
            var originalFileWrapper = $(htmlStr).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-delete-file').hide();
            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();
        }
        ;
    };

        // 展示原附件
    showOriginalFile2('.saleContractFile', '.saleAddFileList',fileWrapperbasic2);
    showOriginalFile2('.purchContractFile', '.purchAddFileList',fileWrapperbasic2);
    if($('.purchInvoiceFile').length) {
        showOriginalFile('.purchInvoiceFile', '.file .purchAddFileList');
    }

    // 触发选择附件
    $('#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;
    });


    // 排序-货物
    function sortIGoodsnfo() {
        var totalPrice = 0;
        var totalInvoicing = 0;
        $(".goodsListTbody").each(function (i, ele) {
            $(ele).find('td:first span').text(i);
            if(i > 0) {
                let money = $(ele).find('td').eq(10).find('input').val()
                if(money) {
                    totalPrice += Number(money.split(',').join(''))
                }
            }
            totalInvoicing += Number($(ele).find('td').eq(9).find('input').val().split(',').join(''))
        });
        if ($(".goodsListTbody").length <= 1) {
            $('.goodsTable .negativeInformationReduce').hide();
        } else {
            $('.goodsTable .negativeInformationReduce').show();
        }
        ;
        if (totalPrice !== 'null') {
            $('.totalAmount').text(commaDelimiter((Math.round(totalPrice * 100) / 100).toFixed(2)))
            let possessionCost =  Number($('.possessionCost').val().split(',').join('')) ? Number($('.possessionCost').val().split(',').join('')) : 0
            $('[name=openAmount]').val(commaDelimiter((Math.round((totalPrice + possessionCost) * 100) / 100).toFixed(2)))
        } else {
            $('.totalAmount').text('0.00')
            $('[name=openAmount]').val(0)
        }
        if(totalInvoicing!== 'null') {
            $('.totalInvoicing').text(commaDelimiter((Math.round(totalInvoicing*10000)/10000).toFixed(4)))
        }else {
            $('.totalInvoicing').text('0.0000')
        }

    };
    sortIGoodsnfo();
    $('.form-horizontal').on('blur', '.possessionCost', function () {
        let num =  Number($(this).val().split(',').join('')) + Number($('.totalAmount').text().split(',').join(''))
        $('[name=openAmount]').val(commaDelimiter(num))
    })
    // 删除行-货物
    $("#entryForm").on('click', '.goodsTable .negativeInformationReduce', function () {
        var id = $(this).parent().parent().attr('id')
        $('.goodsListTbody').each(function ( i, ele) {
            if(id == $(ele).attr('id')) {
                $(ele).remove()
                sortIGoodsnfo();
            }

        })
    });

    // 排序-贴现
    function sortIGoodsnfo2() {
        var totalPrice = 0;
        $(".goodsListTbody2").each(function (i, ele) {
            $(ele).find('td:first span').text(i);
            totalPrice += Number($(ele).find('td').eq(4).find('input').val().split(',').join(''))
        });
        if ($(".goodsListTbody2").length <= 1) {
            $('.goodsTable2 .negativeInformationReduce').hide();
        } else {
            $('.goodsTable2 .negativeInformationReduce').show();
        }
        ;
        if (totalPrice !== 'null') {
            $('.totalAmount2').text(commaDelimiter((Math.round(totalPrice * 100) / 100).toFixed(2)))
            $('[name=openAmount]').val(commaDelimiter((Math.round(totalPrice * 100) / 100).toFixed(2)))
        } else {
            $('.totalAmount2').text('0.00')
            $('[name=openAmount]').val(0)
        }
    };
    sortIGoodsnfo2();
    // 删除行-贴现
     $("#entryForm").on('click', '.goodsTable2 .negativeInformationReduce', function () {
        $(this).parents('.goodsListTbody2').remove();
        sortIGoodsnfo2();
    });
    // 排序-供应商
    function sortIGoodsnfo3() {
        var totalPrice = 0;
        $(".supplierListTbody").each(function (i, ele) {
            $(ele).find('td:first span').text(i);
            totalPrice += Number($(ele).find('td').eq(2).find('input').val().split(',').join(''))
        });
        if ($(".supplierListTbody").length <= 1) {
            $('.supplierTable .negativeInformationReduce').hide();
        } else {
            $('.supplierTable .negativeInformationReduce').show();
        }
        ;
        if (totalPrice !== 'null') {
            $('.totalAmount3').text(commaDelimiter((Math.round(totalPrice * 100) / 100).toFixed(2)))
            $('[name=openAmount]').val(commaDelimiter((Math.round(totalPrice * 100) / 100).toFixed(2)))
        } else {
            $('.totalAmount3').text('0.00')
            $('[name=openAmount]').val(0)
        }
    };
    sortIGoodsnfo3();
    // 删除行-贴现
    $("#entryForm").on('click', '.supplierTable .negativeInformationReduce', function () {
        $(this).parents('.supplierListTbody').remove();
        sortIGoodsnfo3();
    });


    //保存
    function submitFunction(e) {
        var postdata = new FormData();
        // 业务信息
        postdata.append('enterpriseCustomerInfoId', $("[name=enterpriseName]").val());
        postdata.append('businessNumber', $("[name=businessNo]").val());
        postdata.append('tradingPlatformId', $("[name=tradingPlatformId]").val());
        postdata.append('businessBasicInfoId', $('#businessNameId').val());
        
        // 开票信息
        postdata.append('taxIdentifyNumber', $("[name=taxIdentifyNumber]").val());
        postdata.append('address', $("[name=address]").val());
        postdata.append('phone', $("[name=phone]").val());
        postdata.append('accountBankName', $("[name=accountBankName]").val());
        postdata.append('accountNumber', $("[name=accountNumber]").val());
        postdata.append('invoiceType', $("[name=invoiceType]").val());
        postdata.append('amountKind', $("[name=amountKind]").val());
        postdata.append('remark', $("[name=remark]").val());
        postdata.append('openAmount', $('[name=openAmount]').val().split(',').join(''));


        if ($('[name=amountKind] option:selected').text() == '货款') {
            //货物信息
            for (var i = 1; i < $(".goodsListTbody").length; i++) {
                postdata.append('invoiceGoodsInfos[' + (i - 1) + '].settlementBasicInfoId', $(".goodsListTbody").eq(i).find('td').eq(1).attr('settlementBasicInfoId'));
                postdata.append('invoiceGoodsInfos[' + (i - 1) + '].settlementGoodsInfoId', $(".goodsListTbody").eq(i).find('td').eq(1).attr('id'));
                postdata.append('invoiceGoodsInfos[' + (i - 1) + '].goodsFactory', $(".goodsListTbody").eq(i).find('td').eq(1).attr('goodsFactory'));
                postdata.append('invoiceGoodsInfos[' + (i - 1) + '].settlementNumber', $(".goodsListTbody").eq(i).find('td').eq(1).text());
                postdata.append('invoiceGoodsInfos[' + (i - 1) + '].goodsName', $(".goodsListTbody").eq(i).find('td').eq(2).text());
                postdata.append('invoiceGoodsInfos[' + (i - 1) + '].goodsType', $(".goodsListTbody").eq(i).find('td').eq(3).text());
                postdata.append('invoiceGoodsInfos[' + (i - 1) + '].goodsUnit', $(".goodsListTbody").eq(i).find('td').eq(4).text());
                postdata.append('invoiceGoodsInfos[' + (i - 1) + '].goodsQuantity', $(".goodsListTbody").eq(i).find('td').eq(5).text().split(',').join(''));
                postdata.append('invoiceGoodsInfos[' + (i - 1) + '].salesPrice', $(".goodsListTbody").eq(i).find('td').eq(6).text().split(',').join(''));
                postdata.append('invoiceGoodsInfos[' + (i - 1) + '].salesTotalPrice', $(".goodsListTbody").eq(i).find('td').eq(7).text().split(',').join(''));
                postdata.append('invoiceGoodsInfos[' + (i - 1) + '].usedNum', $(".goodsListTbody").eq(i).find('td').eq(8).text().split(',').join(''));
                postdata.append('invoiceGoodsInfos[' + (i - 1) + '].openQuantity', $(".goodsListTbody").eq(i).find('td').eq(9).find('input').val().split(',').join(''));
                postdata.append('invoiceGoodsInfos[' + (i - 1) + '].openAmount', $(".goodsListTbody").eq(i).find('td').eq(10).find('input').val().split(',').join(''));
            }

            i = null;
            postdata.append('invoicePossessionCostInfos.possessionCostType', $("[name=possessionCostType]").val());
            postdata.append('invoicePossessionCostInfos.possessionCost', $("[name=possessionCost]").val().split(',').join(''));
        } else if ($('[name=amountKind] option:selected').text() == '贴现费用') {
            //货物信息
            for (var i = 1; i < $(".goodsListTbody2").length; i++) {
                postdata.append('invoiceGoodsInfos[' + (i - 1) + '].settlementBasicInfoId', $(".goodsListTbody2").eq(i).find('td').eq(1).attr('settlementBasicInfoId'));
                postdata.append('invoiceGoodsInfos[' + (i - 1) + '].goodsName', $(".goodsListTbody2").eq(i).find('td').eq(1).text());
                postdata.append('invoiceGoodsInfos[' + (i - 1) + '].goodsType', $(".goodsListTbody2").eq(i).find('td').eq(2).text());
                postdata.append('invoiceGoodsInfos[' + (i - 1) + '].goodsUnit', $(".goodsListTbody2").eq(i).find('td').eq(3).text());
                postdata.append('invoiceGoodsInfos[' + (i - 1) + '].openAmount', $(".goodsListTbody2").eq(i).find('td').eq(4).find('input').val().split(',').join(''));
            }
            i = null;
        } else if ($('[name=amountKind] option:selected').text() == '资金占用费') {
            //货物信息
            for (var i = 1; i < $(".supplierListTbody").length; i++) {
                postdata.append('invoiceSupplierInfos[' + (i - 1) + '].supplierId', $(".supplierListTbody").eq(i).find('td').eq(1).find('select').val());
                postdata.append('invoiceSupplierInfos[' + (i - 1) + '].openAmount', $(".supplierListTbody").eq(i).find('td').eq(2).find('input').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;

        var url = '/saleInvoice/doAdd', 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('/saleInvoice/pendingSaleList', 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 = {
        'taxIdentifyNo': {
            required: true
        },
        'address': {
            required: true
        },
        'phone': {
            required: true
        },
        'accountBankName': {
            required: true,
        },
        'accountNumber': {
            required: true,
        },
        'amountKind': {
            required: true,
        },
        'invoiceType': {
            required: true,
        },

    };

    var formMessages = {
        'taxIdentifyNo': {
            required: '请输入纳税识别号',
        },
        'address': {
            required: '请输入地址'
        },
        'phone': {
            required: '请输入电话'
        },
        'accountBankName': {
            required: '请输入开户行名称'
        },
        'accountNumber': {
            required: '请输入开户账号'
        },
        'amountKind': {
            required: '请选择金额种类'
        },
        'invoiceType': {
            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 ($('[name=amountKind] option:selected').text() == '货款') {
                    if ($(".goodsListTable .goodsListTbody").length) {
                        $('.goodsListTable .validInput').keyup();
                    } else {
                        new $.zui.Messager('请添加货物信息。', {
                            type: 'danger'
                        }).show();
                        return false;
                    }
                    if($("[name=possessionCostType]")) {
                        if($("[name=possessionCostType]") === '1') {
                            new $.zui.Messager('请输入资金占用费', {
                                type: 'danger'
                            }).show();
                            return false;
                        }
                    }else {
                        new $.zui.Messager('请选择资金占用费类型', {
                            type: 'danger'
                        }).show();
                        return false;
                    }

                } else if ($('[name=amountKind] option:selected').text() == '贴现费用') {
                    if ($(".goodsListTable2 .goodsListTbody2").length) {
                        $('.goodsListTable2 .validInput').keyup();
                    } else {
                        new $.zui.Messager('请添加货物信息。', {
                            type: 'danger'
                        }).show();
                        return false;
                    }
                } else if ($('[name=amountKind] option:selected').text() == '资金占用费') {
                    if ($(".supplierListTable .supplierListTbody").length) {
                        $('.supplierListTable input').keyup();
                    } 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();
            }
        }

    })

    $(".supplierListTbody").on("keyup","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('/saleInvoice/pendingSaleList', 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) {
            return commaDelimiter(cellValue)
        } else {
            return ''
        }
    }

    //金额种类选择
    $('[name=amountKind]').change(function () {
        if ($('[name=amountKind] option:selected').text() == '货款') {
            $(".huokuan").show();
            $(".tiexian").hide();
            $(".zijin").hide();
            let num = Number($('.totalAmount').text().split(',').join('')) + Number($('.possessionCost').val().split(',').join(''))
            $('[name=openAmount]').val(commaDelimiter(num))
            //$('.goodsListTable').empty();
        } else if ($('[name=amountKind] option:selected').text() == '贴现费用') {
            $(".tiexian").show();
            $(".huokuan").hide();
            $(".zijin").hide();
            let num = Number($('.totalAmount2').text().split(',').join(''))
            $('[name=openAmount]').val(commaDelimiter(num))
            //$('.goodsListTable2').empty();
        } else if ($('[name=amountKind] option:selected').text() == '资金占用费') {
            $(".zijin").show();
            $(".huokuan").hide();
            $(".tiexian").hide();
            let num = Number($('.totalAmount3').text().split(',').join(''))
            $('[name=openAmount]').val(commaDelimiter(num))
            //$('.supplierListTable').empty();
        } else {
            $('[name=openAmount]').val('')
            $(".huokuan").hide();
            $(".tiexian").hide();
            $(".zijin").hide();
        }
    })
    $('[name=amountKind]').change()

    $("[name=possessionCostType]").on('change', function (e) {
        if($('[name=possessionCostType] option:selected').val() === '1') {
            $('.possessionCostHide').show()
            $('.possessionCostHideInput').show()
            $('[name=possessionCostType]').parent().attr('width', '35%')
            let num = Number($('.totalAmount').text().split(',').join('')) + Number($('.possessionCost').val().split(',').join(''))
            $('[name=openAmount]').val(commaDelimiter(num))
        }else {
            $('.possessionCostHide').hide()
            $('.possessionCostHideInput').hide()
            $('[name=possessionCostType]').parent().attr('width', '85%')
            let num = Number($('.totalAmount').text().split(',').join(''))
            $('[name=openAmount]').val(commaDelimiter(num))
        }
    })
    $('[name=possessionCostType]').change()


    function invoiceGoodsInfos(cellValue, options, rowObject) {
        return JSON.stringify(rowObject)
    }

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

    function checkBoxDisabled2() {
        $('.goodsListTbody2').each(function ( i, ele) {
            if($(ele).attr('id')){
                setTimeout(() => {
                    var nameVal = `jqg_chooseGoodsList2_${$(ele).attr('id')}`
                    $(`[name=${nameVal}]`).attr('checked', true)
                    $(`[name=${nameVal}]`).attr('disabled',true)
                }, 300);
            }
        })
    }


    function tablefunction(tableid) {
        var tipword = '', pageid = '', pageNo = 1, postData = {};
        url = '', colNamesArray = [], colModelArray = [];
        switch (tableid) {
            case '#chooseGoodsList':
                tipword = '货物';
                pageid = '#chooseGoodsListPage';
                postData = {
                    'businessNumber': $("[name=businessNo]").val()
                };
                url = '/saleInvoice/saleSelectGoodsOfPayment';
                colNamesArray = ['ID', '编号', '结算单号', '供应商', '结算日期', '货物信息'];
                colModelArray = [
                    {name: 'id', label: 'ID', hidedlg:true, hidden:true,sortable:false,title:false},
                    {name: 'orderNumber', label: '编号', hidedlg:true, width:55,sortable:false,title:false},
                    {name: 'settlementNumber', label: '结算单号', sortable:false, align:'left', title:false},
                    {name: 'supplier.enterpriseName', label: '供应商', sortable:false, align:'left', title:false},
                    {name: 'settlementDate', label: '结算日期',sortable:false, align:'left', title:false},
                    {name: 'invoiceGoodsInfos', label: '货物信息', hidedlg: true, hidden: true, sortable:false, align:'left', title:false, formatter: invoiceGoodsInfos},
                    // {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')
            },
            onSelectAll: function(aRowids,status) {
                checkBoxDisabled()
            },
            onPaging:function(pgButton){
                checkBoxDisabled()
            },
            rownumbers: false,
            postData: postData,
            page: pageNo,
            loadError: function () {
                // new $.zui.Messager(tipword + '列表加载失败', {
                //     type: 'warning'
                // }).show();
            }
        }, true);
        $(tableid).trigger('reloadGrid');
        checkBoxDisabled()

    };
    function tablefunction2(tableid) {
        var tipword = '', pageid = '', pageNo = 1, postData = {};
        url = '', colNamesArray = [], colModelArray = [];
        switch (tableid) {
            case '#chooseGoodsList2':
                tipword = '货物';
                pageid = '#chooseGoodsListPage2';
                postData = {
                    // 'beginTime':invoiceQuery.startDate,
                    // 'endTime':invoiceQuery.endDate,
                    // 'status':invoiceQuery.status,
                    'businessNumber': $("[name=businessNo]").val()
                };
                url = '/saleInvoice/saleSelectGoodsOfDiscount';
                colNamesArray = ['ID', '编号', '名称', '型号', '单位', '结算基本信息ID'];
                colModelArray = [
                    {name: 'id', label: 'ID', hidedlg:true, hidden:true,sortable:false,title:false},
                    {name: 'orderNumber', label: '编号', hidedlg:true, width:55,sortable:false,title:false},
                    {name: 'goodsName', 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: 'settlementBasicInfoId', label: '结算基本信息ID', hidedlg:true, hidden:true,sortable:false, align:'left', 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,
            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) {
                checkBoxDisabled2()
            },
            onPaging:function(pgButton){
                checkBoxDisabled2()
            },
            rownumbers: false,
            postData: postData,
            page: pageNo,
            loadError: function () {
                // new $.zui.Messager(tipword + '列表加载失败', {
                //     type: 'warning'
                // }).show();
            }
        }, true);
        $(tableid).trigger('reloadGrid');
        checkBoxDisabled2()
    };

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

    var goodsFlag = '';

    //货物
    $("#chooseButton").click(function () {
        goodsFlag = 'goods';
        $('#chooseGoodsList').setGridParam({
            mtype: 'GET',
            url: '/saleInvoice/saleSelectGoodsOfPayment',
            datatype: 'json',
            postData: {
                // 'beginTime':invoiceQuery.startDate,
                // 'endTime':invoiceQuery.endDate,
                // 'status':invoiceQuery.status,
                'businessNumber': $("[name=businessNo]").val()
            },
            page: 1,
            onPaging:function(pgButton){
                checkBoxDisabled()
            },
        });
        $('#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;

    });
    $('#myModal-chooseGoods').click(function () {
        checkBoxDisabled()
    })

    //贴现费用
    $("#chooseButton2").click(function () {
        goodsFlag = 'amount';

        $('#chooseGoodsList2').setGridParam({
            mtype: 'GET',
            url: '/saleInvoice/saleSelectGoodsOfDiscount',
            datatype: 'json',
            postData: {
                // 'beginTime':settleQuery.startDate,
                // 'endTime':settleQuery.endDate,
                // 'status':settleQuery.status,
                'businessNumber': $("[name=businessNo]").val()
            },
            page: 1,
            onPaging:function(pgButton){
                checkBoxDisabled2()
            },
        });
        $('#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();
        })
        checkBoxDisabled2()
        return false;

    });
    $('#myModal-chooseGoods2').click(function () {
        checkBoxDisabled2()
    })

    //添加供应商
    $("#addSupplier").click(function () {
        var supplierTrClone3 = $(".supplierListTbody:first").clone();
        supplierTrClone3.find('.negativeInformationReduce').show();
        supplierTrClone3.find('.error').hide();
        supplierTrClone3.find('input').val('');
        supplierTrClone3.find('select').val('');
        supplierTrClone3.show();
        $('.supplierListTable').append(supplierTrClone3);
        sortIGoodsnfo3();
    });



    // 删除行
    $("#entryForm").on('click', '.supplierTable .negativeInformationReduce', function () {
        $(this).parents('.supplierListTbody').remove();
        sortIGoodsnfo3();
    });

    function calcMoneyEmpty(money) {
        return money == null ? '' : money
    }
    $(".chooseSure").click(function () {
        var ids = $('#chooseGoodsList').jqGrid('getGridParam', 'selarrrow');
        $('.goodsListTbody').each(function ( i, ele) {
            if($(ele).attr('id')){
                ids =  ids.filter(item => item !== $(ele).attr('id'))
            }
        })
        if (ids.length > 0) {
            for (var i = 0; i < ids.length; i++) {
                var chooseData = $('#chooseGoodsList').jqGrid('getRowData', ids[i]);
                var dataInfo = JSON.parse(chooseData.invoiceGoodsInfos)
                var  chooseDataGoodsInfo = dataInfo.invoiceGoodsInfos
                for (let j = 0; j < chooseDataGoodsInfo.length; j++) {
                    var trStr = `<tr class="choosedGoodsTbody">
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;" trValue=${i} id=${ids[i]}></td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;" rowspanValue=${j == 0 ? chooseDataGoodsInfo.length : '' }>` + chooseData.acceptanceDate + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseDataGoodsInfo[j].goodsName + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` +  chooseDataGoodsInfo[j].goodsType + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` +  chooseDataGoodsInfo[j].goodsUnit + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` +  (Number(chooseDataGoodsInfo[j].goodsQuantity)).toFixed(4) + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + ( chooseDataGoodsInfo[j].salesPrice !== null ? commaDelimiter((Number(chooseDataGoodsInfo[j].salesPrice)).toFixed(2)) : '') + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + calcMoney((Number(chooseDataGoodsInfo[j].salesTotalPrice)).toFixed(2)) + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + calcMoney((Number(chooseDataGoodsInfo[j].usedNum)).toFixed(4)) + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + (Number(chooseDataGoodsInfo[j].openQuantity)).toFixed(4) + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + calcMoneyEmpty((Number(chooseDataGoodsInfo[j].openAmount)).toFixed(2)) + `</td>
                        <td style="display: none">` +  chooseDataGoodsInfo[j].settlementGoodsInfoId + `</td>
                        <td style="display: none">`+chooseDataGoodsInfo[j].settlementBasicInfoId+`</td>
                        <td style="display: none">`+chooseDataGoodsInfo[j].goodsFactory+`</td>
                        <td style="display: none">`+chooseDataGoodsInfo[j].settlementNumber+`</td>
                        <td 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.css('display', '')
                supplierTrClone.find('.error').hide();
                supplierTrClone.find('input').val('');
                supplierTrClone.find('select').val('');
                supplierTrClone.find('td').eq(1).attr('id',$(ele).find('td').eq(11).text())
                supplierTrClone.find('td').eq(1).attr('settlementBasicInfoId', $(ele).find('td').eq(12).text())
                supplierTrClone.find('td').eq(1).attr('goodsFactory', $(ele).find('td').eq(13).text())
                supplierTrClone.find('td').eq(1).text($(ele).find('td').eq(14).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(commaDelimiter($(ele).find('td').eq(7).text()))
                supplierTrClone.find('td').eq(8).text(commaDelimiter($(ele).find('td').eq(8).text()))
                let openNum = Number($(ele).find('td').eq(5).text().split(',').join('')) - Number($(ele).find('td').eq(8).text().split(',').join(''))
                let openNumMoney = openNum * Number($(ele).find('td').eq(6).text().split(',').join(''))
                supplierTrClone.find('td').eq(9).find('input').val(openNum.toFixed(4)) //$(ele).find('td').eq(9).text()
                supplierTrClone.find('td').eq(10).find('input').val(commaDelimiter(openNumMoney.toFixed(2)))  // $(ele).find('td').eq(10).text()
                supplierTrClone.find('td').eq(11).find('input').val($(ele).find('td').eq(11).text())
                // 合并删除
                if( $(ele).find('td').eq(1).attr('rowspanValue')) {
                    supplierTrClone.find('td').eq(11).attr('rowspan', $(ele).find('td').eq(1).attr('rowspanValue'))
                }else {
                    supplierTrClone.find('td').eq(11).remove()
                }

                supplierTrClone.attr('trValue', $(ele).find('td').eq(0).attr('trValue'))
                supplierTrClone.attr('id', $(ele).find('td').eq(0).attr('id'))
                $('.goodsListTable').append(supplierTrClone);
                sortIGoodsnfo();
             }

        })
        $("#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  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;" id=${ids[i]}></td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.acceptanceDate + `</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.goodsType + `</td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.goodsUnit + `</td>
                        <td style="display: none">` + chooseData.settlementBasicInfoId + `</td>
                        <td style="display: none">` + chooseData.id + `</td>
                        <td 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>`
                $(".choosedGoodsList2").append(trStr);
            }
        }
        $(".choosedGoodsTbody2").each(function (i, ele) {
            var supplierTrClone = $(".goodsListTbody2:first").clone();
            supplierTrClone.find('.negativeInformationReduce').show();
            supplierTrClone.css('display', '')
            supplierTrClone.find('.error').hide();
            supplierTrClone.find('input').val('');
            supplierTrClone.find('select').val('');
            supplierTrClone.find('td').eq(1).text($(ele).find('td').eq(2).text())
            supplierTrClone.find('td').eq(2).text($(ele).find('td').eq(3).text())
            supplierTrClone.find('td').eq(3).text($(ele).find('td').eq(4).text())
            supplierTrClone.find('td').eq(1).attr('settlementBasicInfoId', $(ele).find('td').eq(5).text())
            supplierTrClone.find('td').eq(1).attr('id', $(ele).find('td').eq(6).text())
            supplierTrClone.attr('id', $(ele).find('td').eq(0).attr('id'))
            $('.goodsListTable2').append(supplierTrClone);
            sortIGoodsnfo2();
        })
        $("#myModal-chooseGoods2").modal("hide");
    })

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

        //如果有开票数量
        var openNum = $(this).parent().parent().find('td').eq(8).find('input').val().split(',').join('')
        if (openNum) {
            var totalAmount = Math.round((oneSale * openNum) * 100) / 100;
            $(this).parent().siblings().find('.openAmount').val(commaDelimiter((totalAmount).toFixed(4)));
            sortIGoodsnfo();
        }
    })

    //数量输入
    $('.goodsTable').on('keyup', '.openQuantity', function () {
        console.log($(this).val().split(',').join(''))
        var num = Number($(this).val().split(',').join(''))
        var oneSale = Number($(this).parent().parent().find('td').eq(6).text().split(',').join(''));
        if (oneSale) {
            var totalSale = Math.round((oneSale * num) * 100) / 100;
            $(this).parent().siblings().find('.openAmount').val(commaDelimiter((totalSale).toFixed(4)));
            sortIGoodsnfo();
        }

    })

    //贴现 发票输入
    $('.goodsTable2').on('keyup', '.openAmount', function () {
        sortIGoodsnfo2();
    })

    //供应商 发票输入
    $('.supplierTable').on('keyup', '.openAmount', function () {
        sortIGoodsnfo3();
    })


})

let businessNameDataList = []
//获取业务名称
$("[name=enterpriseName]").on('change', function(e) {
    if(!$("[name=enterpriseName]").val()) {
        return
    }
    $("[name=businessName]").val('')
    $("[name=businessName]").children().remove()
    $("[name=businessNo]").val('')
    $("[name=tradingPlatformId]").val('')
    $("[name=platformName]").val('')
    var postdata = new FormData();
    // postdata.append('supplierId', $("[name=supplierName]").val())
    postdata.append('customerId', $("[name=enterpriseName]").val())
    $.ajax({
        url: '/business/management/getBusinessListByCustomerInvoice',
        type: 'post',
        data: postdata,
        processData: false,
        contentType: false,
        success: function(data){
            $('.allBusinessName').empty();
            var businessNameStr = ''
            businessNameDataList = data.data
            var list = data.data
            for (var i = 0; i < list.length; i++) {
                $('.allBusinessName').append('<li class="companyli" value="' + list[i].id + '" businessNameId="' + list[i].businessNumber + '" >' + list[i].businessName + '</li>')
            }
            ;
            i = null;
            withSearchDropDownBox({
                allOptionSelector: '.allBusinessName li',//所有的选项的选择器
                triggerSelector: '#businessName',//触发选择(显示下拉框)的表单的选择器(存放选择的name)
                resultIdSelector: '#businessNameId',//表单元素选择器(存放选择的id)
                dropdownSelector: '.busListBox',//下拉框的选择器
                searchBtn:'.searchBus',
                isCallback: true,
                callback: function () {
                    setTimeout(() => {
                        $('[name=businessName]').change()
                    },100)
                }
            });
            
            // for (var i = 0; i < list.length; i++) {
            //     businessNameStr += `<option value ="${list[i].businessName}" businessNameId="${list[i].id}">${list[i].businessName}</option>`
            // }
            // $("[name=businessName]").append(businessNameStr)
        },       
        error: function(status){
            console.log(status, '获取业务名称失败')
        }
    });
})

// 获取业务编号/贸易平台
$("[name=businessName]").on('change', function(e) {
    if($('#businessNameId').val()){
       const businessNameSelectData =  businessNameDataList.find(item => item.id == $('#businessNameId').val() )
        $("[name=businessNo]").val(businessNameSelectData.businessNumber)
        $("[name=platformName]").val(businessNameSelectData.tradingPlatformName)
        $("[name=tradingPlatformId]").val(businessNameSelectData.tradingPlatformId)
    }else {
        $("[name=businessNo]").val('')
        $("[name=platformName]").val('')
        $("[name=tradingPlatformId]").val('')
    }
})

// 获取业务编号
$("[name=businessName]").on('change', function(e) {
    $('[name=companyName]').val($('[name=enterpriseName] option:checked').text())
    if(!$("[name=enterpriseName]").val()) {
        return
    }
    // $("[name=businessNo]").val('')
    // $("[name=businessNo]").children().remove()
    $("[name=platform]").val('')
    var postdata = new FormData();
    postdata.append('customerId', $("[name=enterpriseName]").val())
    // $.ajax({
    //     url: '/business/management/getBusinessListByCustomerInvoice',
    //     type: 'post',
    //     data: postdata,
    //     processData: false,
    //     contentType: false,
    //     success: function(data){
    //         var str = ''
    //         var list = data.data
    //         for (var i = 0; i < list.length; i++) {
    //             str += `<option value ="${list[i].businessNumber}">${list[i].businessNumber}</option>`
    //         }
    //         $("[name=businessNo]").append(str)
    //     },
    //     error: function(status){
    //         console.log(status, '获取核心企业名称失败')
    //     }
    // });
    $.ajax({
        url: `/saleInvoice/findCustomer?customerId=${$("[name=enterpriseName]").val()}&businessBasicInfoId=${$("#businessNameId").val()}`,
        type: 'GET',
        processData: false,
        contentType: false,
        success: function(data){
            $('[name=taxIdentifyNumber]').val(data.data.socialCreditCode)
            $('[name=address]').val(data.data.address)
            $('[name=phone]').val(data.data.phoneNumber)
            $('[name=accountBankName]').val(data.data.accountBankName)
            $('[name=accountNumber]').val(data.data.accountNumber)
            $('[name=remark]').val(data.data.remark)
        },
        error: function(status){
            console.log(status, '获取核心企业名称失败')
        }
    });
})

// 获取贸易平台
$("[name=businessName]").on('change', function(e) {
    if(!$("[name=businessName]").val()) {
        return
    }
    getSupplier()
    $("[name=platformName]").val('')
    $("[name=tradingPlatformId]").val('')
    var postdata = new FormData();
    postdata.append('businessNumber', $("[name=businessNo]").val())
    $.ajax({
        url: '/platform/getPlateformByBusiness',
        type: 'post',
        data: postdata,
        processData: false,
        contentType: false,
        success: function(data){
            $("[name=platformName]").val(data.data.platformName)
            $("[name=tradingPlatformId]").val(data.data.id)
        },
        error: function(status){
            console.log(status, '获取核心企业名称失败')
        }
    });
})
