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.purchasePrice ? commaDelimiter(chooseData.purchasePrice) : '') + `</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 () {
    //初始化日期
    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 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('.invoiceFileOld', '.invoiceFile .addFileList');
    showOriginalFile('.goodsFileOld', '.goodsFile .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 totalPrice = 0;
        $(".goodsListTbody").each(function (i, ele) {
            $(ele).find('td:first span').text(i);
            totalPrice += 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))
        } else {
            $('.totalAmount').text('0.00')
        }


    };
    sortIGoodsnfo();

    // 删除行-货物
    $("#entryForm").on('click', '.goodsTable .negativeInformationReduce', function () {
        $(this).parents('.goodsListTbody').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))
        } else {
            $('.totalAmount2').text('0.00')
        }
    };
    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))
        } else {
            $('.totalAmount3').text('0.00')
        }
    };
    sortIGoodsnfo3();
    // 删除行-贴现
    $("#entryForm").on('click', '.supplierTable .negativeInformationReduce', function () {
        $(this).parents('.supplierListTbody').remove();
        sortIGoodsnfo3();
    });


    //保存
    function submitFunction(e) {
        var postdata = new FormData();



        if ($('[name=amountKind] option:selected').text() == '货款') {
            //货物信息
            for (var i = 1; i < $(".goodsListTbody").length; i++) {
                postdata.append('purchInvoiceGoodsList[' + (i - 1) + '].acceptanceBusinessGoodsId', $(".goodsListTbody").eq(i).find('td').eq(1).attr('acceptanceBusinessGoodsId'));
                postdata.append('purchInvoiceGoodsList[' + (i - 1) + '].goodsName', $(".goodsListTbody").eq(i).find('td').eq(1).text());
                postdata.append('purchInvoiceGoodsList[' + (i - 1) + '].modelNumber', $(".goodsListTbody").eq(i).find('td').eq(2).text());
                postdata.append('purchInvoiceGoodsList[' + (i - 1) + '].units', $(".goodsListTbody").eq(i).find('td').eq(3).text());
                postdata.append('purchInvoiceGoodsList[' + (i - 1) + '].quantity', $(".goodsListTbody").eq(i).find('td').eq(4).text().split(',').join(''));
                postdata.append('purchInvoiceGoodsList[' + (i - 1) + '].unitPrice', $(".goodsListTbody").eq(i).find('td').eq(5).find('input').val().split(',').join(''));
                postdata.append('purchInvoiceGoodsList[' + (i - 1) + '].totalPrice', $(".goodsListTbody").eq(i).find('td').eq(6).find('input').val().split(',').join(''));
                postdata.append('purchInvoiceGoodsList[' + (i - 1) + '].invoicedQuantity', $(".goodsListTbody").eq(i).find('td').eq(7).find('input').val().split(',').join(''));
                postdata.append('purchInvoiceGoodsList[' + (i - 1) + '].openQuantity', $(".goodsListTbody").eq(i).find('td').eq(8).find('input').val().split(',').join(''));
                postdata.append('purchInvoiceGoodsList[' + (i - 1) + '].openAmount', $(".goodsListTbody").eq(i).find('td').eq(9).find('input').val().split(',').join(''));
            }
            i = null;
        } else if ($('[name=amountKind] option:selected').text() == '贴现费用') {
            //货物信息
            for (var i = 1; i < $(".goodsListTbody2").length; i++) {
                postdata.append('purchInvoiceGoodsList[' + (i - 1) + '].acceptanceBusinessGoodsId', $(".goodsListTbody2").eq(i).find('td').eq(1).attr('acceptanceBusinessGoodsId'));
                postdata.append('purchInvoiceGoodsList[' + (i - 1) + '].goodsName', $(".goodsListTbody2").eq(i).find('td').eq(1).text());
                postdata.append('purchInvoiceGoodsList[' + (i - 1) + '].modelNumber', $(".goodsListTbody2").eq(i).find('td').eq(2).text());
                postdata.append('purchInvoiceGoodsList[' + (i - 1) + '].units', $(".goodsListTbody2").eq(i).find('td').eq(3).text());
                postdata.append('purchInvoiceGoodsList[' + (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('purchInvoiceGoodsList[' + (i - 1) + '].supplierId', $(".supplierListTbody").eq(i).find('td').eq(1).find('select').val());
                postdata.append('purchInvoiceGoodsList[' + (i - 1) + '].openAmount', $(".supplierListTbody").eq(i).find('td').eq(2).find('input').val().split(',').join(''));
            }
            i = null;
        }

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

        postdata.append('purchInvoiceInfo.businessNumber', $("[name=businessNumber]").val());
        postdata.append('purchInvoiceInfo.invoiceDate', $("[name=invoiceDate]").val());
        //postdata.append('purchaserId',$("[name=purchaserId]").val());
        //postdata.append('mortgageNumber',$("[name=mortgageNumber]").val());
        postdata.append('purchInvoiceInfo.invoiceNumber', $("[name=invoiceNumber]").val());
        postdata.append('purchInvoiceInfo.supplierId', $("[name=supplierId]").val());
        postdata.append('purchInvoiceInfo.invoiceAmount', $("[name=invoiceAmount]").val().split(',').join(''));
        postdata.append('purchInvoiceInfo.invoiceType', $("[name=invoiceType]").val());
        postdata.append('purchInvoiceInfo.amountKind', $("[name=amountKind]").val());

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

        for(var m=0; m<deleteFileIdArr.length; m++) {
            postdata.append('deleteFile['+m+']',deleteFileIdArr[m]);
        }
        m = null;

        var url = '/purchInvoice/doUpdate', 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('/invoiceManage/pendingPurchList', 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 = {
        'invoiceDate': {
            required: true
        },
        'invoiceAmount': {
            required: true
        },
        'invoiceNumber': {
            required: true
        },
        'supplierId': {
            required: true,
        },
        'invoiceType': {
            required: true,
        },
        'amountKind': {
            required: true,
        },

    };

    var formMessages = {
        'invoiceDate': {
            required: '请选择发票日期',
        },
        'invoiceAmount': {
            required: '请输入发票金额'
        },
        'invoiceNumber': {
            required: '请输入发票单号'
        },
        'supplierId': {
            required: '请选择供应商'
        },
        'invoiceType': {
            required: '请选择发票类型'
        },
        'amountKind': {
            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(Number($('[name=invoiceAmount]').val().split(',').join('')) !== Number($('.totalAmount').text().split(',').join(''))) {
                        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;
                    }
                    //开票总额=发票金额
                    if(Number($('[name=invoiceAmount]').val().split(',').join('')) !== Number($('.totalAmount2').text().split(',').join(''))) {
                        new $.zui.Messager('发票金额不等于开票总金额。', {
                            type: 'danger'
                        }).show();
                        return false;
                    }
                } else if ($('[name=amountKind] option:selected').text() == '资金占用费') {
                    if ($(".supplierListTable .supplierListTbody").length) {
                        $('.supplierListTable .validInput').keyup();
                    } else {
                        new $.zui.Messager('请选择供应商。', {
                            type: 'danger'
                        }).show();
                        return false;
                    }
                    //开票总额=发票金额
                    if(Number($('[name=invoiceAmount]').val().split(',').join('')) !== Number($('.totalAmount3').text().split(',').join(''))) {
                        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("change",".validInput",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('/invoiceManage/pendingPurchList', 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 ''
        }
    }

    function tablefunction(tableid) {
        var tipword = '', pageid = '', pageNo = 1, postData = {};
        url = '', colNamesArray = [], colModelArray = [];
        switch (tableid) {
            case '#chooseGoodsList':
                tipword = '货物';
                pageid = '#chooseGoodsListPage';
                postData = {
                    // 'beginTime':invoiceQuery.startDate,
                    // 'endTime':invoiceQuery.endDate,
                    // 'status':invoiceQuery.status,
                    'businessNumber': invoiceQuery.detailId
                };
                url = '/purchInvoice/purchSelectGoodsOfPayment';
                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: 'acceptanceDate', label: '验收日期', sortable: false, align: 'left', title: false},
                    {
                        name: 'acceptanceBusinessGoodsId',
                        label: '货物Id',
                        hidedlg: true,
                        hidden: true,
                        sortable: false,
                        align: 'left',
                        title: false
                    },
                    {
                        name: 'invoicedQuantity',
                        label: '已开票数',
                        hidedlg: true,
                        hidden: true,
                        sortable: false,
                        align: 'left',
                        title: false
                    },
                    {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: 'purchasePrice',
                        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':invoiceQuery.startDate,
                    // 'endTime':invoiceQuery.endDate,
                    // 'status':invoiceQuery.status,
                    'businessNumber': invoiceQuery.detailId
                };
                url = '/purchInvoice/purchSelectGoodsOfDiscount';
                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: 'acceptanceDate', label: '验收日期', sortable: false, align: 'left', title: false},
                    {
                        name: 'acceptanceBusinessGoodsId',
                        label: '货物Id',
                        hidedlg: true,
                        hidden: true,
                        sortable: false,
                        align: 'left',
                        title: false
                    },
                    {
                        name: 'invoicedQuantity',
                        label: '已开票数',
                        hidedlg: true,
                        hidden: true,
                        sortable: false,
                        align: 'left',
                        title: false
                    },
                    {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: 'purchasePrice',
                        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');
    };

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

    //金额种类选择
    $('[name=amountKind]').change(function () {
        if ($('[name=amountKind] option:selected').text() == '货款') {
            $(".huokuan").show();
            $(".tiexian").hide();
            $(".zijin").hide();
        } else if ($('[name=amountKind] option:selected').text() == '贴现费用') {
            $(".tiexian").show();
            $(".huokuan").hide();
            $(".zijin").hide();
        } else if ($('[name=amountKind] option:selected').text() == '资金占用费') {
            $(".zijin").show();
            $(".huokuan").hide();
            $(".tiexian").hide();
        } else {
            $(".huokuan").hide();
            $(".tiexian").hide();
            $(".zijin").hide();
        }
    })
    $('[name=amountKind]').change()


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

        goodsFlag = 'goods';
        $('#chooseGoodsList').setGridParam({
            mtype: 'GET',
            url: '/purchInvoice/purchSelectGoodsOfPayment',
            datatype: 'json',
            postData: {
                // 'beginTime':invoiceQuery.startDate,
                // 'endTime':invoiceQuery.endDate,
                // 'status':invoiceQuery.status,
                'businessNumber': invoiceQuery.detailId
            },
            page: 1
        });
        $('#chooseGoodsList').trigger('reloadGrid');
        $("#myModal-chooseGoods").modal("show");
        $("#myModal-chooseGoods").on('shown.zui.modal', function () {
            $(".modal-dialog").css({'margin-top': '58px'})
            $(window).resize();
            $("#chooseGoodsList_cb").css({'width': '45', 'padding': '0 0.12rem'})
            $('#chooseGoodsList .jqgfirstrow td:first').css('width', '45')

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

    });

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

        $('#chooseGoodsList2').setGridParam({
            mtype: 'GET',
            url: '/purchInvoice/purchSelectGoodsOfDiscount',
            datatype: 'json',
            postData: {
                // 'beginTime':settleQuery.startDate,
                // 'endTime':settleQuery.endDate,
                // 'status':settleQuery.status,
                'businessNumber': invoiceQuery.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;

    });

    //添加供应商
    $("#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();
    });

    $(".chooseSure").click(function () {
        var ids = $('#chooseGoodsList').jqGrid('getGridParam', 'selarrrow');
        if (ids.length > 0) {
            for (var i = 0; i < ids.length; i++) {
                var chooseData = $('#chooseGoodsList').jqGrid('getRowData', ids[i]);
                var trStr = `<tr class="choosedGoodsTbody">
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;"></td>
                        <td  style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.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.purchasePrice ? commaDelimiter(chooseData.purchasePrice) : '') + `</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);
            }
        }

        var postdata1 = new FormData();
        postdata1.append('businessNumber', $("[name=businessNumber]").val());
        $(".choosedGoodsTbody").each(function (i, ele) {

            //货物信息
            postdata1.append('selectGoodsList[' + (i) + '].acceptanceBusinessGoodsId', $(ele).find('td').eq(8).text());
            postdata1.append('selectGoodsList[' + (i) + '].goodsName', $(ele).find('td').eq(2).text());
            postdata1.append('selectGoodsList[' + (i) + '].goodsType', $(ele).find('td').eq(4).text());
            postdata1.append('selectGoodsList[' + (i) + '].goodsUnit', $(ele).find('td').eq(5).text());
            postdata1.append('selectGoodsList[' + (i) + '].goodsNum', $(ele).find('td').eq(6).text());
            postdata1.append('selectGoodsList[' + (i) + '].purchasePrice', $(ele).find('td').eq(7).text().split(',').join(''));

        })
        $.ajax({
            url: '/purchInvoice/determine',
            type: 'post',
            data: postdata1,
            processData: false,
            contentType: false,
            success: function (data) {
                if (data.success) {
                    data.data.forEach(function (ele, i) {
                        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.goodsName)
                            supplierTrClone.find('td').eq(2).text(ele.modelNumber)
                            supplierTrClone.find('td').eq(3).text(ele.units)
                            supplierTrClone.find('td').eq(4).text(ele.quantity)
                            supplierTrClone.find('td').eq(5).find('input').val(commaDelimiter(ele.unitPrice))//单价
                            supplierTrClone.find('td').eq(1).attr('acceptanceBusinessGoodsId', ele.acceptanceBusinessGoodsId)
                            supplierTrClone.find('td').eq(7).find('input').val(ele.invoicedQuantity)

                            //如果有采购单价
                            if (ele.unitPrice) {
                                var onePurch = Number(ele.unitPrice)
                                var num = Number(ele.quantity);
                                var totalPurch = Math.round((onePurch * num) * 100) / 100;
                                supplierTrClone.find('td').eq(6).find('input').val(commaDelimiter(totalPurch))

                            } else {
                                supplierTrClone.find('td').eq(6).find('input').val(0.00)
                            }

                            supplierTrClone.show();

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

                            sortIGoodsnfo();
                        } else {
                            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.goodsName)
                            supplierTrClone2.find('td').eq(2).text(ele.modelNumber)
                            supplierTrClone2.find('td').eq(3).text(ele.units)
                            supplierTrClone2.find('td').eq(1).attr('acceptanceBusinessGoodsId', ele.acceptanceBusinessGoodsId)
                            supplierTrClone2.show();

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

                            sortIGoodsnfo2();
                        }
                    })

                } else {

                }
            },
            error: function (status) {

            }
        });

        $("#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;"></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.purchasePrice ? commaDelimiter(chooseData.purchasePrice) : '') + `</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>`
                $(".choosedGoodsList2").append(trStr);
            }
        }

        var postdata1 = new FormData();
        postdata1.append('businessNumber', $("[name=businessNumber]").val());
        $(".choosedGoodsTbody2").each(function (i, ele) {

            //货物信息
            postdata1.append('selectGoodsList[' + (i) + '].acceptanceBusinessGoodsId', $(ele).find('td').eq(8).text());
            postdata1.append('selectGoodsList[' + (i) + '].goodsName', $(ele).find('td').eq(2).text());
            postdata1.append('selectGoodsList[' + (i) + '].goodsType', $(ele).find('td').eq(4).text());
            postdata1.append('selectGoodsList[' + (i) + '].goodsUnit', $(ele).find('td').eq(5).text());
            postdata1.append('selectGoodsList[' + (i) + '].goodsNum', $(ele).find('td').eq(6).text());
            postdata1.append('selectGoodsList[' + (i) + '].purchasePrice', $(ele).find('td').eq(7).text().split(',').join(''));

        })
        $.ajax({
            url: '/purchInvoice/determine',
            type: 'post',
            data: postdata1,
            processData: false,
            contentType: false,
            success: function (data) {
                if (data.success) {
                    data.data.forEach(function (ele, i) {
                        if (goodsFlag == 'goods') {

                        } else {
                            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.goodsName)
                            supplierTrClone2.find('td').eq(2).text(ele.modelNumber)
                            supplierTrClone2.find('td').eq(3).text(ele.units)
                            supplierTrClone2.find('td').eq(1).attr('acceptanceBusinessGoodsId', ele.acceptanceBusinessGoodsId)
                            supplierTrClone2.show();

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

                            sortIGoodsnfo2();
                        }
                    })

                } else {

                }
            },
            error: function (status) {

            }
        });

        $("#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());
        var totalSale = Math.round((oneSale * num) * 100) / 100;
        $(this).parent().siblings().find('.totalPrice').val(commaDelimiter(totalSale));

        //如果有开票数量
        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));
            sortIGoodsnfo();
        }
    })

    //数量输入
    $('.goodsTable').on('keyup', '.openQuantity', function () {
        var num = Number($(this).val().split(',').join(''))
        var oneSale = Number($(this).parent().parent().find('td').eq(5).find('input').val().split(',').join(''));

        if (oneSale) {
            var totalSale = Math.round((oneSale * num) * 100) / 100;
            $(this).parent().siblings().find('.openAmount').val(commaDelimiter(totalSale));
            sortIGoodsnfo();
        }

    })

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

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

})