$(function(){
  var productClassifyId=$("#productClassifyId").val();

  //获取卡类
  ajax_doSubmit("/getProductClassifiesList.html","data:",function(data){
    for(var i=0;i<data.length;i++)
    {
      if(productClassifyId==null || productClassifyId=="")
      {
        productClassifyId=data[i].class;
      }
      if(productClassifyId==data[i].class){
        if(data[i].id==1){
        var htmlLi='<div class="clearfix card-type-item active" curLink="/sell.html?type='+data[i].class+'">'+
                  '<img class="card-type-img" src="/static/home/images/index/nav_'+data[i].id+'_icon.png" /><span>'+data[i].name+'</span><span id="newActivity"></span></div>';
        }else{
          var htmlLi='<div class="clearfix card-type-item active" curLink="/sell.html?type='+data[i].class+'">'+
                  '<img class="card-type-img" src="/static/home/images/index/nav_'+data[i].id+'_icon.png" /><span>'+data[i].name+'</span></div>';
        }
        $("#productClassifiesList").append(htmlLi);
      }else{
        var htmlLi='<div class="clearfix card-type-item" curLink="/sell.html?type='+data[i].class+'">'+
                '<img class="card-type-img" src="/static/home/images/index/nav_'+data[i].id+'_icon.png" /><span>'+data[i].name+'</span></div>';
        $("#productClassifiesList").append(htmlLi);
      }
      
    }
  });
  
    getRecycleOperatorsByProductClassifyId(productClassifyId,false);
    getMaxBatchSubmitCount();
    getIsAuthen();
});
//新人活动
$(document).ready(function(){
  $.ajax({
        url: "/isParticipateNewMemberActivity.html",
        data:{_csrf:ctxPath.csrf},
        dataType:'json',
        type: 'POST',
        xhrFields: {
            withCredentials: true
        },
        crossDomain: true,
        beforeSend: function() {},
        success: function(data) {
//          console.log("data",data);
          var newActivity_ = '';
          if(data.code == "000001"){
//            console.log("新人活动没有开启");
          }
          else if(data.code == "000002"){
//            console.log("实名认证信息已参与过新人活动，失去参与活动资格");
          }
          else if(data.code == "000003"){
//            console.log("已销过话费卡，失去参与新人活动资格");
          }
          else if(data.code =='000004'){
//            console.log("未登录");
          //  newActivity = '<span class= "new_activity">（首张按面值回收）</span>';
              //  $("#newActivity").html(newActivity);
          }
          else{
//            console.log("有资格参与新人活动");
           // newActivity = '<span class= "new_activity">（首张按面值回收）</span>';
               // $("#newActivity").html(newActivity);
          }
        },
        complete: function() {
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
//           alert(XMLHttpRequest.status);
        }
    });
})


/**
 * @description: 通过产品类型ID获取它下面的所有运营商信息，即卡种
 */
