// 排序-货物
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();
    }
    ;
};

// 选择货物的时候后端计算暂定单价
function calcGoodsTempPrice(goodsList, type) {
    if(!$("[name=accrualMarginCalcMethod]").val()) {
        if(type !== 'noMessage') {
            new $.zui.Messager('请选择利差计算方式', {
                type: 'danger'
            }).show();
        }
        return
    }
    var postdata = new FormData();

    goodsList.forEach((item, index) => {
        postdata.append(`salesGoodsIds[${index}].id`, item.id);
        postdata.append(`salesGoodsIds[${index}].quantity`, item.quantity);
        postdata.append(`salesGoodsIds[${index}].supplement`, item.supplement);
    })
    postdata.append(`priceRule.accrualMarginCalcMethod`, $("[name=accrualMarginCalcMethod]").val());
    if($("[name=accrualMarginCalcMethod] option:selected").attr('code') === 'purchAccrualMarginCalcMethod_fixedInterest') {
        if(!$("[name=factoringFinanceDeadline]").val()) {
            if(type !== 'noMessage') {
                new $.zui.Messager('请输入预估保理融资期限', {
                    type: 'danger'
                }).show();
            }

            return
        }
        if(!$("[name=monthlyInterestRate]").val()) {
            if(type !== 'noMessage') {
                new $.zui.Messager('请输入月利率', {
                    type: 'danger'
                }).show();
            }

            return
        }
        postdata.append(`priceRule.factoringFinanceDeadline`, $("[name=factoringFinanceDeadline]").val());
        postdata.append(`priceRule.monthlyInterestRate`, $("[name=monthlyInterestRate]").val());
    }else {
        if(!$("[name=differAmount]").val()) {
            if(type !== 'noMessage') {
                new $.zui.Messager('请输入差额', {
                    type: 'danger'
                }).show();
            }
            return
        }
        postdata.append(`priceRule.differAmount`, $("[name=differAmount]").val().split(',').join(''));
    }
    $.ajax({
        url: '/purchContract/calculateGoods',
        type: 'post',
        processData: false,
        contentType: false,
        data: postdata,
        success: function (data) {
            if (data.success) {
                const list = data.data
                if(type === 'noMessage') {
                    $('.goodsListTable').empty()
                }
                list.forEach(item => {
                    var supplierTrClone2 = $(".goodsListTbody:first").clone();
                    supplierTrClone2.find('.negativeInformationReduce').show();
                    supplierTrClone2.find('.error').hide();
                    supplierTrClone2.find('input').val('');
                    supplierTrClone2.find('select').val('');
                    supplierTrClone2.find('td').eq(1).find('input').attr('supplement', item.supplement)
                    supplierTrClone2.find('td').eq(1).find('input').val(item.goodsName)
                    supplierTrClone2.find('td').eq(2).find('input').val(item.goodsFactory)
                    supplierTrClone2.find('td').eq(3).find('input').val(item.modelNumber)
                    supplierTrClone2.find('td').eq(4).find('input').val(item.units)
                    supplierTrClone2.find('td').eq(5).find('input').val(item.quantity)
                    supplierTrClone2.find('td').eq(6).find('input').val(item.price === '不明确' ? item.price : Number(item.price).toFixed(2))
                    supplierTrClone2.find('td').eq(7).find('input').val(item.remark)
                    supplierTrClone2.find('td').eq(1).find('input').attr('goodsId', item.id)
                    supplierTrClone2.attr('id', item.id)
                    supplierTrClone2.show();
                    $('.goodsListTable').append(supplierTrClone2);
                    sortIGoodsnfo();
                })
                $("#myModal-chooseGoods").modal("hide");
            } else {
                new $.zui.Messager('暂定单价失败:' + data.msg, {
                    type: 'danger'
                }).show();
            }
        },
        error: function (status) {
            new $.zui.Messager('暂定单价发生错误:' + status, {
                type: 'danger'
            }).show();
        }
    });
}

// 利差计算方式发生改变
$("[name=accrualMarginCalcMethod]").on('change', function () {

    if($(".goodsListTbody").length > 1) {
        const goodList = []
        for (let i = 1; i < $(".goodsListTbody").length; i++) {
            goodList.push({
                supplement: $(".goodsListTbody").eq(i).find('td').eq(1).find('input').attr('supplement'),
                id: $(".goodsListTbody").eq(i).find('td').eq(1).find('input').attr('goodsId'),
                quantity: $(".goodsListTbody").eq(i).find('td').eq(5).find('input').val()
            })

        }
        calcGoodsTempPrice(goodList, 'noMessage')
    }

})

