$('[name=receivableType]').on('change', function () {
    if($('[name=receivableType] option:selected').attr('code') === 'goodsCharge') {
        $('.receivableTypeChange').show()
    }else {
        $('.receivableTypeChange').hide()
    }
})
$(function () {
    $('[name=receivableType]').change()
    //初始化日期
    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=firstSettleDate]','1970-01-01','2116-12-31');
    setDate('[name=releaseDate]',$("[name=creatTime]").val(),'2116-12-31');


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

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

    // 排序-付款条件
    function sortReceiptInfo(){
        $(".paymentListTbody").each(function(i,ele){
            $(ele).find('td:first span').text(i+1);
        });
        $('.paymentTable .negativeInformationReduce').show();
        // if( $(".paymentListTbody").length <= 1 ){
        //     $('.paymentTable .negativeInformationReduce').hide();
        // }else{
        //     $('.paymentTable .negativeInformationReduce').show();
        // };
    };
    // 展示原先有的附件
    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();
        }
        ;
    };

    if($('.fileInfoListOriginal').length) {
        // 展示原附件
        showOriginalFile('.fileInfoListOriginal', '.addFileList');
    }

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

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

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

    // 删除附件
    $("#contractEntryForm").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;
    });
    // 删除(原有的)附件
    $("#contractEntryForm").on("click",".btn-delete-originalfile",function(){
        var deleteOrgindex = $(this).parents('td').find('.btn-delete-originalfile').index($(this));
        $(".fileInfoListOriginal").eq(deleteOrgindex).remove();
        $(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;
    });

    let str = ''
    if(!$(".personalListTbodyBack").length){
        str = `
        <tr class="personalListTbody">
            <td width="25%" style="background-color:#fff;">
                <input type="text" name="type" maxlength="500" class="form-control type validInput" readonly>
                <span class="error" style="display:none;font-size:0.12rem;">请选择类型</span>
            </td>
            <td width="25%" style="background-color:#fff;" class="enter">
                <input type="text" name="name" maxlength="500" class="form-control name validInput">
                <span class="error" style="display:none;font-size:0.12rem;">请输入姓名</span>
            </td>
            <td width="25%" style="background-color:#fff;" class="enter">
                <input type="text" name="mobile" maxlength="500" class="form-control mobile validInput">
                <span class="error" style="display:none;font-size:0.12rem;">请输入联系方式</span>
            </td>
            <td width="25%" style="background-color:#fff;">

            </td>
        </tr>
        <tr class="personalListTbody">
            <td width="25%" style="background-color:#fff;">
                <input type="text" name="type" maxlength="500" class="form-control type validInput" readonly>
                <span class="error" style="display:none;font-size:0.12rem;">请选择类型</span>
            </td>
            <td width="25%" style="background-color:#fff;" class="enter">
                <input type="text" name="name" maxlength="500" class="form-control name validInput">
                <span class="error" style="display:none;font-size:0.12rem;">请输入姓名</span>
            </td>
            <td width="25%" style="background-color:#fff;" class="enter">
                <input type="text" name="mobile" maxlength="500" class="form-control mobile validInput">
                <span class="error" style="display:none;font-size:0.12rem;">请输入联系方式</span>
            </td>
            <td width="25%" style="background-color:#fff;">

            </td>
        </tr>
        <tr class="personalListTbody">
            <td width="25%" style="background-color:#fff;">
                <input type="text" name="type" maxlength="500" class="form-control type validInput" readonly>
                <span class="error" style="display:none;font-size:0.12rem;">请选择类型</span>
            </td>
            <td width="25%" style="background-color:#fff;" class="enter">
                <input type="text" name="name" maxlength="500" class="form-control name validInput">
                <span class="error" style="display:none;font-size:0.12rem;">请输入姓名</span>
            </td>
            <td width="25%" style="background-color:#fff;" class="enter">
                <input type="text" name="mobile" maxlength="500" class="form-control mobile validInput">
                <span class="error" style="display:none;font-size:0.12rem;">请输入联系方式</span>
            </td>
            <td width="25%" style="background-color:#fff;">

            </td>
        </tr>`
        $(".personalTbody").append(str)
    }

    $('.personalTbody').find('.personalListTbody').eq(1).find('.type').val('合同签署人')
    $('.personalTbody').find('.personalListTbody').eq(2).find('.type').val('验收经办人')
    $('.personalTbody').find('.personalListTbody').eq(3).find('.type').val('结算经办人')

    $('.personalListTbodyBack').each(function (i,ele) {
        if(i>2) {
            $(ele).find('.negativeInformationReduce').show()
        }else {
            $(ele).find('select.type').prop('disabled',true);
        }
    })

    // 人员信息添加
    $('#personalAdd').on('click', function() {
        let personalTrClone = $(".personalListTbodyAdd:first").clone();
        personalTrClone.show()
        personalTrClone.find('.negativeInformationReduce').show();
        personalTrClone.find('.error').hide();
        $('.personalListTbody:last').after(personalTrClone);
    })

    // 人员信息删除行
    $("#contractEntryForm").on('click','.personalTable .negativeInformationReduce',function(){
        if( $(".personalListTbody").length === 1) {
            $(".personalListTbodyAdd").css({display: 'none'})
            $(".personalListTbodyAdd").find('input').val('')
        }else {
            $(this).parents('.personalListTbody').remove();
        }
    });

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

    // 付款条件-添加
    $('#paymentAdd').on('click', function() {
        if($(".paymentListTbody").length === 1 && $(".paymentListTbody:first").css('display') !== 'table-row') {
            $(".paymentListTbody:first").css({display: 'table-row'})
            $(".paymentListTbody:first").find('input').val('')
        } else {

            let supplierTrClone = $(".paymentListTbody:first").clone();
            supplierTrClone.find('.negativeInformationReduce').show();
            supplierTrClone.find('.error').hide();
            supplierTrClone.find('input').val('');
            $('.paymentListTbody:last').after(supplierTrClone);
        }
        sortReceiptInfo();
    })

    // 添加行-付款条件
    $("#contractEntryForm").on('click','.paymentTable .negativeInformationPlus',function(){
        var supplierTrClone = $(".paymentListTbody:first").clone();
        supplierTrClone.find('.negativeInformationReduce').show();
        supplierTrClone.find('.error').hide();
        supplierTrClone.find('input').val('');
        $(this).parents('.paymentListTbody').after(supplierTrClone);
        sortReceiptInfo();
    });

    // 删除行
    $("#contractEntryForm").on('click','.paymentTable .negativeInformationReduce',function(){
        if( $(".paymentListTbody").length === 1) {
            $(".paymentListTbody:first").css({display: 'none'})
            $(".paymentListTbody:first").find('input').val('')
        }else {
            $(this).parents('.paymentListTbody').remove();
        }

        sortReceiptInfo();
    });

    // 排序-货物
    function sortIGoodsnfo(){
        $(".goodsListTbody").each(function(i,ele){
            $(ele).find('td:first span').text(i);
        });
        if( $(".goodsListTbody").length <= 1 ){
            $('.goodsTable .negativeInformationReduce').hide();
        }else{
            $('.goodsTable .negativeInformationReduce').show();
        };
    };
    sortIGoodsnfo();


    $("#contractEntryForm").on('click','.goodsTable #addGoods',function(){
        var supplierTrClone = $(".goodsListTbody:first").clone();
        supplierTrClone.find('.negativeInformationReduce').show();
        supplierTrClone.find('.error').hide();
        supplierTrClone.find('input').val('');
        supplierTrClone.find('select').val('');
        supplierTrClone.show();
        $('.goodsListTable').append(supplierTrClone);
        sortIGoodsnfo();
    });


    // 删除行
    $("#contractEntryForm").on('click','.goodsTable .negativeInformationReduce',function(){
        $(this).parents('.goodsListTbody').remove();
        sortIGoodsnfo();
    });

    //下载
    function downloadSubmit() {
        window.open('/salesContract/downloadFile')
        // var postdata = new FormData();
        // $.ajax({
        //     url: '/acceptance/downloadFile',
        //     type: 'post',
        //     data: postdata,
        //     processData: false,
        //     contentType: false,
        //     success: function(data){
        //         downloadFileByBase64(data.data, '下载货物模板.xlsx')
        //     },
        //     error: function(status){
        //         console.log(status, '下载模板失败')
        //     }
        // })
    }
    $('#downloadFileTemp').on('click',function (){
        downloadSubmit()
    })

    //导入
    $("#importButton").click(function () {
        $('#importFile').click();
    })

    $("#contractEntryForm").on("change","#importFile",function(e){
        var that = $(this);
        var file = e.target.files[0] || e.dataTransfer.files[0];//用于提交
        var postData = new FormData();
        postData.append('file',file);
        m = null;
        $.ajax({
            url:'/salesContract/doImportGoodsInfo',
            type:'post',
            data:postData,
            processData:false,
            contentType:false,
            success:function(data){
                if( data.success ){
                    for (var n=0; n<data.data.length; n++) {

                        var supplierTrClone1 = $(".goodsListTbody:first").clone();
                        supplierTrClone1.show();
                        supplierTrClone1.find('td').eq(1).find('input').val(data.data[n].goodsName)
                        supplierTrClone1.find('td').eq(2).find('input').val(data.data[n].goodsFactory)
                        supplierTrClone1.find('td').eq(3).find('input').val(data.data[n].modelNumber)
                        supplierTrClone1.find('td').eq(4).find('input').val(data.data[n].units)
                        supplierTrClone1.find('td').eq(5).find('input').val(data.data[n].quantity)
                        supplierTrClone1.find('td').eq(6).find('select').val(data.data[n].clearPrice)
                        supplierTrClone1.find('td').eq(7).find('input').val(data.data[n].salesPrice)
                        supplierTrClone1.find('td').eq(8).find('input').val(data.data[n].remark)
                        supplierTrClone1.find('.error').hide();

                        $('.goodsListTable').append(supplierTrClone1);
                        $("#importFile").val('')
                    }
                    if(data.data.length == 0) {
                        new $.zui.Messager('导入模板数据为空', {
                        type: 'danger'
                    }).show();}
                    n=null;
                    sortIGoodsnfo();
                }else{
                    new $.zui.Messager('导入失败:'+data.msg, {
                        type: 'danger'
                    }).show();
                }
            },
            error:function(status){
                new $.zui.Messager('导入时发生错误:'+status.msg, {
                    type: 'danger'
                }).show();
            }
        });
        return false;
    });

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

    //结算周期方式
    $("[name=settleCycleMethodDict]").change(function () {
        $("[name=settleCycle]").val('')
        if($("[name=settleCycleMethodDict] option:selected").text() == '自然月') {
            $("[name=settleCycle]").parent().find('.viewDetailWord').text('个自然月')
        }else {
            $("[name=settleCycle]").parent().find('.viewDetailWord').text('天')
        }
    })
    if($("[name=settleCycleMethodDict] option:selected").text() == '自然月') {
        $("[name=settleCycle]").parent().find('.viewDetailWord').text('个自然月')
    }else {
        $("[name=settleCycle]").parent().find('.viewDetailWord').text('天')
    }

    //是否有质保金
    $("[name=retention]").change(function () {
        if($("[name=retention] option:selected").val() == 0) {
            $(".retentionTr").hide();
            $("[name=retention]").parent().css('width','0').attr('colspan',3)
        }else {
            $(".retentionTr").show();
            $("[name=retention]").parent().removeAttr('colspan').css('width','35%')
        }
    })
    $("[name=retention]").change()

    //质保金上限
    $("[name=limit]").change(function () {
        if($("[name=limit] option:selected").val() == 0) {
            $(".retentionLimitTr").hide();
            $("[name=limit]").parent().css('width','0').attr('colspan',3)
        }else {
            $(".retentionLimitTr").show();
            $("[name=limit]").parent().removeAttr('colspan').css('width','35%')
        }
    })
    $("[name=limit]").change()

    //质保金释放方式
    $("[name=releaseMethodDict]").change(function () {
        if($("[name=releaseMethodDict] option:selected").text() == '固定日期') {
            $("[name=releaseMethodDict]").parent().removeAttr('colspan').css('width','35%')
            $(".releaseDate").show();
            $(".releaseDays").hide();
        }else if($("[name=releaseMethodDict] option:selected").text() == '回款后固定天数'){
            $("[name=releaseMethodDict]").parent().removeAttr('colspan').css('width','35%')
            $(".releaseDate").hide();
            $(".releaseDays").show();
        }else {
            $("[name=releaseMethodDict]").parent().css('width','0').attr('colspan','3')
            $(".releaseDate").hide();
            $(".releaseDays").hide();
        }
    })
    $("[name=releaseMethodDict]").change()

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

    })
    $(".goodsListTable").on("change", ".goodsListTbody .definePrice", function (event) {
        if($(this).val() == '1') {
            $(this).parent().parent().find('td').eq(7).find('input').addClass('validInput')
        }else {
            $(this).parent().parent().find('td').eq(7).find('input').removeClass('validInput')
            $(this).parent().parent().find('td').eq(7).find('.shows').hide()
        }
    })
    $(".paymentListTbody").on("keyup","input",function(e){
        if($(this).val() == '') {
            $(this).next().addClass('shows').show();
        }else {
            $(this).next().removeClass('shows').hide();
        }
    })




})
//保存
function submitFunction(e){
    var postdata = new FormData();
    postdata.append('taskId',$("[name=taskId]").val());
    postdata.append('businessKey',$("[name=basicId]").val());
    postdata.append('salesContractBasicInfo.id',$("[name=salesContractBasicInfoId]").val());
    postdata.append('salesContractBasicInfo.businessNumber',$("[name=businessNo]").val());
    postdata.append('salesContractBasicInfo.contractNumber',$("[name=contractNumber]").val());
    postdata.append('salesContractBasicInfo.contractName',$("[name=contractName]").val());

    postdata.append('salesContractBasicInfo.contractPeriod',$("[name=contractPeriod]").val());
    postdata.append('salesContractBasicInfo.contractPlanAmountType',$("[name=contractPlanAmountType]").val());
    postdata.append('salesContractBasicInfo.contractPlanAmount',$("[name=contractPlanAmount]").val().split(",").join(''));
    // postdata.append('salesContractBasicInfo.checkOperator',$("[name=checkOperator]").val());
    // postdata.append('salesContractBasicInfo.settlementOperator',$("[name=settlementOperator]").val());

    //人员信息
    for(var i=0;i<$('.personalListTbody').not(':first').length;i++) {
        postdata.append('salesContractPersonInfos['+i+'].type',$(".personalListTbody").not(':first').eq(i).find('.type').val());
        postdata.append('salesContractPersonInfos['+i+'].name',$(".personalListTbody").not(':first').eq(i).find('.name').val());
        // postdata.append('salesContractPersonInfos['+i+'].cardType',$(".personalListTbody").eq(i).find('.cardType').val());
        // postdata.append('salesContractPersonInfos['+i+'].socialCreditCode',$(".personalListTbody").eq(i).find('.socialCreditCode').val());
        postdata.append('salesContractPersonInfos['+i+'].mobile',$(".personalListTbody").not(':first').eq(i).find('.mobile').val());
    }
    //付款条件
    for(var i=0;i<$(".paymentListTbody").length;i++) {
        postdata.append('paymentConditionList['+i+'].paymentCondition',$(".paymentListTbody").eq(i).find('.paymentCondition').val());
    }
    i=null;
    postdata.append('salesContractBasicInfo.sellerName',$("[name=sellerName]").val());
    postdata.append('salesContractBasicInfo.buyerName',$("[name=buyerName]").val());
    // postdata.append('salesContractSettleInfo.deliveryDate',$("[name=deliveryDate]").val());
    // postdata.append('salesContractSettleInfo.signDate',$("[name=signDate]").val());
    // postdata.append('salesContractSettleInfo.firstSettleDate',$("[name=firstSettleDate]").val());
    postdata.append('salesContractSettleInfo.settleCycleMethod',$("[name=settleCycleMethodDict]").val());
    postdata.append('salesContractSettleInfo.settleCycle',$("[name=settleCycle]").val());
    postdata.append('salesContractSettleInfo.receivableType ',$("[name=receivableType]").val());
    if($("[name=receivableType]  option:selected").attr('code') === 'goodsCharge') {
        postdata.append('salesContractSettleInfo.planPaybackDays', $("[name=planPaybackDays]").val());
        postdata.append('salesContractSettleInfo.estimatePaybackDays',$("[name=estimatePayBackDays]").val());
    }

    postdata.append('salesContractRetentionInfo.retention',$("[name=retention]").val());
    postdata.append('salesContractRetentionInfo.retentionPercent',$("[name=retentionPercent]").val());
    postdata.append('salesContractRetentionInfo.limit',$("[name=limit]").val());
    postdata.append('salesContractRetentionInfo.retentionLimit',$("[name=retentionLimit]").val().split(",").join(''));
    postdata.append('salesContractRetentionInfo.releaseMethod',$("[name=releaseMethodDict]").val());
    if($("[name=releaseMethodDict] option:selected").text() == '固定日期') {
        postdata.append('salesContractRetentionInfo.releaseDate',$("[name=releaseDate]").val());
    }
    if($("[name=releaseMethodDict] option:selected").text() == '回款后固定天数'){
        postdata.append('salesContractRetentionInfo.releaseDays',$("[name=releaseDays]").val());
    }

    //货物信息
    for(var i=1;i<$(".goodsListTbody").length;i++) {
        postdata.append('goodsInfoList['+(i-1)+'].goodsName',$(".goodsListTbody").eq(i).find('td').eq(1).find('input').val());
        postdata.append('goodsInfoList['+(i-1)+'].goodsFactory',$(".goodsListTbody").eq(i).find('td').eq(2).find('input').val());
        postdata.append('goodsInfoList['+(i-1)+'].modelNumber',$(".goodsListTbody").eq(i).find('td').eq(3).find('input').val());
        postdata.append('goodsInfoList['+(i-1)+'].units',$(".goodsListTbody").eq(i).find('td').eq(4).find('input').val());
        postdata.append('goodsInfoList['+(i-1)+'].quantity',$(".goodsListTbody").eq(i).find('td').eq(5).find('input').val());
        postdata.append('goodsInfoList['+(i-1)+'].clearPrice',$(".goodsListTbody").eq(i).find('td').eq(6).find('select').val());
        postdata.append('goodsInfoList['+(i-1)+'].salesPrice',$(".goodsListTbody").eq(i).find('td').eq(7).find('input').val());
        postdata.append('goodsInfoList['+(i-1)+'].remark',$(".goodsListTbody").eq(i).find('td').eq(8).find('input').val());
    }
    i=null;
    // 附件信息
    for( var m=0;m<$('.addFileList').data('filearray').length;m++ ){
        postdata.append('salesContractFile',$('.addFileList').data('filearray')[m]);
    };
    m = null;
    // 删除的附件信息
    // for( var m=0;m<$('.addFileList').data('deletefileid').length;m++ ){
    //     postdata.append('deleteFileIdList['+m+']',$('.addFileList').data('deletefileid')[m]);
    // };
    // m = null;

    if($(".fileInfoListOriginal").length) {
        $('.fileInfoListOriginal').each(function (i, ele) {
            postdata.append('fileIdList['+i+']',$(ele).find('.originalId').val())
        })
    }
    var url = '/salesContract/doAdd',tip='录入';
    if(e === 'temp') {
            url = '/salesContract/tempAdd',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('/salesContract/list',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 = {
    'contractNumber':{
        required:true,
        maxlength:50
    },
    'contractName': {
        required:true,
    },
    'contractPeriod':{
        required:true,
        // digits:true,
        // min:0
    },
    'contractPlanAmountType':{
        required:true,

    },
    'contractPlanAmount':{
        required:true,
        // checkContractPlanAmountType: true
    },
    'checkOperator':{
        required:true,
        maxlength:50
    },
    'settlementOperator':{
        required:true,
        maxlength:50
    },
    'paymentCondition':{
        required:true,
        maxlength:500
    },
    'deliveryDate':{
        required:true
    },
    'signDate':{
        required:true
    },
    'firstSettleDate':{
        required:true,
    },
    'settleCycleMethodDict':{
        required:true
    },
    'settleCycle':{
        required:true,
        digits:true,
        min:0
    },
    'receivableType': {
        required:true
    },
    'planPaybackDays':{
        required:true,
        checkPlanPaybackDays:true
    },
    'estimatePayBackDays':{
        required:true,
        checkEstimatePayBackDays:true
    },
    'retention':{
        required:true
    },
    'retentionPercent':{
        required:true,
        checkRetentionPercent: true
    },
    'limit':{
        required:true
    },
    'retentionLimit':{
        required:true,
        checkRetentionLimit:true
    },
    'releaseMethodDict':{
        required:true
    },
    'releaseDate':{
        required:true
    },
    'releaseDays':{
        required:true,
        digits:true,
        checkReleaseDays:true
    },

};

var formMessages = {
    'contractNumber':{
        required:'请输入合同编号',
        maxlength:'最多输入50个字符'
    },
    'contractName': {
        required:'请输入合同名称'
    },
    'contractPeriod':{
        required:'请输入合同期限'
    },
    'contractPlanAmountType':{
        required:'请选择合同约定金额类型'
    },
    'contractPlanAmount':{
        required:'请输入合同约定金额',
    },
    'checkOperator':{
        required:'请输入验收经办人',
        maxlength:'最多输入50个字符'
    },
    'settlementOperator':{
        required:'请输入结算经办人',
        maxlength:'最多输入50个字符'
    },
    'paymentCondition':{
        required:'请输入付款条件',
        maxlength:'最多输入500个字符'
    },
    'deliveryDate':{
        required:'请输入发货时间'
    },
    'signDate':{
        required:'请输入签收时间'
    },
    'firstSettleDate':{
        required:'请选择第一次结算时间',
    },
    'settleCycleMethodDict':{
        required:'请选择结算周期方式'
    },
    'settleCycle':{
        required:'请输入结算周期'
    },
    'receivableType': {
        required: '请选择应收账款种类'
    },
    'planPaybackDays':{
        required:'请输入约定回款时间'
    },
    'estimatePayBackDays':{
        required:'请输入预估回款时间',
    },
    'retention':{
        required:'请选择是否有质保金'
    },
    'retentionPercent':{
        required:'请输入质保金比例'
    },
    'limit':{
        required:'请选择质保金是否有上限'
    },
    'retentionLimit':{
        required:'请输入质保金上限',
    },
    'releaseMethodDict':{
        required:'请选择质保金释放时间'
    },
    'releaseDate':{
        required:'请选择释放日期'
    },
    'releaseDays':{
        required:'请输入释放天数'
    },
};

//合同约定金额限制
$.validator.addMethod("checkContractPlanAmountType",function(value,element){
    value = value.replace(/,/gi,'')
    var score = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/
    return this.optional(element) || (score.test(value));
},"合同约定金额格式不正确");

//约定回款时间限制
$.validator.addMethod("checkPlanPaybackDays",function(value,element){
    value = value.replace(/,/gi,'')
    var score = /^([1-9][0-9]*)$/
    return this.optional(element) || (score.test(value));
},"请输入大于0的整数");

//预估回款时间限制
$.validator.addMethod("checkEstimatePayBackDays",function(value,element){
    value = value.replace(/,/gi,'')
    var score = /^([1-9][0-9]*)$/
    return this.optional(element) || (score.test(value));
},"请输入大于0的整数");

//质保金比例限制
$.validator.addMethod("checkRetentionPercent",function(value,element){
    if( Number(value) > 0 && Number(value) <= 100){
        return this.optional(element) || true
    }
},"质保金比例格式不正确");

//质保金上限限制
$.validator.addMethod("checkRetentionLimit",function(value,element){
    value = value.replace(/,/gi,'')
    var score = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/
    return this.optional(element) || (score.test(value));
},"质保金上限格式不正确");

//释放天数限制
$.validator.addMethod("checkReleaseDays",function(value,element){
    value = value.replace(/,/gi,'')
    var score = /^([1-9][0-9]*)$/
    return this.optional(element) || (score.test(value));
},"请输入大于0的整数");

//验证付款条件
function paymentValid() {
    $('.paymentListTbody').each(function (i,ele) {
        if($(ele).find('.paymentCondition').val() !== '') {
            $(ele).find('.error').removeClass('shows').hide()
        }else {
            $(ele).find('.error').addClass('shows').show()
        }
    })
}



//表单验证
function addNewCustomer(e){
    paymentValid();
    if($(".addFileList .fileinput").val() == '' && !$(".addFileList .content").length) {
        $(".addFileList .error").addClass('shows').show();
    }else {
        $(".addFileList .error").removeClass('shows').hide();
    }

    $("#contractEntryForm").validate({
        promptPosition : "bottomLeft",
        submitHandler : function(form) {
            //回款时间校验
            if(Number($("[name=estimatePayBackDays]").val()) < Number($("[name=planPaybackDays]").val())) {
                new $.zui.Messager('预估回款时间应大于约定回款时间' , {
                    type: 'danger'
                }).show();
                return false;
            }
            //释放日期校验
            if(new Date($('[name=gmtCreate]').val()).getTime() > new Date($('[name=releaseDate]').val()).getTime()) {
                new $.zui.Messager('释放日期应大于业务创建日期' , {
                    type: 'danger'
                }).show();
                return false;
            }
            //付款条件提交验证
            if($(".paymentTable .paymentListTbody").length) {
                if($(".paymentTable .paymentListTbody").length === 1 && $(".paymentTable .paymentListTbody").css('display') === 'none') {
                    new $.zui.Messager('请添加付款条件', {
                        type: 'danger'
                    }).show();
                    return false;
                }else {
                    $('.paymentTable .validInput').change();
                }

            }else {
                new $.zui.Messager('请添加付款条件', {
                    type: 'danger'
                }).show();
                return false;
            }
            //人员信息提交验证
            if($(".personalListTbody").not(':first').length == 0){
                console.log(111)
                new $.zui.Messager('请添加人员信息', {
                    type: 'danger'
                }).show();
                return false;
            }
            for(var i=0;i<$(".personalListTbody").not(':first').length;i++) {
                if(!$(".personalListTbody").not(':first').eq(i).find('.type').val()) {
                    new $.zui.Messager('请选择人员信息类型', {
                        type: 'danger'
                    }).show();
                    return false;
                }
                if(!$(".personalListTbody").not(':first').eq(i).find('.name').val()) {
                    new $.zui.Messager('请输入人员信息姓名', {
                        type: 'danger'
                    }).show();
                    return false;
                }
                if(!$(".personalListTbody").not(':first').eq(i).find('.mobile').val()) {
                    new $.zui.Messager('请输入人员信息联系方式', {
                        type: 'danger'
                    }).show();
                    return false;
                }
            }
            // if($(".personalTable .personalListTbody").length) {
            //     if($(".personalTable .personalListTbody").length === 1 && $(".personalTable .personalListTbody").css('display') === 'none') {
            //         new $.zui.Messager('请添加人员信息', {
            //             type: 'danger'
            //         }).show();
            //         return false;
            //     }else{
            //         for(var i=0;i<$(".personalListTbody").length;i++) {
            //             if(!$(".personalListTbody").eq(i).find('.name').val()) {
            //                 new $.zui.Messager('请输入人员信息姓名', {
            //                     type: 'danger'
            //                 }).show();
            //                 return false;
            //             }
            //         }
            //         $('.personalTable .validInput').change();
            //     }
            // }else {
            //     new $.zui.Messager('请添加人员信息', {
            //         type: 'danger'
            //     }).show();
            //     return false;
            // }

            //货物必填验证
            if($(".goodsListTable .goodsListTbody").length) {
                $('.goodsListTable .validInput').change();
            }else {
                new $.zui.Messager('请添加货物信息。' , {
                    type: 'danger'
                }).show();
                return false;
            }
            if( $('.error.shows').length>0 ){
                $('.error.shows:first').prev().focus();
                return;
            };
            submitFunction(e);
        },
        rules:formRules,
        messages : formMessages
    });
};

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

 // 暂存-按钮
 $(".yk_addNewMsg .submitTemSave").click(function (event) {
    event.preventDefault();
    submitFunction('temp', event)
 })

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