function getRecycleOperatorsByProductClassifyId(productClassifyId, isOpenCardSortMenu){
    var cardSortItemHtml = '';
    var selectedCardSortItem = '';
    var chooseOperatorId = $("#chooseOperatorId").val();
    //console.log("chooseOperatorId:"+ chooseOperatorId); 
    
	ajax_doSubmit("/getRecycleOperatorsByProductClassifyId.html","data:productClassifyId="+productClassifyId,function(data){
		if(data.length<=0){
		    // $("#cardSortMedia .card-sort-selected").html('<div class="null-data">暂无可支持的卡种</div>');
		    selectedCardSortItem = '<div class="null-data">暂无可支持的卡种</div>';
		}else{
			var opeMaintainHtml = '';
			for(var i = 0; i < data.length; i++) {
				// var icoSrc = data[i].iconUrl.replace("http://renrenxiaoka-resource.oss-cn-shenzhen.aliyuncs.com", ctxPath.staticDomain);
				var icoSrc = data[i].phoneRecycleIcon;				
				if(data[i].maintenanceState === 1){
					opeMaintainHtml = '<span class="color-orange">（维护中）</span>';
				}else{
					opeMaintainHtml = '';
				}
		        cardSortItemHtml += '<a class="list-item '+ ((i == 0  && chooseOperatorId == "") ? 'active' : '') +'" href="javascript:void(0);" sortId="'+ data[i].id +'" productCode="'+data[i].productCode+'" maintenanceState="'+ data[i].maintenanceState +'" onclick="cardSortSelect(this);">' +
		            '<img class="card-sort-img" src="'+icoSrc+'" /><span>'+data[i].name+'</span>' + opeMaintainHtml +
		            '</a>';

		        //没有规定运营商的情况下默认选择第一项
		        if(i == 0 && chooseOperatorId == ""){
		            $("#operatorId").val(data[i].id);

		            selectedCardSortItem = '<div operatorId="'+ data[i].id +'" productCode="'+data[i].productCode+'">' +
		                '<img class="card-sort-img" src="'+icoSrc+'" /><span>'+data[i].name+'</span>' + opeMaintainHtml +
		                '</div>';

		            if(data[i].maintenanceState === 1){
		            	$("#sellSubmitBtn").addClass('no-allowed');
		            }else{
		            	$("#sellSubmitBtn").removeClass('no-allowed');
		            }
		        }

		        //规定了运营商并且和数据的第i项的id一样
		        if(chooseOperatorId != "" && data[i].id == chooseOperatorId){
		            $("#operatorId").val(data[i].id);

		            selectedCardSortItem = '<div operatorId="'+ data[i].id +'" productCode="'+data[i].productCode+'">' +
		                '<img class="card-sort-img" src="'+icoSrc+'" /><span>'+data[i].name+'</span>' + opeMaintainHtml +
		                '</div>';
		        
		            //onlyCardPassFn(2);
		            
		            if(data[i].maintenanceState === 1){
		            	$("#sellSubmitBtn").addClass('no-allowed');
		            }else{
		            	$("#sellSubmitBtn").removeClass('no-allowed');
		            }
		        }
		    }
		}
		
	    if(isOpenCardSortMenu){
	    	if(data.length<=0){	    	
	    		return false;
	    	}
	    	/*------ 测试用的开始 ------*/
	        /*cardSortItemHtml += '<a class="list-item" href="javascript:void(0);" sortId="21" productCode="JW_ALL" onclick="cardSortSelect(this);">' +
	            '<img class="card-sort-img" src="http://192.168.1.100:8080/RenRenXiaoKaMobileResource/template/web/images/common/recyclePageIcon/tape_jwqywk.png" /><span>骏网全业务卡</span>' +
	            '</a>';*/
	        /*------ 测试用的结束 ------*/
	        var cardSortListHtml = '<div class="actionsheet-menu">' +
	            '<div class="actionsheet-header"><h4>请选择卡种</h4><span class="actionsheet-close-btn"><i class="icon-close"></i></span></div>' +
	            '<div class="cardsort-listing" id="cardSortMeun">'+ cardSortItemHtml +'</div>' +
	            '</div>';

	        openActionSheet(cardSortListHtml);

	        //设置选中项
	        var curOpeId = $("#cardSortMedia .card-sort-selected").children("div").attr("operatorId");
	        //console.log("curOpeId:"+ curOpeId);
	        if(curOpeId != ""){
	            $("#cardSortMeun .list-item").each(function(){
	                if($(this).attr("sortId") == curOpeId){
	                    $(this).addClass("active");
	                }else{
	                    $(this).removeClass("active");
	                }
	            });
	        }
	    }else{
	        //设置选中的卡种内容
	        $("#cardSortMedia .card-sort-selected").html(selectedCardSortItem);
	    }

	    getCardRulesByOperatorId($("#operatorId").val());
	    // getRecyclePricesByOperatorId($("#operatorId").val(), false);

	});
}

/**
 * @description: 通过运营商ID获取它下面的卡号、卡密规则；一个运营商可能有多条规则，例如：天宏一卡通
 */