// 预估保理融资期限、月利率、差额
$("[name=factoringFinanceDeadline], [name=monthlyInterestRate], [name=differAmount]").on('blur', function () {
    if($(".goodsListTbody").length > 1) {
        const goodList = []
        for (let i = 1; i < $(".goodsListTbody").length; i++) {
            goodList.push({
                supplement: $(".goodsListTbody").eq(i).find('td').eq(1).find('input').attr('supplement'),
                id: $(".goodsListTbody").eq(i).find('td').eq(1).find('input').attr('goodsId'),
                quantity: $(".goodsListTbody").eq(i).find('td').eq(5).find('input').val()
            })

        }
        calcGoodsTempPrice(goodList, 'noMessage')
    }
} )


function chooseGoods(id) {
    var chooseData = $('#chooseGoodsList').jqGrid('getRowData', id);
    var trStr = `<tr class="choosedGoodsTbody">
                        <td width="5%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;"></td>
                        <td width="14%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.goodsName + `</td>
                        <td width="14%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.goodsFactory + `</td>
                        <td width="14%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.modelNumber + `</td>
                        <td width="13%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.units + `</td>
                        <td width="13%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.quantity + `</td>
                        <td width="13%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.salesPrice + `</td>
                        <td style="display: none">` + chooseData.id + `</td>
                        <td style="display: none" class="remark">` + chooseData.remark + `</td>
                        <td width="10%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;border-right: 1px solid #E8F0F3;"><span class="relaseGoods" style="color: #5AC4FC;cursor: pointer">释放</span></td>
                    </tr>`
    $(".choosedGoodsList").append(trStr);
    $("#myModal-chooseGoods").resize();
    sortChooseGoodsInfo();
}

//paixu
function sortChooseGoodsInfo() {
    $(".choosedGoodsTbody").each(function (i, ele) {
        $(ele).find('td:first').text(i + 1);
    });
}



$(function () {
    //初始化日期
    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');

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

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


    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 submitFunction(e) {
        var postdata = new FormData();

        postdata.append('taskId', $("[name=taskId]").val());
        postdata.append('businessKey', $("[name=basicId]").val());
        postdata.append('purchContractBasicInfo.id', $("[name=purchContractBasicInfoId]").val());
        postdata.append('purchContractBasicInfo.businessNumber', $("[name=businessNo]").val());
        postdata.append('purchContractBasicInfo.contractNumber', $("[name=contractNumber]").val());
        postdata.append('purchContractBasicInfo.supplierName', $("[name=supplierName]").val());
        postdata.append('purchContractBasicInfo.contractName', $("[name=contractName]").val());
        postdata.append('purchContractBasicInfo.buyerName', $("[name=buyerName]").val());
        postdata.append('purchContractBasicInfo.contractPeriod', $("[name=contractPeriod]").val());
        postdata.append('purchContractBasicInfo.repurchMethod', $("[name=repurchMethod]").val());
        postdata.append('purchContractBasicInfo.contractPlanAmountType', $("[name=contractPlanAmountType]").val());
        postdata.append('purchContractBasicInfo.contractPlanAmount', $("[name=contractPlanAmount]").val().split(",").join(''));

        //付款条件
        for (var i = 0; i < $(".paymentListTbody").length; i++) {
            postdata.append('purchContractPaymentCondition[' + i + '].paymentCondition', $(".paymentListTbody").eq(i).find('.paymentCondition').val());
        }
        i = null;

        // postdata.append('purchContractSettleCycle.deliveryDate', $("[name=deliveryDate]").val());
        // postdata.append('purchContractSettleCycle.signDate', $("[name=signDate]").val());
        // postdata.append('purchContractSettleCycle.firstSettleDate', $("[name=firstSettleDate]").val());
        postdata.append('purchContractSettleCycle.settleCycleMethod', $("[name=settleCycleMethodDict]").val());
        postdata.append('purchContractSettleCycle.settleCycle', $("[name=settleCycle]").val());
        postdata.append('purchContractSettleCycle.planPaybackDays', $("[name=planPaybackDays]").val());
        postdata.append('purchContractSettleCycle.settleMinAmount',$("[name=settleMinAmount]").val().split(',').join(''));

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

        postdata.append('purchContractPriceRule.accrualMarginCalcMethod', $("[name=accrualMarginCalcMethod]").val());
        if ($("[name=accrualMarginCalcMethod] option:selected").text() == '固定利率') {
            postdata.append('purchContractPriceRule.tradePlatformOffer', $("[name=tradePlatformOffer]").val());
            postdata.append('purchContractPriceRule.factoringOffer', $("[name=factoringOffer]").val());
            postdata.append('purchContractPriceRule.factoringFinanceDeadline', $("[name=factoringFinanceDeadline]").val());
            postdata.append('purchContractPriceRule.monthlyInterestRate', $("[name=monthlyInterestRate]").val());
        } else {
            postdata.append('purchContractPriceRule.differAmount', $("[name=differAmount]").val().split(',').join(''));
        }

        // postdata.append('purchContractArExp.startDate', $("[name=startDate]").val());
        // postdata.append('purchContractArExp.endDate', $("[name=endDate]").val());

        //货物信息
        for (var i = 1; i < $(".goodsListTbody").length; i++) {
            postdata.append('purchContractGoodsInfo[' + (i - 1) + '].supplement', $(".goodsListTbody").eq(i).find('td').eq(1).find('input').attr('supplement'));
            postdata.append('purchContractGoodsInfo[' + (i - 1) + '].goodsName', $(".goodsListTbody").eq(i).find('td').eq(1).find('input').val());
            postdata.append('purchContractGoodsInfo[' + (i - 1) + '].goodsFactory', $(".goodsListTbody").eq(i).find('td').eq(2).find('input').val());
            postdata.append('purchContractGoodsInfo[' + (i - 1) + '].modelNumber', $(".goodsListTbody").eq(i).find('td').eq(3).find('input').val());
            postdata.append('purchContractGoodsInfo[' + (i - 1) + '].units', $(".goodsListTbody").eq(i).find('td').eq(4).find('input').val());
            postdata.append('purchContractGoodsInfo[' + (i - 1) + '].quantity', $(".goodsListTbody").eq(i).find('td').eq(5).find('input').val());
            //postdata.append('purchContractGoodsInfo['+(i-1)+'].clearPrice',$(".goodsListTbody").eq(i).find('td').eq(6).find('select').val());
            //postdata.append('purchContractGoodsInfo['+(i-1)+'].purchPrice',$(".goodsListTbody").eq(i).find('td').eq(7).find('input').val().split(',').join());
            postdata.append('purchContractGoodsInfo[' + (i - 1) + '].price', $(".goodsListTbody").eq(i).find('td').eq(6).find('input').val());
            postdata.append('purchContractGoodsInfo[' + (i - 1) + '].remark', $(".goodsListTbody").eq(i).find('td').eq(7).find('input').val());

            postdata.append('purchContractGoodsInfo[' + (i - 1) + '].salesContractGoodsInfoId', $(".goodsListTbody").eq(i).find('td').eq(1).find('input').attr('goodsId'));
            postdata.append('purchContractGoodsInfo[' + (i - 1) + '].goodsCode', $(".goodsListTbody").eq(i).find('td').eq(0).find('span').text());
        }
        // 增值税要求
        postdata.append('purchContractVatInfo.priceComment', $("[name=priceComment]").val());
        postdata.append('purchContractVatInfo.taxRate', $("[name=taxRate]").val());
        postdata.append('purchContractVatInfo.receiptType', $("[name=receiptType]").val());
        // postdata.append('purchContractVatInfo.openCycle', $("[name=openCycle]").val());
        postdata.append('purchContractVatInfo.openBank', $("[name=openBank]").val());
        postdata.append('purchContractVatInfo.receiptAccount', $("[name=receiptAccount]").val());
        postdata.append('purchContractVatInfo.receiptRemark', $("[name=receiptRemark]").val());

        // 结算与付款
        postdata.append('purchContractSettlePayment.settleMethod', $("[name=settleMethod]").val());
        postdata.append('purchContractSettlePayment.paymentMethod', $("[name=paymentMethod]").val());
        postdata.append('purchContractSettlePayment.bankAccountName', $("[name=bankAccountName]").val());
        postdata.append('purchContractSettlePayment.bankAccount', $("[name=bankAccount]").val());
        postdata.append('purchContractSettlePayment.bankName', $("[name=bankName]").val());

        // 需方收货人
        for (var i = 1; i < $(".demandListTbody").length; i++) {
            postdata.append('buyers[' + (i - 1) + '].serialNumber', i);
            postdata.append('buyers[' + (i - 1) + '].name', $(".demandListTbody").eq(i).find('td').eq(1).find('input').val());
            postdata.append('buyers[' + (i - 1) + '].idCard', $(".demandListTbody").eq(i).find('td').eq(2).find('input').val());
            postdata.append('buyers[' + (i - 1) + '].contact', $(".demandListTbody").eq(i).find('td').eq(3).find('input').val());
        }

        // 供应商发货人
        for (var i = 1; i < $(".supplierListTbody").length; i++) {
            postdata.append('sellers[' + (i - 1) + '].serialNumber', i);
            postdata.append('sellers[' + (i - 1) + '].name', $(".supplierListTbody").eq(i).find('td').eq(1).find('input').val());
            postdata.append('sellers[' + (i - 1) + '].idCard', $(".supplierListTbody").eq(i).find('td').eq(2).find('input').val());
            postdata.append('sellers[' + (i - 1) + '].contact', $(".supplierListTbody").eq(i).find('td').eq(3).find('input').val());
        }


        i = null;
        var url = '/purchContract/doAdd', tip = '录入';
        function submitAjax() {
            $.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('/purchContract/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();
                }
            });
        }
        if(e === 'temp') {
            url = '/purchContract/tempAdd',tip='暂存';
            submitAjax()
        }

        if(e !== 'temp') {
            if($("[name=accrualMarginCalcMethod] option:selected").attr('code') === 'purchAccrualMarginCalcMethod_fixedInterest') {
                if( Number($('[name=monthlyInterestRate]').val()) === 0) {
                    bootbox.confirm({
                        title : '提示',
                        message : '<div style="text-align:left;font-size:0.12rem">月利率为 0，无贸易差价，确定提交么 ?</div>',
                        size : 'small',
                        buttons : {
                            cancel :  {
                                label : '取消',
                                className:  'btn-white btn-info',

                            },
                            confirm : {
                                label : '确定',
                                className:'btn-white btn-info colorbtn'
                            }
                        },
                        callback:function(result){
                            if (result) {
                                submitAjax()
                            }
                        }
                    })
                }else {
                    submitAjax()
                }
            }else {
                if( Number($('[name=differAmount]').val()) === 0) {
                    bootbox.confirm({
                        title : '提示',
                        message : '<div style="text-align:left;font-size:0.12rem">固定差额为 0，无贸易差价，确定提交么 ?</div>',
                        size : 'small',
                        buttons : {
                            cancel :  {
                                label : '取消',
                                className:  'btn-white btn-info',

                            },
                            confirm : {
                                label : '确定',
                                className:'btn-white btn-info colorbtn'
                            }
                        },
                        callback:function(result){
                            if (result) {
                                submitAjax()
                            }
                        }
                    })
                }else {
                    submitAjax()
                }
            }
        }
        return false;
    };

    var formRules = {
        // 'contractNumber': {
        //     required: true,
        // },
        'contractName': {
            required: true
        },
        'contractPeriod': {
            required: true,
            // digits:true,
            // min:0
        },
        'contractPlanAmountType': {
            required: true
        },
        'contractPlanAmount': {
            required: true,
            // checkContractPlanAmount: true
        },
        'repurchMethod': {
            required: true
        },

        'deliveryDate': {
            required: true
        },
        'signDate': {
            required: true
        },
        'firstSettleDate': {
            required: true,
        },
        'settleCycleMethodDict': {
            required: true
        },
        'settleCycle': {
            required: true,
            digits:true,
            min:0
        },
        'planPaybackDays': {
            required: true,
            checkPlanPaybackDays:true,
        },
        'settleMinAmount':{
            required:true,
            checkSettleMinAmount:true,
        },

        'retention': {
            required: true
        },
        'retentionPercent': {
            required: true,
            checkRetentionPercent: true
        },
        'hasLimit': {
            required: true
        },
        'retentionLimit': {
            required: true,
            checkRetentionLimit:true
        },
        'releaseMethodDict': {
            required: true
        },
        'releaseDate': {
            required: true
        },
        'releaseDays': {
            required: true,
            digits:true,
            checkReleaseDays:true
        },

        'accrualMarginCalcMethod': {
            required: true
        },
        'tradePlatformOffer': {
            required: true,
            checkTradePlatformOffer:true,
        },
        'factoringOffer': {
            required: true,
            checkFactoringOffer:true,
        },
        'factoringFinanceDeadline': {
            required: true,
            digits:true,
            min:0
        },
        'startDate': {
            required: true
        },
        'endDate': {
            required: true
        },
        'monthlyInterestRate': {
            required: true,
            checkMonthlyInterestRate:true,
        },
        'differAmount': {
            required: true,
            checkDifferAmount:true
        },
        'settleMethod': {
            required: true
        },
        'paymentMethod': {
            required: true
        },
        'receiptRemark': {
            required: true
        },
        'receiptAccount': {
            required: true
        },
        'openBank': {
            required: true
        },
        'openCycle': {
            required: true
        },
        'receiptType': {
            required: true
        },
        'taxRate': {
            required: true,
            checkTaxRate:true
        },
        'priceComment': {
            required: true
        },
        'bankAccountName': {
            required: true
        },
        'bankAccount': {
            required: true
        },
        'bankName': {
            required: true
        }

    };

    var formMessages = {
        // 'contractNumber': {
        //     required: '请输入合同编号',
        //     maxlength:'最多输入50个字符',
        // },
        'contractName': {
            required: '请输入合同名称',
            maxlength:'最多输入50个字符',
        },
        'contractPeriod': {
            required: '请输入合同期限'
        },
        'contractPlanAmountType': {
            required: '请选择合同约定金额类型'
        },
        'contractPlanAmount': {
            required: '请输入合同约定金额',
        },
        'repurchMethod': {
            required: '请选择回购方式'
        },

        'deliveryDate': {
            required: '请输入发货时间'
        },
        'signDate': {
            required: '请输入签收时间'
        },
        'firstSettleDate': {
            required: '请选择第一次结算时间',
        },
        'settleCycleMethodDict': {
            required: '请选择结算周期方式'
        },
        'settleCycle': {
            required: '请输入结算周期'
        },
        'planPaybackDays': {
            required: '请输入约定回款时间'
        },
        'settleMinAmount':{
            required:'请输入结算最低差额',
        },
        'retention': {
            required: '请选择是否有质保金'
        },
        'retentionPercent': {
            required: '请输入质保金比例'
        },
        'hasLimit': {
            required: '请选择质保金是否有上限'
        },
        'retentionLimit': {
            required: '请输入质保金上限',
        },
        'releaseMethodDict': {
            required: '请选择质保金释放时间'
        },
        'releaseDate': {
            required: '请选择释放日期'
        },
        'releaseDays': {
            required: '请输入释放天数'
        },

        'accrualMarginCalcMethod': {
            required: '请选择利差计算方式'
        },
        'tradePlatformOffer': {
            required: '请输入贸易平台报价'
        },
        'factoringOffer': {
            required: '请输入保理报价',
        },
        'factoringFinanceDeadline': {
            required: '请输入预估保理融资期限'
        },
        'startDate': {
            required: '请输入开始日期'
        },
        'endDate': {
            required: '请输入结束日期'
        },
        'monthlyInterestRate': {
            required: '请输入月利率'
        },
        'differAmount': {
            required: '请输入差额'
        },
        'settleMethod': {
            required: '请选择结算方式'
        },
        'paymentMethod': {
            required: '请选择付款方式'
        },
        'receiptRemark': {
            required: '请输入发票备注',
            maxlength:'最多输入500个字符',
},
        'receiptAccount': {
            required: '请输入发票账号',
            maxlength:'最多输入50个字符',
        },
        'openBank': {
            required: '请输入发票开户行',
            maxlength:'最多输入50个字符',
        },
        'openCycle': {
            required: '请输入开票周期',
            maxlength:'最多输入50个字符',
        },
        'receiptType': {
            required: '请选择发票类型'
        },
        'taxRate': {
            required: '请输入税率',
        },
        'priceComment': {
            required: '请输入价款说明',
            maxlength:'最多输入50个字符',
        },
        'bankAccountName': {
            required: '请输入价供应商收款账户名',
        },
        'bankAccount': {
            required: '请输入收款账号',
        },
        'bankName': {
            required: '请输入收款账号开户行',
        }
    };

    //约定回款时间限制
    $.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("checkSettleMinAmount",function(value,element){
        value = value.replace(/,/gi,'')
        // var score = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/;
        var score = /^(?:[1-9]\d*|0)(?:\.\d{1,2})?$/;
        return this.optional(element) || (score.test(value));
    },"请输入大于等于0的整数");

    //合同约定金额限制
    $.validator.addMethod("checkContractPlanAmount",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("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的整数");

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

    //贸易平台报价
    $.validator.addMethod("checkTradePlatformOffer",function(value,element){
        value = value.replace(/,/gi,'')
        var score = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,4})?$/
        return this.optional(element) || (score.test(value));
    },"贸易平台报价格式不正确");

    //保理报价
    $.validator.addMethod("checkFactoringOffer",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("checkMonthlyInterestRate",function(value,element){
        value = value.replace(/,/gi,'')
        var score = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,4})?$/
        return this.optional(element) || (score.test(value));
    },"月利率格式不正确");

    // $.validator.addMethod("checkMonthlyInterestRateNew",function(value,element){
    //     value = value.replace(/,/gi,'')
    //     var score = /^(?:[1-9]\d*|0)(?:\.\d{1,2})?$/
    //     return this.optional(element) || (score.test(value));
    // },"月利率格式不正确");

    //税率
    $.validator.addMethod("checkTaxRate",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));
    },"税率格式不正确");

    //验证付款条件
    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();
        $("#contractEntryForm").validate({
            promptPosition: "bottomLeft",
            submitHandler: function (form) {
                //货物必填验证
                if ($(".goodsListTable .goodsListTbody").length) {
                    $('.goodsListTable .validInput').change();
                } else {
                    new $.zui.Messager('请添加货物信息', {
                        type: 'danger'
                    }).show();
                    return false;
                }
                // 需方发货人
                if($(".demandListTable .demandListTbody").length) {
                    $('.demandListTable .validInput').change();
                }else {
                    new $.zui.Messager('请添加需方收货人信息', {
                        type: 'danger'
                    }).show();
                    return false;
                }
                // 供应商发货人
                if ($(".supplierListTable .supplierListTbody").length) {
                    $('.supplierListTable .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
        });
    };

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

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

    //是否有质保金
    $("[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=hasLimit]").change(function () {
        if ($("[name=hasLimit] option:selected").val() == 0) {
            $(".retentionLimitTr").hide();
            $("[name=hasLimit]").parent().css('width', '0').attr('colspan', 3)
        } else {
            $(".retentionLimitTr").show();
            $("[name=hasLimit]").parent().removeAttr('colspan').css('width', '35%')
        }
    })
    $("[name=hasLimit]").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()

    //利差计算方式变化
    $('[name=accrualMarginCalcMethod]').change(function () {
        if ($('[name=accrualMarginCalcMethod]').val() !== '') {
            if ($('[name=accrualMarginCalcMethod] option:selected').text() == '固定利率') {
                $('.rateTr').show()
                $('.chaTr').hide();
            } else {
                $('.rateTr').hide()
                $('.chaTr').show();
            }
        } else {
            $('.rateTr').hide();
            $('.chaTr').hide()
        }
    })
    $('[name=accrualMarginCalcMethod]').change()

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

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

    // 供应商发货人
    $(".supplierListTable").on("change", ".validInput", function (e) {
        if ($(this).parent().parent().css('display') !== 'none') {
            if ($(this).val() == '') {
                $(this).next().addClass('shows').show();
            } else {
                $(this).next().removeClass('shows').hide();
            }
        }
    })


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

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

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


    // $(".yk_addNewMsg .submitBusiness").click(addNewCustomer);

    //关闭按钮
    $(".yk_addNewMsg .btn-cancel, .newBackBtn").click(function () {
        $.get('/purchContract/list', function (data) {

            $(".yk_rightcontent").empty().append(data);
        });
        return false;
    });


    //释放
    $("#myModal-chooseGoods").on('click', '.chooseGoodsTable .relaseGoods', function () {
        $(this).parents('.choosedGoodsTbody').remove();
        sortChooseGoodsInfo();
        //return false;
    });

    function hideSelectAll() {
        $("#cb_chooseGoodsList").hide();
        return (true);
    }

    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 checkBoxDisabled() {
        $('.goodsListTbody').each(function ( i, ele) {
            if($(ele).attr('id')){
                setTimeout(() => {
                    var nameVal = `jqg_chooseGoodsList_${$(ele).attr('id')}`
                    $(`[name=${nameVal}]`).attr('checked', false)
                    $(`[name=${nameVal}]`).attr('disabled',true)
                }, 300);
            }
        })
    }

    function tablefunction(tableid) {
        var tipword = '', pageid = '', pageNo = 1, postData = {};
        url = '', colNamesArray = [], colModelArray = [];
        switch (tableid) {
            case '#chooseGoodsList':
                tipword = '货物';
                pageid = '#chooseGoodsListPage';
                postData = {
                    'businessKey': $("[name=basicId]").val(),
                    'taskId': $("[name=taskId]").val()
                };
                url = '/purchContract/selectGoods';
                colNamesArray = ['ID', '销售备注', 'supplement', '编号', '名称', '厂家', '型号', '单位', '数量', '销售单价'];
                colModelArray = [
                    {name: 'id', label: 'ID', hidedlg: true, hidden: true, sortable: false, title: false},
                    {name: 'remark', label: '销售备注', hidedlg: true, hidden: true, sortable: false, title: false},
                    {name: 'supplement', label: 'supplement', hidedlg: true, hidden: true, sortable: false, title: false},
                    {name: 'orderNumber', label: '编号', hidedlg: true, width: 50, sortable: false, title: false},
                    {name: 'goodsName', label: '名称', sortable: false, align: 'left', title: false},
                    {name: 'goodsFactory', label: '厂家', sortable: false, align: 'left', title: false},
                    {name: 'modelNumber', label: '型号', sortable: false, align: 'left', title: false},
                    {name: 'units', label: '单位', sortable: false, align: 'left', title: false},
                    {name: 'quantity', label: '数量', sortable: false, align: 'left', title: false},
                    {name: 'salesPrice', label: '销售单价', sortable: false, align: 'left', title: false},
                    // {name: 'operate', label: '操作',sortable:false,align:'left',title:false,formatter:operate},
                ];
                break;
        }
        ;
        sxUtil.jqGrid(tableid, {
            colNames: colNamesArray,
            colModel: colModelArray,
            height: 'auto',
            mtype: 'GET',
            url: url,
            // pager: pageid,
            rowNum: 0,
            rowList: [],
            multiselect: true,
            multiboxonly: true,
            beforeSelectRow: function (rowid, e) {
                var $myGrid = $(this),
                    i = $.jgrid.getCellIndex($(e.target).closest('td')[0]),
                    cm = $myGrid.jqGrid('getGridParam', 'colModel');
                return (cm[i].name == 'cb')
            },
            onSelectAll: function(aRowids,status) {
                checkBoxDisabled()
            },
            rownumbers: false,
            postData: postData,
            // page: pageNo,
            loadError: function () {
                new $.zui.Messager(tipword + '列表加载失败', {
                    type: 'warning'
                }).show();
            }
        }, true);
        $(tableid).trigger('reloadGrid');
    };

    tablefunction('#chooseGoodsList');

    $("#chooseButton").click(function () {
        $('#chooseGoodsList').setGridParam({
            mtype: 'GET',
            url: '/purchContract/selectGoods',
            datatype: 'json',
            postData: {
                'businessKey': $("[name=basicId]").val(),
                'taskId': $("[name=taskId]").val()
            },
            page: 1
        });
        $('#chooseGoodsList').trigger('reloadGrid');
        $("#myModal-chooseGoods").modal("show");
        $("#myModal-chooseGoods").on('shown.zui.modal', function () {
            $(window).resize();
            $("#chooseGoodsList_cb").css({'width': '45', 'padding': '0 0.12rem'})
            $('#chooseGoodsList .jqgfirstrow td:first').css('width', '45')

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

    // 贸理通2.0货物点击确定逻辑
    /* $(".chooseSure").click(function () {
        var ids = $('#chooseGoodsList').jqGrid('getGridParam', 'selarrrow');
        if (ids.length > 0) {
            let goodsListTbodyId = []
            $('.goodsListTbody').each(function ( j, ele) {
                goodsListTbodyId.push($(ele).attr('id'))
            })
            for (var i = 0; i < ids.length; i++) {
                const goodsListTbodyIdStatus = goodsListTbodyId.every(item => item !== ids[i])
                if(goodsListTbodyIdStatus) {
                    var chooseData = $('#chooseGoodsList').jqGrid('getRowData', ids[i]);
                    var trStr = `<tr class="choosedGoodsTbody">
                            <td width="5%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;"></td>
                            <td width="14%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;" supplement=${chooseData.supplement}>` + chooseData.goodsName + `</td>
                            <td width="14%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.goodsFactory + `</td>
                            <td width="14%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.modelNumber + `</td>
                            <td width="13%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.units + `</td>
                            <td width="13%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.quantity + `</td>
                            <td width="13%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.salesPrice + `</td>
                            <td style="display: none">` + chooseData.id + `</td>
                            <td style="display: none" class="remark">` + chooseData.remark + `</td>
                            <td width="10%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;border-right: 1px solid #E8F0F3;"><span class="relaseGoods" style="color: #5AC4FC;cursor: pointer">释放</span></td>
                        </tr>`
                    $(".choosedGoodsList").append(trStr);
                }
            }
        }

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

            var supplierTrClone2 = $(".goodsListTbody:first").clone();
            supplierTrClone2.find('.negativeInformationReduce').show();
            supplierTrClone2.find('.error').hide();
            supplierTrClone2.find('input').val('');
            supplierTrClone2.find('select').val('');
            supplierTrClone2.find('td').eq(1).find('input').attr('supplement', $(ele).find('td').eq(1).attr('supplement'))
            supplierTrClone2.find('td').eq(1).find('input').val($(ele).find('td').eq(1).text())
            supplierTrClone2.find('td').eq(2).find('input').val($(ele).find('td').eq(2).text())
            supplierTrClone2.find('td').eq(3).find('input').val($(ele).find('td').eq(3).text())
            supplierTrClone2.find('td').eq(4).find('input').val($(ele).find('td').eq(4).text())
            supplierTrClone2.find('td').eq(5).find('input').val($(ele).find('td').eq(5).text())
            supplierTrClone2.find('td').eq(6).find('input').val($(ele).find('td.remark').text())
            supplierTrClone2.find('td').eq(1).find('input').attr('goodsId',$(ele).find('td').eq(7).text())
            supplierTrClone2.attr('id', $(ele).find('td').eq(7).text())
            supplierTrClone2.show();
            $('.goodsListTable').append(supplierTrClone2);
            sortIGoodsnfo();

        })
        $("#myModal-chooseGoods").modal("hide");
    }) */

    // 贸理通V3.1货物点击确定逻辑
    $(".chooseSure").click(function () {
        var ids = $('#chooseGoodsList').jqGrid('getGridParam', 'selarrrow');
        if(ids.length) {
            let goodsListTbodyId = []
            $('.goodsListTbody').each(function ( j, ele) {
                goodsListTbodyId.push($(ele).attr('id'))
            })
            const goodList = []
            for (var i = 0; i < ids.length; i++) {

                const goodsListTbodyIdStatus = goodsListTbodyId.every(item => item !== ids[i])
                if(goodsListTbodyIdStatus) {
                    const { quantity } = $('#chooseGoodsList').jqGrid('getRowData', ids[i])
                    // const pattern = /\d+(\.\d+)?/;
                    // const match = quantity.match(pattern);
                    const match = quantity.replace(/<[^>]+>/g, '')
                    goodList.push({
                        ...$('#chooseGoodsList').jqGrid('getRowData', ids[i]),
                        quantity: match
                    })
                }
                // if(goodsListTbodyIdStatus) {
                //     goodList.push($('#chooseGoodsList').jqGrid('getRowData', ids[i]))
                // }else {
                //     new $.zui.Messager('请选择货物', {
                //         type: 'danger'
                //     }).show();
                //     return
                // }
            }
            console.log(goodList, 9999)
            if(goodList.length) {
                calcGoodsTempPrice(goodList)
            }else {
                new $.zui.Messager('货物已全部选择', {
                    type: 'danger'
                }).show();
            }

        }else {
            new $.zui.Messager('请选择货物', {
                type: 'danger'
            }).show();
        }
    })
})

// 排序-需求方收货人-供方收货人
function sortInfo(className, table){
    $(className).each(function(i,ele){
        $(ele).find('td:first span').text(i);
    });
    if( $(className).length <= 1 ){
        $(`${table} .negativeInformationReduce'`).hide();
    }else{
        $(`${table} .negativeInformationReduce`).show();
    };
};


// 需求方收货人-添加
$("#contractEntryForm").on('click','.demandTable #demandAddBtn',function(){
    var supplierTrClone = $(".demandListTbody:first").clone();
    supplierTrClone.find('.negativeInformationReduce').show();
    supplierTrClone.find('.error').hide();
    supplierTrClone.find('input').val('');
    supplierTrClone.find('select').val('');
    supplierTrClone.show();
    $('.demandListTable').append(supplierTrClone);
    sortInfo('.demandListTbody', '.demandTable');
});

// 删除行
$("#contractEntryForm").on('click','.demandTable .negativeInformationReduce',function(){
    $(this).parents('.demandListTbody').remove();
    sortInfo('.demandListTbody', '.demandrTable');
});


// 供应商收货人添加
$("#contractEntryForm").on('click','.supplierTable #supplierAddBtn',function(){
    var supplierTrClone = $(".supplierListTbody:first").clone();
    supplierTrClone.find('.negativeInformationReduce').show();
    supplierTrClone.find('.error').hide();
    supplierTrClone.find('input').val('');
    supplierTrClone.find('select').val('');
    supplierTrClone.show();
    $('.supplierListTable').append(supplierTrClone);
    sortInfo('.supplierListTbody', '.supplierTable');
});

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