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();
    });

    // 排序-货物
    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 submitFunction(e){
        var postdata = new FormData();

        postdata.append('taskId',$("[name=taskId]").val());
        postdata.append('businessKey',$("[name=basicId]").val());
        postdata.append('purchContractBasicInfo.businessNumber',$("[name=businessNo]").val());
        postdata.append('purchContractBasicInfo.contractNumber',$("[name=contractNumber]").val());
        postdata.append('purchContractBasicInfo.contractName',$("[name=contractName]").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.isLimit',$("[name=limit]").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)+'].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)+'].remark',$(".goodsListTbody").eq(i).find('td').eq(6).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());
        }
        i=null;

        var url = '/purchContract/doAdd',tip='录入';

        $.ajax({
            url:url,
            type:'post',
            data:postdata,
            processData:false,
            contentType:false,
            success:function(data){
                if( data.success ){
                    new $.zui.Messager( tip+'合同成功', {
                        type: 'success'
                    }).show();
                    $.get('/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();
            }
        });
        return false;
    };

    var formRules = {
        'contractNumber':{
            required:true
        },
        'contractName':{
            required:true
        },
        'contractPeriod':{
            required:true
        },
        'contractPlanAmountType':{
            required:true
        },
        'contractPlanAmount':{
            required:true,
        },
        'repurchMethod':{
            required:true
        },

        'deliveryDate':{
            required:true
        },
        'signDate':{
            required:true
        },
        'firstSettleDate':{
            required:true,
        },
        'settleCycleMethodDict':{
            required:true
        },
        'settleCycle':{
            required:true
        },
        'planPaybackDays':{
            required:true
        },
        // 'settleMinAmount':{
        //     required:true,
        // },

        'retention':{
            required:true
        },
        'retentionPercent':{
            required:true
        },
        'limit':{
            required:true
        },
        'retentionLimit':{
            required:true,
        },
        'releaseMethodDict':{
            required:true
        },
        'releaseDate':{
            required:true
        },
        'releaseDays':{
            required:true
        },

        'accrualMarginCalcMethod':{
            required:true
        },
        'tradePlatformOffer':{
            required:true
        },
        'factoringOffer':{
            required:true,
        },
        'factoringFinanceDeadline':{
            required:true
        },
        'startDate':{
            required:true
        },
        'endDate':{
            required:true
        },
        'monthlyinterestRate':{
            required:true
        },
        'differAmount':{
            required:true
        },
    };

    var formMessages = {
        'contractNumber':{
            required:'请输入合同编号'
        },
        'contractName':{
            required:'请输入合同名称'
        },
        '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:'请输入质保金比例'
        },
        'limit':{
            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:'请输入差额'
        },
    };

    //验证付款条件
    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( $('.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=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()

    //利差计算方式变化
    $('[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();
            }
        }

    })
    $(".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 .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 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 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','销售备注','编号','名称','厂家','型号','单位','数量','销售单价','操作'];
                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: '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,
            multiselect: false,
            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':'100','padding':'0 0.12rem'})
                //$('#chooseGoodsList .jqgfirstrow td:first').css('width','100')

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

    });

    $(".chooseSure").click(function () {
        $(".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').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.show();
            $('.goodsListTable').append(supplierTrClone2);
            sortIGoodsnfo();

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


})