function getCardRulesByOperatorId(operatorId){
	
	ajax_doSubmit("/mgetCardRules.html","data:operatorId="+operatorId,function(data){

		if(data != null && data != "" && data != undefined)
		{
			var html = "";
		    for(var i = 0; i < data.length; i++){
		        if(i == data.length - 1){
		        	if(data[i].cardNumberLength=="" || data[i].cardNumberLength==null || data[i].cardNumberLength==undefined){
                        html += '卡密' + data[i].cardPasswordLength + '位';
                    }else{
                        html += '卡号' + data[i].cardNumberLength + '位，卡密' + data[i].cardPasswordLength + '位';
                    }	           
		        }else{
		        	if(data[i].cardNumberLength=="" || data[i].cardNumberLength==null || data[i].cardNumberLength==undefined){
                        html += '卡密' + data[i].cardPasswordLength + '位，或';
                    }else{
                        html += '卡号' + data[i].cardNumberLength + '位，卡密' + data[i].cardPasswordLength + '位，或';
                    }		           
		        }
		    }
		    
		    if(data.length > 0){
    			if(data[0].cardNumberLength == '-1'){
    				$("#recycleRulesWrap").html('【注意事项】<span id="cardRules"></span>面值一定要选择正确，如造成损失后果自负！');
    				$("#cardlist-tidy-btn").addClass("no-allowed").attr("title", "该卡暂不支持自动整理，请手动整理");
    			}else{
    				$("#recycleRulesWrap").html('【卡密规则】 <span id="cardRules"></span><span id="cardTips">，面值一定要选择正确！不能有误，提交大量错卡一律封号不予解封！</span>');
    				$("#cardlist-tidy-btn").removeClass("no-allowed").attr("title", "");
    			}
    			
    			if(data.length > 1){ // 有多个规则
    				$("#cardNumRule").val('-1');
                    $("#cardPassRule").val('-1');
    			}else{
    				$("#cardNumRule").val(data[0].cardNumberLength);
                    $("#cardPassRule").val(data[0].cardPasswordLength);
    			}
    		}else{
    			// 没有获取到卡密规则
    		}
		    
		    $("#cardRules").html(html);
		    if(operatorId == 105 || operatorId==111){
        			$("#cardRules").html("此卡为账户内寄售，请填写账号和密码,");
					$("#submitWay-selected").html('<p submitWay="1">单卡提交</p>');
					$("#batchMode").hide();
					 $("#singleMode").show();
					onlyCardPassFn(1);
					$("input[name=type]").val(1);
        		}else{
					 $("#submitWay-selected").html('<p submitWay="2">批量提交</p>');
					 
					 $("#singleMode").hide();
					$("#batchMode").show();
					 onlyCardPassFn(2);
					 $("input[name=type]").val(2);
				}
		    // 提示文字处理
    		setProductRuleTip(operatorId);
		    
		    onlyCardPassFn( $.trim($("#type").val()) );
		}
	});
	
}

/**
 * @description: 通过运营商ID获取它下面的所有面值
 */
