// 出入账--处理(保理出账)
$(function () {
       // 出账类型为实退金额和资金占用费时，处理页面显示供应商名称和采购合同编号、出账类型为融资利息和融资本金时，处理页面显示贸易平台名称
       const cashTypeCode = $("[name=cashTypeId]").attr('code')
       if(cashTypeCode == 'outType_discount' || cashTypeCode == 'outType_funds_used_cost') {
           $('.isOneHide').show()
           $('.isTwoHide').hide()
       }else if(cashTypeCode == 'outType_factoring_interest' || cashTypeCode == 'outType_factoring_principal'){
           $('.isOneHide').hide()
           $('.isTwoHide').show()
       }else {
           $('.isOneHide').hide()
           $('.isTwoHide').hide()
       }
    $('.submitBusiness').removeClass("loadingCircle");

    function getCompany() {
        $.ajax({
            url: '/cashFlow/getCompanyBelong',
            type: 'get',
            data: {},
            async: false,
            success: function (data) {
                if (data.success) {
                    $("[name=companyBelong]").empty();
                    $("[name=companyBelong]").append('<option value="">请选择</option>')
                    for (var i = 0; i < data.data.length; i++) {
                        $("[name=companyBelong]").append('<option value="' + data.data[i].companyBelong + '">' + data.data[i].companyName + '</option>')
                    }
                    ;
                    i = null;
                } else {
                    new $.zui.Messager('获取选项失败:' + data.msg, {
                        type: 'danger'
                    }).show();
                }
                ;
            },
            error: function (status) {
                new $.zui.Messager('获取选项出错:' + status, {
                    type: 'danger'
                }).show();
            }
        });
    }

    getCompany()

    $('.unifiedEditorClass').each(function (i, ele) {
        var editor = new UE.ui.Editor({
            'fullscreen': false
        });
        editor.render($(ele).attr('id'));
        if ($(ele).parents('.loanRecordList').find('.thisExecutor').attr('thisVisible') == 'true') {
            editor.addListener('ready', function () {
                editor.setDisabled();
            });
        }
        ;
    });

    // 处理银行名称和银行卡号
    function handlerBankAndNUmber () {
        if($('[name=returnBankInfo]').val() == 'true') {
            setTimeout(function () {
                $('.loanBankNameBox2').find('input').val($('[name=supplierBankCardInfoBankName]').val())
                $('.loanBankNameBox2').find('input').attr('readonly', true)
                $('.loanBankNoBox2').find('input').val($('[name=supplierBankCardInfoAccountNumber]').val())
                $('.loanBankNoBox2').find('input').attr('readonly', true)
            }, 500)
        }
    }
    handlerBankAndNUmber()


    // 附件相关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>';

    // 如果一开始没有出账记录数据
    if ($('.loanRecordList').length <= 0) {
        $('.loanRecordListBox').append('<tbody class="loanRecordList"><tr><td width="5%" rowspan="2" style="background:#fff;">1</td>'
            + '<td width="10%" class="enter"><input type="text" class="form-control thisLoanDate" readOnly><span class="error" style="display:none;">请选择此次放款日期</span></td>'
            + '<td width="10%" class="enter"><input type="text" class="form-control thisLoanAmount" value="' + commaDelimiter($("#amountMoney").val()) + '" style="padding-right:0.3rem;">'
            + '<span class="error" style="display:none;">请输入此次放款金额</span><i class="viewDetailWord" crid="' + $('.currencyBigId').attr('crid') + '">' + $(".currencyBigId").val() + '</i></td>'
            + '<td width="10%" class="enter companyOwnershipBox"><select class="form-control companyOwnershipInput"></select><span class="error" style="display:none">请选择公司归属</span></td>'
            + '<td width="11%" class="enter loanBankNameBox"><select class="form-control"></select><span class="error" style="display:none;">请选择银行名称</span></td>'
            + '<td width="13%" class="enter loanBankNoBox"><select class="form-control"></select><span class="error" style="display:none;">请选择银行卡号</span></td>'
            + '<td width="11%" class="enter loanBankNameBox2"><input type="text" class="form-control"><span class="error" style="display:none;">请输入银行名称</span></td>'
            + '<td width="13%" class="enter loanBankNoBox2"><input type="text" class="form-control"><span class="error" style="display:none;">请输入银行卡号</span></td>'
            + '<td width="9%" class="enter"><input type="text" class="form-control nowrite thisExecutor" value="' + $('.currentUserId').val() + '" thisExecutorId="' + $('.currentUserId').attr('cuid') + '" thisVisible="false" readOnly></td>'
            + '<td width="8%" rowspan="2" style="background:#fff;padding-left:0;padding-right:0;"><span class="negativeInformationPlus">+增加</span><span class="negativeInformationReduce">-删除</span></td></tr>'
            + '<tr class="editorBigBox"><td colspan="8" class="enter">'
            + '<textarea id="unifiedEditor0" class="unifiedEditorClass" style="height:230px;width:100%;"></textarea>'
            + '</td></tr></tbody>');
        // 初始化富文本框
        var editor = new UE.ui.Editor({
            'fullscreen': false
        });
        editor.render('unifiedEditor0');

        // '公司归属'填值
        $("#companyOwnership option").each(function (i, ele) {
            $('.companyOwnershipBox select').append('<option code="' + $(ele).attr('code') + '" value="' + $(ele).attr('value') + '">' + $(ele).text() + '</option>')
        });
    }
    ;

    var editorIdNum = $('.unifiedEditorClass').length;//富文本框id标识,递增


    // 初始化日期选择
    function initDate(selector, startDate) {
        $(selector).datetimepicker(
            {
                weekStart: 1,
                autoclose: 1,
                todayHighlight: 0,
                startView: 2,
                minView: 2,
                forceParse: 0,
                showMeridian: 1,
                startDate: startDate,
                endDate: getCurrentDayTime(),
                format: "yyyy-mm-dd"
            }
        );
    };

    // initDate('.thisLoanDate',$('#billDate').val())
    initDate('.thisLoanDate', $('[name=cashDate]').val())

//	$('.loanRecordList').each(function(i,ele){
//		$(ele).data('deletefileid',[]);// 每一组出账记录上记录该组删除的原附件id, 初始为空, 若不是原先已有的出账记录则该值始终为空
//		$(ele).find('.refinanExpendFileList').data('filearray',[]);// 每一组出账记录的附件上记录该组新添加的附件数据, 初始为空
//	});

    //根据选择的公司归属查询银行名称
    function getBankName(selector, companyOwnershipId) {
        var bankdata = [];
        $.ajax({
            url: '/cashFlow/getBankName',
            type: 'get',
            async: false,
            data: {
                'companyBelong': companyOwnershipId
            },
            success: function (data) {
                if (data.success) {
                    bankdata = data.data;
                } else {
                    new $.zui.Messager('查询银行名称失败:' + data.msg, {
                        type: 'danger'
                    }).show();
                }
            },
            error: function (status) {
                new $.zui.Messager('查询银行名称时发生错误:' + status, {
                    type: 'danger'
                }).show();
            }
        });
        $(selector).val('');
        $(selector).empty();
        var banknameOption = "<option value=''>请选择</option>";
        for (var i = 0; i < bankdata.length; i++) {
            banknameOption += "<option value='" + bankdata[i] + "'>" + bankdata[i] + "</option>"
        }
        ;
        i = null;
        $(selector).append(banknameOption);
    };

    //公司归属变化时,要清空重置银行卡号/银行名称/金额单位,重新获取银行名称
    $(".loanRecordListBox").on('change', '.companyOwnershipInput', function () {
        $(this).parents('tbody').find('.loanBankNoBox select').val('');
        $(this).parents('tbody').find('.loanBankNoBox select').empty().append("<option value=''>请选择</option>");
        getBankName($(this).parents('tbody').find('.loanBankNameBox select'), $(this).val());
        //只有一个银行名称时,默认选择该名称
        if ($(this).parents('tbody').find('.loanBankNameBox select option').length == 2) {
            $(this).parents('tbody').find('.loanBankNameBox select').val($(this).parents('tbody').find('.loanBankNameBox select option').eq(1).attr('value'));
            $(this).parents('tbody').find('.loanBankNameBox select').change();
        }
        ;
    });


    //根据所选公司归属和银行名称查询银行卡号
    function getBankCardNo(selectorNo, companyOwnershipId, bankName) {
        var bankNodata = [];
        $.ajax({
            url: '/cashFlow/getBankAccount',
            type: 'get',
            async: false,
            data: {
                'companyBelong': companyOwnershipId,
                'bankName': bankName
            },
            success: function (data) {
                if (data.success) {
                    bankNodata = data.data;
                } else {
                    new $.zui.Messager('查询银行卡号失败:' + data.msg, {
                        type: 'danger'
                    }).show();
                }
            },
            error: function (status) {
                new $.zui.Messager('查询银行卡号时发生错误:' + status, {
                    type: 'danger'
                }).show();
            }
        });
        $(selectorNo).val('');
        $(selectorNo).empty();
        var bankNoOption = "<option value=''>请选择</option>";
        // for( var i=0;i<bankNodata.length;i++ ){
        //     bankNoOption += "<option bankid='"+bankNodata[i].id+"' currency='"+bankNodata[i].currency.id+"' unit='"+bankNodata[i].currency.name+"' value='"+bankNodata[i].bankCardNo+"'>"+bankNodata[i].bankCardNo+"</option>"
        // };
        // i = null;
        for (var i = 0; i < bankNodata.length; i++) {
            bankNoOption += "<option value='" + bankNodata[i] + "' bankid='" + bankNodata[i] + "'>" + bankNodata[i] + "</option>"
        }
        ;
        i = null;
        $(selectorNo).append(bankNoOption);

    };

    //银行名称变化时,要清空重置银行卡号/金额单位,重新获取银行卡号
    $(".loanRecordListBox").on('change', '.loanBankNameBox select', function () {
        getBankCardNo($(this).parents('tbody').find('.loanBankNoBox select'), $(this).parents('tbody').find('.companyOwnershipBox select').val(), $(this).val());
        //只有一个银行卡号时,默认选择该卡号
        if ($(this).parents('tbody').find('.loanBankNoBox select option').length == 2) {
            $(this).parents('tbody').find('.loanBankNoBox select').val($(this).parents('tbody').find('.loanBankNoBox select option').eq(1).attr('value'));
        }
        ;
    });

    // 排序
    function loanRecordSort() {
        if ($('.loanRecordListBox .loanRecordList').length > 1) {
            $('.loanRecordListBox').find('.negativeInformationReduce').show();
        } else {
            $('.loanRecordListBox').find('.negativeInformationReduce').hide();
        }
        ;
        $('.loanRecordListBox .loanRecordList').each(function (i, ele) {
            $(ele).find('tr:first td:first').text(i + 1);
        });
    };
    loanRecordSort();

    // 新增一行
    $(".loanRecordListBox").on('click', '.negativeInformationPlus', function () {
        var loanRecordClone = $(this).parents('tbody').clone();
        loanRecordClone.find('.thisLoanDate').val('');
        loanRecordClone.find('.thisLoanDate').css('color', '#333');
        initDate(loanRecordClone.find('.thisLoanDate'), $('[name=cashDate]').val());
        loanRecordClone.find('.thisLoanAmount').val('');
        loanRecordClone.find('.thisLoanAmount').css('color', '#333');
        loanRecordClone.find('.viewDetailWord').css('color', '#333');
        loanRecordClone.find('input').prop('disabled', false);

        loanRecordClone.find('select').empty();
        loanRecordClone.find('select').val('');

        loanRecordClone.find('.companyOwnershipBox select').show();
        loanRecordClone.find('.companyOwnershipBox div').remove();
        loanRecordClone.find('.companyOwnershipBox').css('color', '#333');
        loanRecordClone.find('.loanBankNameBox,.loanBankNoBox').removeAttr('checkid');
        $("#companyOwnership option").each(function (i, ele) {
            loanRecordClone.find('.companyOwnershipBox select').append('<option code="' + $(ele).attr('code') + '" value="' + $(ele).attr('value') + '">' + $(ele).text() + '</option>')
        });


        loanRecordClone.find('.loanBankNameBox select').show();
        loanRecordClone.find('.loanBankNameBox div').remove();
        loanRecordClone.find('.loanBankNameBox').css('color', '#333');
        loanRecordClone.find('.loanBankNameBox2 input').val('');

        loanRecordClone.find('.loanBankNoBox select').show();
        loanRecordClone.find('.loanBankNoBox div').remove();
        loanRecordClone.find('.loanBankNoBox').css('color', '#333');
        loanRecordClone.find('.loanBankNoBox2 input').val('');

        loanRecordClone.find('.error').removeClass('shows').hide();
        loanRecordClone.find('tr:first').removeAttr('reid');

        loanRecordClone.find('.thisExecutor').attr('thisVisible', 'false');
        loanRecordClone.find('.thisExecutor').attr('thisExecutorId', $('.currentUserId').attr('cuid'));
        loanRecordClone.find('.thisExecutor').val($('.currentUserId').val());

//		loanRecordClone.data('deletefileid',[]);
//		loanRecordClone.find('.refinanExpendFileList').data('filearray',[]);
//		loanRecordClone.find('.fileContent').empty().append('<span class="spanHolder">上传附件</span>')
        loanRecordClone.find('.editorBigBox td').empty().append('<textarea id="unifiedEditor' + editorIdNum + '" class="unifiedEditorClass" style="height:230px;width:100%;"></textarea>')
        editorIdNum++;

        $(this).parents('tbody').after(loanRecordClone);
        var editor = new UE.ui.Editor({
            'fullscreen': false
        });
        editor.render(loanRecordClone.find('.unifiedEditorClass').attr('id'));
        loanRecordSort();
        handlerBankAndNUmber()
    });

    var deleteExpenditureRecordIdList = [];// 删除的出账记录数据的id
    // 删除一行
    $(".loanRecordListBox").on('click', '.negativeInformationReduce', function () {
        if ($(this).parents('tbody').find('.thisExecutor').attr('thisVisible') == 'true') {
            new $.zui.Messager('该条数据已提交,不可删除', {
                type: 'danger'
            }).show();
            return;
        }
        ;
        if ($(this).parents('tbody').find('tr:first').attr('reid') && $(this).parents('tbody').find('tr:first').attr('reid') != '') {
            deleteExpenditureRecordIdList.push($(this).parents('tbody').find('tr:first').attr('reid'))
        }
        ;
        $(this).parents('tbody').remove();
        loanRecordSort();
    });

    // 如果一开始有出账数据
    if ($('.loanRecordList').length > 0) {
        // 金额添加分隔符
        $('.thisLoanAmount').each(function (i, ele) {
            $(ele).val(commaDelimiter($(ele).val()))
        });
        $('.loanRecordList').each(function (n, element) {
            if ($(element).find('.companyOwnershipInput').attr('backValue') !== '' && $(element).find('.companyOwnershipInput').attr('backValue') !== undefined) {
                $("#companyOwnership option").each(function (i, ele) {
                    $(element).find('.companyOwnershipInput').append('<option code="' + $(ele).attr('code') + '" value="' + $(ele).attr('value') + '">' + $(ele).text() + '</option>')
                });
                $(element).find('.companyOwnershipInput').val($(element).find('.companyOwnershipInput').attr('backValue'))
            }
        })

        // 填充公司归属/银行名称/银行卡号
        $('.loanRecordList').each(function (i, ele) {
            if ($(ele).find('.companyOwnershipInput').val() != '') {
                $(ele).find('.companyOwnershipInput').change();
                if ($(ele).find('.loanBankNameBox').attr('checkid')) {
                    $(ele).find('.loanBankNameBox').find('select option').each(function (j, dom) {
                        if ($(dom).attr('value') == $(ele).find('.loanBankNameBox').attr('checkid')) {
                            $(dom).prop('selected', true);
                            $(ele).find('.loanBankNameBox select').change();
                        }
                        ;
                    });
                }
                ;
                if ($(ele).find('.loanBankNoBox').attr('checkid')) {
                    $(ele).find('.loanBankNoBox').find('select option').each(function (j, dom) {
                        if ($(dom).attr('bankid') == $(ele).find('.loanBankNoBox').attr('checkid')) {
                            $(dom).prop('selected', true);
                        }
                        ;
                    });
                }
                ;
            }
            ;
        });
    }
    ;

    // 已提交的出账记录数据不可修改
    $('.loanRecordList').each(function (i, ele) {
        if ($(ele).find('.thisExecutor').attr('thisVisible') == 'true') {
            $(ele).find('.thisLoanDate,.thisLoanAmount,.viewDetailWord').css({
                'color': '#868686',
                'cursor': 'default'
            }).prop('disabled', true);
            $(ele).find('.companyOwnershipBox select').hide();
            $(ele).find('.companyOwnershipBox').css('color', '#868686').append('<div style="padding-left:0.1rem;">' + $(ele).find('.companyOwnershipBox select option:selected').text() + '</div>');
            $(ele).find('.loanBankNameBox select').hide();
            $(ele).find('.loanBankNameBox').css('color', '#868686').append('<div style="padding-left:0.1rem;">' + $(ele).find('.loanBankNameBox select option:selected').text() + '</div>');
            $(ele).find('.loanBankNoBox select').hide();
            $(ele).find('.loanBankNoBox').css('color', '#868686').append('<div style="padding-left:0.1rem;">' + $(ele).find('.loanBankNoBox select option:selected').text() + '</div>');
        }
    });

    // 展示原先有的附件
    function showOriginalFile(source, insert) {
        for (var i = 0; i < $(".loanRecordList").length; i++) {
            for (var j = 0; j < $(".loanRecordList").eq(i).find(source).length; j++) {
                var originalFileWrapper = $(fileWrapperbasic).clone();
                originalFileWrapper.find('.file-name').text($(".loanRecordList").eq(i).find(source).eq(j).find('.originalName').val());
                originalFileWrapper.find('.file-name').attr('originalid', $(".loanRecordList").eq(i).find(source).eq(j).find('.originalId').val());
                if (parseFloat($(".loanRecordList").eq(i).find(source).eq(j).find('.originalSize').val()) < 1048576) {
                    originalFileWrapper.find('.file-size').text(($(".loanRecordList").eq(i).find(source).eq(j).find('.originalSize').val() / 1024).toFixed(2) + "KB");
                } else {
                    originalFileWrapper.find('.file-size').text(($(".loanRecordList").eq(i).find(source).eq(j).find('.originalSize').val() / 1024 / 1024).toFixed(2) + "MB");
                }
                ;
                var originaltype = $(".loanRecordList").eq(i).find(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(' + $(".loanRecordList").eq(i).find(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");
                $(".loanRecordList").eq(i).find(insert).find('.fileContent').append(originalFileWrapper)
            }
            ;
            j = null;
            if ($(".loanRecordList").eq(i).find(insert).find('.file-wrapper').length > 0) {
                $(".loanRecordList").eq(i).find(insert).find('.spanHolder').remove();
            }
            ;
        }
        ;
        i = null;
    };
    // 展示原先附件
    //showOriginalFile('.loanRecordFileListOriginal','.refinanExpendFileList');
    //$('.loanRecordFileListOriginal').remove();

    // 触发选择附件
    $('.loanRecordListBox').on("click", ".choiceFile", function () {
        if ($(this).parents('tbody').find('.thisExecutor').attr('thisVisible') == 'true') {
            new $.zui.Messager('该条数据已提交,不可变更', {
                type: 'danger'
            }).show();
            return;
        }
        ;
        if (!window.FileReader) {
            new $.zui.Messager('您的浏览器版本过低，请升级您的浏览器', {
                type: 'danger'
            }).show();
            return;
        }
        ;
        $(this).parent().find('.fileinput').click();
    });
    $('.loanRecordListBox').on("click", ".fileContent", function () {
        if ($(this).find(".spanHolder").length > 0) {
            if ($(this).parents('tbody').find('.thisExecutor').attr('thisVisible') == 'true') {
                new $.zui.Messager('该条数据已提交,不可变更', {
                    type: 'danger'
                }).show();
                return;
            }
            ;
        }
        ;
        if (!window.FileReader) {
            new $.zui.Messager('您的浏览器版本过低，请升级您的浏览器', {
                type: 'danger'
            }).show();
            return;
        }
        ;
        if ($(this).find(".spanHolder").length > 0) {
            $(this).parent().prev().click();
        }
        ;
    });

    // 选择附件
    $(".loanRecordListBox").on("change", ".fileinput", function (e) {
        var that = $(this);
        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).parents('td').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>')
                }
                ;
            };
        };
    });

    // 删除(添加的)附件
    $(".loanRecordListBox").on("click", ".btn-delete-file", function () {
        if ($(this).parents('tbody').find('.thisExecutor').attr('thisVisible') == 'true') {
            new $.zui.Messager('该条数据已提交,不可变更', {
                type: 'danger'
            }).show();
            return;
        }
        ;
        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;
    });

    // 删除(原有的)附件
    $(".loanRecordListBox").on("click", ".btn-delete-originalfile", function () {
        if ($(this).parents('tbody').find('.thisExecutor').attr('thisVisible') == 'true') {
            new $.zui.Messager('该条数据已提交,不可变更', {
                type: 'danger'
            }).show();
            return;
        }
        ;
        $(this).parents('.loanRecordList').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;
    });

    $('#amountMoney').val(commaDelimiter($('#amountMoney').val()));


    //金额添加逗号分隔符
    $(".loanRecordListBox").on('keyup', '.thisLoanAmount', function () {
        $(this).val(commaDelimiter($(this).val()));
    });

    // 每一行的必填验证
    function loanRecordValid(t, tip, source) {
        if (t == undefined) {
            $('.loanRecordList').each(function (i, ele) {
                // 此次放款日期
                if ($(ele).find('.thisLoanDate').val() == '') {
                    $(ele).find('.thisLoanDate').parents('td').find('.error').addClass('shows').show();
                } else {
                    $(ele).find('.thisLoanDate').parents('td').find('.error').removeClass('shows').hide();
                }
                ;
                // 此次放款金额
                if ($(ele).find('.thisLoanAmount').val() == '') {
                    $(ele).find('.thisLoanAmount').parents('td').find('.error').addClass('shows').text('请输入此次放款金额').show();
                } else {
                    $(ele).find('.thisLoanAmount').parents('td').find('.error').removeClass('shows').hide();
                }
                ;
                // 公司归属
                if ($(ele).find('.companyOwnershipBox select').val() == '' || $(ele).find('.companyOwnershipBox select').val() == undefined) {
                    $(ele).find('.companyOwnershipBox').find('.error').addClass('shows').show();
                } else {
                    $(ele).find('.companyOwnershipBox').find('.error').removeClass('shows').hide();
                }
                // 银行名称
                if ($(ele).find('.loanBankNameBox select').val() == '' || $(ele).find('.loanBankNameBox select').val() == undefined) {
                    $(ele).find('.loanBankNameBox').find('.error').addClass('shows').show();
                } else {
                    $(ele).find('.loanBankNameBox').find('.error').removeClass('shows').hide();
                }
                if ($(ele).find('.loanBankNameBox2 input').val() == '' || $(ele).find('.loanBankNameBox2 input').val() == undefined) {
                    $(ele).find('.loanBankNameBox2').find('.error').addClass('shows').show();
                } else {
                    $(ele).find('.loanBankNameBox2').find('.error').removeClass('shows').hide();
                }
                ;
                // 银行卡号
                if ($(ele).find('.loanBankNoBox select').val() == '' || $(ele).find('.loanBankNoBox select').val() == undefined) {
                    $(ele).find('.loanBankNoBox').find('.error').addClass('shows').show();
                } else {
                    $(ele).find('.loanBankNoBox').find('.error').removeClass('shows').hide();
                }
                ;
                if ($(ele).find('.loanBankNoBox2 input').val() == '' || $(ele).find('.loanBankNoBox2 input').val() == undefined) {
                    $(ele).find('.loanBankNoBox2').find('.error').addClass('shows').show();
                } else {
                    $(ele).find('.loanBankNoBox2').find('.error').removeClass('shows').hide();
                }
            });
        } else {
            if (t.val() == '' || t.val() == undefined) {
                t.parents('td').find('.error').addClass('shows').text(tip).show();
            } else {
                t.parents('td').find('.error').removeClass('shows').hide();
            }
        }
        ;
    };

    // 金额的正确验证
    function loanAmountValid(t, s) {
        if (t.val() == '') {
            return false
        }
        ;
        // 正数和小数
        if (/^[0-9]+([.]{1}[0-9]+){0,1}$/.test(t.val().split(',').join(''))) {
            if (s == undefined) {
                t.next().removeClass('shows').text('').hide();
            }
            ;
        } else {
            if (s == undefined) {
                t.next().addClass('shows').text('请输入正确的数字').show();
            }
            return false;
        }
        ;
        // 小数点后最多两位
        if (t.val().indexOf('.') > 0) {
            if (String(t.val()).split('.')[1].length <= 2) {
                if (s == undefined) {
                    t.next().removeClass('shows').text('').hide();
                }
                ;
            } else {
                if (s == undefined) {
                    t.next().addClass('shows').text('小数点后最多两位小数').show();
                }
                ;
                return false;
            }
            ;
        }
        ;
        //只能输入17位数,包括小数点和小数点后两位(即使没有输入小数也要自动补两位小数),不包括负号
        var decimalLengthFlag = false, changevalue = '', value = t.val();
        if (value.indexOf('-') != -1) {//有负号
            changevalue = value.split(',').join('').substring(1, value.split(',').join('').length);
        } else {//没有负号
            changevalue = value.split(',').join('');
        }
        ;
        if (changevalue.length <= 14) {
            decimalLengthFlag = true;
        } else {
            if (changevalue.length > 17) {
                decimalLengthFlag = false;
            } else {
                decimalLengthFlag = true;
                if (changevalue.substring(0, 14).indexOf('.') == -1) {//第15位之前没有小数点,第15位只能是小数点
                    if (changevalue.charAt(14) == '.') {
                        decimalLengthFlag = true;
                    } else {
                        decimalLengthFlag = false;
                    }
                }
            }
            ;
        }
        ;
        if (decimalLengthFlag) {
            if (s == undefined) {
                t.next().removeClass('shows').text('').hide();
            }
            ;
            return true;
        } else {
            if (s == undefined) {
                t.next().addClass('shows').text('超出金额可输入最大位数').show();
            }
            ;
            return false;
        }
        ;
    };

    // 此次放款日期
    $(".loanRecordListBox").on('change', '.thisLoanDate', function () {
        loanRecordValid($(this), '请输入此次放款日期');
    });

    // 此次放款金额
    $(".loanRecordListBox").on('keyup', '.thisLoanAmount', function () {
        loanRecordValid($(this), '请输入此次放款金额');
        loanAmountValid($(this));
    });

    // 公司归属
    $(".loanRecordListBox").on('change', '.companyOwnershipBox select', function () {
        loanRecordValid($(this), '请选择公司归属');
        $(this).parents('tbody').find('.loanBankNameBox select').change();
        $(this).parents('tbody').find('.loanBankNoBox select').change();
    });

    // 银行名称
    $(".loanRecordListBox").on('change', '.loanBankNameBox select', function () {
        loanRecordValid($(this), '请选择银行名称');
        $(this).parents('tbody').find('.loanBankNoBox select').change();
    });
    $(".loanRecordListBox").on('change', '.loanBankNameBox2 input', function () {
        loanRecordValid($(this), '请输入银行名称');
    });

    // 银行卡号
    $(".loanRecordListBox").on('change', '.loanBankNoBox select', function () {
        loanRecordValid($(this), '请选择银行卡号');
    });
    $(".loanRecordListBox").on('change', '.loanBankNoBox2 input', function () {
        loanRecordValid($(this), '请输入银行卡号');
    });


    // 最后的暂存或保存
    function submitFunction(e) {
        var tipword = '';
        var postdata = new FormData();

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

        postdata.append('cashFlowManageBaseVo.cashTypeDict.id', $("[name=cashTypeId]").val());
        postdata.append('cashFlowManageBaseVo.amount', $("[name=amount]").val().split(',').join(''));
        $('.loanRecordList').removeClass('needSave');
        // 出账记录--过滤掉已提交的(已提交过的数据不再传)
        $('.loanRecordList').each(function (i, ele) {
            if ($(ele).find('.thisExecutor').attr('thisVisible') == 'false') {// 未提交过的
                $(ele).addClass('needSave')
            }
            ;
        });

        // 出账记录
        $('.loanRecordList.needSave').each(function (i, ele) {
            if ($(ele).find('tr:first').attr('reid') && $(ele).find('tr:first').attr('reid') != '') {
                postdata.append('cashFlowManageOutInfoList[' + i + '].id', $(ele).find('tr:first').attr('reid'));
            }
            ;
            postdata.append('cashFlowManageOutInfoList[' + i + '].fromBankAccount', $(ele).find('.loanBankNoBox select').find('option:selected').attr('bankid') ? $(ele).find('.loanBankNoBox select').find('option:selected').attr('bankid') : '');
            postdata.append('cashFlowManageOutInfoList[' + i + '].fromCompanyBelong', $(ele).find('.companyOwnershipBox select').find('option:selected').attr('value') ? $(ele).find('.companyOwnershipBox select').find('option:selected').attr('value') : '');
            postdata.append('cashFlowManageOutInfoList[' + i + '].fromBankName', $(ele).find('.loanBankNameBox select').find('option:selected').attr('value') ? $(ele).find('.loanBankNameBox select').find('option:selected').attr('value') : '');

            postdata.append('cashFlowManageOutInfoList[' + i + '].toBankAccount', $(ele).find('.loanBankNoBox2 input').val() ? $(ele).find('.loanBankNoBox2 input').val() : '');
            postdata.append('cashFlowManageOutInfoList[' + i + '].toBankName', $(ele).find('.loanBankNameBox2 input').val() ? $(ele).find('.loanBankNameBox2 input').val() : '');

            postdata.append('cashFlowManageOutInfoList[' + i + '].loanAmount', $(ele).find('.thisLoanAmount').val().split(',').join(''));
            postdata.append('cashFlowManageOutInfoList[' + i + '].loanDate', $(ele).find('.thisLoanDate').val());
            postdata.append('cashFlowManageOutInfoList[' + i + '].currExecutor', $(ele).find('.thisExecutor').attr('thisExecutorId'));

            postdata.append('cashFlowManageOutInfoList[' + i + '].fileText', UE.getEditor($(ele).find('.unifiedEditorClass').attr('id')).getContent());

        });

        // 删除的出账记录
        for (var i = 0; i < deleteExpenditureRecordIdList.length; i++) {
            postdata.append('cashFlowManageOutInfoList.deleteLoanRecordIdList[' + i + ']', deleteExpenditureRecordIdList[i]);
        }
        ;
        i = null;

        tipword = '保存';
        $('.submitBusiness').addClass("loadingCircle");

        var url = '/cashFlow/doDeal';
        $.ajax({
            url: url,
            type: 'post',
            data: postdata,
            processData: false,
            contentType: false,
            success: function (data) {
                if (data.success) {
                    new $.zui.Messager(tipword + '成功', {
                        type: 'success'
                    }).show();
                    $('.tempoSave,.submitBusiness').removeClass("loadingCircle");+

                    $(".yk_rightcontent").load('/cashFlow/list');
                } else {
                    new $.zui.Messager(tipword + '失败:' + data.msg, {
                        type: 'danger'
                    }).show();
                    $('.submitBusiness').removeClass("loadingCircle");
                }
            },
            error: function (status) {
                new $.zui.Messager(tipword + '时出错:' + status, {
                    type: 'danger'
                }).show();
                $('.submitBusiness').removeClass("loadingCircle");
            }
        });
        return false;


    };

    //表单验证
    function billingRecordFormValid(e) {
        $("#entryForm").validate({
            promptPosition: "bottomLeft",
            submitHandler: function (form) {
                // 放款表格必填验证
                loanRecordValid();
                // 放款表格的金额正确性验证
                $(".loanRecordList").each(function (i, ele) {
                    loanAmountValid($(ele).find('.thisLoanAmount'));
                });
                if ($('.error.shows').length > 0) {
                    $('.error.shows:first').parents('td').find('input:first').focus();
                    $('.error.shows:first').parents('td').find('select:first').focus();
                    return;
                }
                ;
                submitFunction(e)
            },
            rules: {
                'remark': {//摘要
                    maxlength: 1500
                }
            },
            messages: {
                'remark': {
                    maxlength: "最多只能输入{0}个字符"
                }
            }
        })
    };


    //确定保存按钮
    $(".submitBusiness").click(billingRecordFormValid);

    //返回取消按钮
    $(".btn-cancel, .newBackBtn").click(function () {
        // $('#billDate').datetimepicker('remove');
        $(".yk_rightcontent").load('/cashFlow/list');
        return false;
    })
})