function getRecyclePricesByOperatorId(operatorId, isOpenCardFaceValueMenu){
	var plat = $.trim($("#submitPlatform").val());
	var stype=$.trim($("#type").val());
	ajax_doSubmit("/getRecyclePricesByOperatorId.html","data:operatorId="+operatorId+"&stype="+stype,function(data){
        if(data != null && data != "" && data != undefined){

            var cardFaceValueItemHtml = '';
            var rateType = "1";	// 默认固定费率类型
            var isMaintainClass = "";
            var maintainHtml = "";
            var curOpeMainState = $("#cardSortMedia .card-sort-selected").children("div").attr('opeMaintance');
            for(var i=0;i<data.length;i++) {
            	if(curOpeMainState === '1'){ // 运营商在维护
            		isMaintainClass = 'price_maintain';
            		maintainHtml = '~维护中';
            	}else{
                    if(data[i].maintenanceState === 1){ // 面值在维护
                        isMaintainClass = 'price_maintain';
                        maintainHtml = '~维护中';
                    }else{
                        isMaintainClass = '';
                        maintainHtml = '';
                    }
                }
            	if(data[i].type == "2"){
					var  recyclePrice="";
						cardFaceValueItemHtml += '<a class="list-item '+isMaintainClass+'" href="javascript:void(0);" priceVal="'+ data[i].price +'" rateType="'+data[i].type+'" parMainTain="'+ data[i].maintenanceState +'" onclick="cardFaceValueSelect(this);">' +
							'<span class="color9">¥'+data[i].price+'  </span><span class="color-orange">'+recyclePrice+'</span>' +
							'<span class="maintance-label">'+ maintainHtml +'</span>' +
							'</a>';
				}else{
					if($("#productClassifyId").val() ==0){
						var  recyclePrice='￥' + parseFloat(data[i].recyclePrice).toFixed(2) + '(回收价)';
						cardFaceValueItemHtml += '<a class="list-item '+isMaintainClass+'" href="javascript:void(0);" priceVal="'+ data[i].price +'" rateType="'+data[i].type+'" parMainTain="'+ data[i].maintenanceState +'" onclick="cardFaceValueSelect(this);">' +
							'<span class="color9">¥'+data[i].price+' / </span><span class="color-orange">'+recyclePrice+'</span>' +
							'<span class="maintance-label">'+ maintainHtml +'</span>' +
							'</a>';
					}else{
						 var  recyclePrice='￥' + parseFloat(data[i].recyclePrice).toFixed(2) + '(回收价)' ;
						 cardFaceValueItemHtml += '<a class="list-item '+isMaintainClass+'" href="javascript:void(0);" priceVal="'+ data[i].price +'" rateType="'+data[i].type+'" parMainTain="'+ data[i].maintenanceState +'" onclick="cardFaceValueSelect(this);">' +
							 '<span class="color9">¥'+data[i].price+' / </span><span class="color-orange">'+recyclePrice+'</span>' +
							 '<span class="maintance-label">'+ maintainHtml +'</span>' +
							 '</a>';
					}
				}

                if(i == 0){
                    // $("#price").val(parseFloat(data[i].price).toFixed(0));//面值默认选中第一项
                    $("#price").val(0);//面值默认不选
                    rateType = data[i].type;
                }
            }

            if(isOpenCardFaceValueMenu){
                var cardFaceValueListHtml = '<div class="actionsheet-menu">' +
                    '<div class="actionsheet-header"><h4>请选择面值</h4><span class="actionsheet-close-btn"><i class="icon-close"></i></span></div>' +
                    '<div class="cardFaceValue-listing" id="cardFaceValueMeun">'+ cardFaceValueItemHtml +'</div>' +
                    '</div>';

                openActionSheet(cardFaceValueListHtml);

                //设置选中项
                var curFaceValue = $("#facevalue-selected").children("p").attr("priceVal");
                console.log("curFaceValue:"+ curFaceValue);
                if(curFaceValue != ""){
                    $("#cardFaceValueMeun .list-item").each(function(){
                        if($(this).attr("priceVal") == curFaceValue){
                            $(this).addClass("active");
                        }else{
                            $(this).removeClass("active");
                        }
                    });
                }
            }

		}else{
            //无数据
            $("#cardFaceValueMeun").html('<div class="null-data">暂无可支持的面值</div>');
            $("#price").val(0);
            $("#recentConsumeDuration").html("");
		}

	},function(){
        //加载中
        $("#cardFaceValueMeun").html('<div class="loading"><img src="/static/home/images/common/loading.gif">加载中，如长时间无法显示请刷新页面</div>');

    });

}

/**
 * @description: 根据运营商及面值获取对应的费率范围信息
 */
function getRateRangeInfo(operatorId, price){
	var plat = $.trim($("#submitPlatform").val());
    ajax_doSubmit("/getRateRangeInfo.html","data:operatorId="+operatorId+"&price="+price+"&submitFrom="+plat,function(data){
    	if(price != "0"){
            if(data != null && data != "" && data != undefined) {
                $("#cardDiscountMedia").removeClass("d-none");
                $("#cardSubmitWayMedia").removeClass("border-bottom-0");
                $("#cardDiscount").attr("placeholder", "允许输入的折扣是" + parseFloat(data.from).toFixed(2) + "%~" + parseFloat(data.end).toFixed(2) + "%");
                $("#discountHidFromId").val(parseFloat(data.from).toFixed(2));
        		$("#discountHidEndId").val(parseFloat(data.end).toFixed(2));
            } else {
                $("#cardDiscountMedia").addClass("d-none");
                $("#cardSubmitWayMedia").addClass("border-bottom-0");
                $("#discountHidFromId").val('');
        		$("#discountHidEndId").val('');
            }
		}
	});
}

/**
 * @description: 获取支持批量提交的最大数量
 */
function getMaxBatchSubmitCount(){
    ajax_doSubmit("/getMaxBatchSubmitCount.html","data:",function(data){
        if(data != null && data != "" && data != undefined && data.code == "000000"){
            $("#maxSubmitCount").html(data.object);
			$("#maxSubmitCounta").html(data.object);
        }else{
            $("#maxSubmitCount").html("0");
        }
	});
}

/**
 * @description: 获取运营商及面值对应的消耗时长
 */
function getRecentConsumeDuration(operatorId, price) {
    ajax_doSubmit("/getRecentConsumeDuration.html","data:operatorId="+operatorId+"&price="+price,function(data){
        if(data != null && data != "" && data != undefined){
            //只有需要用户输入折扣的才显示折扣
            var discountTxt = "";
            if(data.discount != null && data.discount != "" && data.discount != undefined && data.discount != "0" && $("#operatorId").val() == "4"){
                discountTxt = "，输入折扣是"+data.discount+"%";
            }          
            
            if(data.durationMilliSeconds != null && data.durationMilliSeconds != "" && data.durationMilliSeconds != undefined && data.durationMilliSeconds != "0"){                
            	if(operatorId != "5" && operatorId != "6" && operatorId != "7" ){ // 话费卡慢销不显示最近1张消耗时长
            		//$("#recentConsumeDuration").html(data.operatorName+data.price+"元面值最近1张回收成功的卡密"+ discountTxt +"，耗时为"+ meslDurationFormat(data.durationMilliSeconds) +"（仅供参考）");
            	}
            }else{
                $("#recentConsumeDuration").html("");                
            }
            
            if(data.consumptionTime != null && data.consumptionTime != "" && data.consumptionTime != undefined && data.consumptionTime != "0"){
            	if(operatorId != "5" && operatorId != "6" && operatorId != "7" ){ // 话费卡慢销不显示最近N张消耗时长
            		//$("#bathConsumeDuration").show();
            		//$("#bathConsumeDuration").html(data.operatorName+data.price+"元面值最近"+data.consumptionTimeNumber+"张回收成功的卡密，平均每张耗时为"+ meslDurationFormat(data.consumptionTime*1000) +"（仅供参考）");
            	}
            }else{
                $("#bathConsumeDuration").html("");
                $("#bathConsumeDuration").hide();
            }

        }else{
            $("#recentConsumeDuration").html("");
            $("#bathConsumeDuration").html("");
            $("#bathConsumeDuration").hide();
        }
	});
}

/**
 * @description: ajax提交充值卡表单
 */
function ajaxSubmitCardForm(){	
	var limitAmountResult = checkTodayLimitIsEnough();
	if(limitAmountResult){
		var discount = $.trim($("#cardDiscount").val());
	    var discountNum = discount.replace(/[\％%]/g,'').replace(/\s/g,"");
	    $("#cardDiscount").val(discountNum);
	    
	    var productCode = $("#cardSortMedia .card-sort-selected").children("div").attr("productCode");
	    if(productCode === 'JD_E'){
	    	$("#cardPassHid").val($("#cardPass").val().replace(/\W/g, ''));   	
	    }else{
	    	$("#cardPassHid").val($("#cardPass").val());
	    }

		ajax_doSubmit($("#cardForm").attr('action'),"form:cardForm",function(data){			
	        if(data.result == "000000"){
	            layer.open({
	                content: '<p class="ico ico_right">'+data.msg+'</p>'
	                ,btn: '朕知道了'
	                ,yes: function(index){
	                    window.location.reload();
	                }
	            });
			}else{
	            if(data.result == "403"){// 还没有登录
	                document.location.href = ctxPath.domain + "/passport/login/index.html";
	            }else if(data.result == "503"){	// 还没有实名认证
	                noRealNameAuthen(data.msg);
	            }else if(data.result == "000015"){
	            	var minLevel = '初级认证';
	            	var authUrl = ctxPath.domain+'/member/profileManage/realNameAuthen/realNameAuthenInit.do';
					if(parseInt(data.message)===2){
						minLevel = '中级认证';	
						authUrl = ctxPath.domain+'/member/profileManage/realNameAuthen/intermediateAuthen/index.do';
					}else if(parseInt(data.msg)===3){
						minLevel = '高级认证';	
						authUrl = ctxPath.domain+'/member/profileManage/realNameAuthen/seniorAuthen/index.do';
					}
	            	layer.open({
	            		  content: '<p class="ico ico_warn color-red">很抱歉！该产品需要完成'+minLevel+'才能提交，请去完成'+minLevel+'</p>'
	            		  ,btn: ['立即去实名', '取消']
	            		  ,yes: function(index){
	            		      window.location.href= authUrl;	            		      
	            		      layer.close(index);
	            		  }
            		});
	            }else{
	            	//alert("表单信息："+$("#cardForm").serialize());
	                layerInfoTip(data.msg);	                
	            }
			}
	    },function(){
	        layerInfoTip("销卡处理中，请稍候...");
	    });
	}
    
}

/**
 * 获取用户当天限额
 * 返回值如果为空或者或负数就是不限额;如果为0了就是限额用完了
 */
function clearTodayLimit() {//不限额
    $("#todayLimit").html("");
    $("#memberTodayLimit").val("-1");
}
function getIsAuthen(){
	 ajax_doSubmit("/getJuniorAuthenStatus.html","data:",function(data){
		 if(data.object){
			 getMemberLimitAmount();
		 }else{
			 var path="/AuthenInit.html";
			 $("#todayLimit").html('帐号未实名，实名后可提交销卡，<a href="'+path+'">前往实名认证</a>');     
		 }
		});
}
function getMemberLimitAmount(){
	ajax_doSubmit("/getMemberLimitAmount.html","data:",function(data){
		var limitAmount = data.object;
        if(data != null && data != "" && data != undefined){
			if(limitAmount!= null && limitAmount != "" && limitAmount != undefined){
				if(parseFloat(limitAmount)<0){
                    clearTodayLimit();
				}else{
                    $("#todayLimit").html('今天可用额度'+limitAmount+'元');
                    $("#memberTodayLimit").val(limitAmount);
				}
			}else{
                clearTodayLimit();
			}
        }else{
            clearTodayLimit();
        }
	});
}

/**
 * 判断是否超过今日限额
 */
function checkTodayLimitIsEnough(){
    var memberTodayLimit = parseFloat($("#memberTodayLimit").val());
    var totalPrice = "";
    
    var submitWay = $("#type").val();
    if(submitWay=="1"){//单卡提交
    	totalPrice = parseFloat($("#price").val());
    }else if(submitWay=="2"){//批量提交
    	var actualCardNum = parseInt($("#actualCardNum").val());
    	totalPrice = actualCardNum*parseFloat($("#price").val());
    }
    
    if(memberTodayLimit>0){
        if(totalPrice > memberTodayLimit){
        	layerInfoTip('提交失败，本次提交的卡密总面值，超过今天剩余可用额度('+memberTodayLimit+'元)！');           
            return false;
        }else{
            return true;
        }
    }else if(memberTodayLimit==0){//额度已用完
    	layerInfoTip('已到达今天提交限额，请明天再销卡');
        return false;
    }else{//不限额
        return true;
    }
}

