$(function(){
	getRecycleOperatorsByProductClassifyId($("#productClassifyId").val());
	getMaxBatchSubmitCount();
	getMemberLimitAmount();
});

/**
* @description: 通过产品类型ID获取它下面的所有运营商信息
*/
function getRecycleOperatorsByProductClassifyId(productClassifyId)
{
	$.ajax({
        url:ctxPath.domainapi + "/m/recycle/getRecycleOperatorsByProductClassifyId.do",
        data:{productClassifyId:productClassifyId, _csrf:$("input[name='_csrf']").val()},
        dataType: "json",
        async: true,
        type: "POST",
        xhrFields: {
        	withCredentials: true
        },
        crossDomain: true,
        beforeSend: function() {
        	$("#operatorsWrap").html("<div><img valign='middle' src='" + $("meta[name='staticDomain']").attr("content") + "/template/web/images/common/loading.gif'/>&nbsp;加载中，如长时间无法显示请刷新页面</div>");
        },
        success: function(data) {
//        	 console.log("通过产品类型ID获取它下面的所有运营商信息",data);
        	if(data != null && data != "" && data != undefined)
    		{
        		var html = "";
                /*------ 测试用的数据 start ------*/
                /*var html = '<div class="recovery-mode-list data-type-operator" product-code="JW" id="8" maintenanceState="1">' +
                    '<span class="auto-label"><i>自动</i></span>' +
                    '<span class="max-discount"></span>' +
                    '<img src="http://renrenxiaoka-resource.oss-cn-shenzhen.aliyuncs.com/template/web/images/common/recyclePageIcon/jk.png"  alt="" />' +
                    '<i class="max-icon icon-treat"></i><span class="product-name">维护卡</span>' +
                    '</div>';*/
                /*------ 测试用的数据 end ------*/
        		var maintainClass = '';
        		for(var i = 0; i < data.length; i++)
    			{
                    if(i == 0 && $("#chooseOperatorId").val() == "" && data[i].maintenanceState === 1) {
                        maintainClass = 'maintain';
                    }else{
                        maintainClass = '';
                    }
        			html += '<div class="recovery-mode-list data-type-operator ' + ((i == 0  && $("#chooseOperatorId").val() == "") ? 'active' : '') +  ' '+maintainClass+'" product-code="' + data[i].productCode + '" id="' + data[i].id + '" maintenanceState="'+ data[i].maintenanceState +'">' +
								'<span class="auto-label"><i>自动</i></span>' +
                                '<span class="max-discount" id = "maxDiscount"></span>' +
                                '<img src="' + data[i].iconUrl + '"  alt="" />' +
								'<i class="max-icon icon-treat"></i><span class="product-name">'+data[i].name +'</span>' +
							'</div>';

                    if(i == 0 && $("#chooseOperatorId").val() == "") {
                        $("#operatorId").val(data[i].id);
                    }
    			}
        		
        		$("#operatorsWrap").html(html);
        		$("#operatorsWrap .data-type-operator.maintain .max-discount").html('维护');

				//需要判断是否有选择卡种
				if($.cookie('cardType') != null && $.cookie('cardOperator') != null && $.cookie('cardFaceVal') != null){
                    if( productClassifyId == $.cookie('cardType') ){
                        $("#operatorId").val($.cookie('cardOperator'));
                    }
                }

                if($("#chooseOperatorId").val() != ""){
                    $("#operatorId").val($("#chooseOperatorId").val());
                    $(".data-type-operator").each(function(){
                        if($(this).attr("id") == $("#chooseOperatorId").val())
                        {
                            $(this).addClass("active");
                            return false;
                        }
                    });
                }

                // alert("运营商ID："+ $("#operatorId").val());                
        		getCardRulesByOperatorId($("#operatorId").val());        		
        		getRecyclePricesByOperatorId($("#operatorId").val());
    		}
        	else
    		{
        		var html = "";
        		html += '<div class="null-card-data">暂无可支持的卡种</div>';
        		$("#operatorsWrap").html(html);
        		$("#operatorId").val("");
                getRecyclePricesByOperatorId($("#operatorId").val());
    		}
        },
        complete: function() {
        },
        error: function(e) {
        }
    });
}

/**
* @description: 通过运营商ID获取它下面的卡号、卡密规则
*/
function getCardRulesByOperatorId(operatorId)
{
	$.ajax({
        url:ctxPath.domainapi + "/m/recycle/getCardRules.do",
        data:{operatorId:operatorId, _csrf:$("input[name='_csrf']").val()},
        dataType: "json",
        async: true,
        type: "POST",
        xhrFields: {
        	withCredentials: true
        },
        crossDomain: true,
        beforeSend: function() {
        	$("#cardRulesNumber, #cardRulesPassword").html("<img valign='middle' src='" + $("meta[name='staticDomain']").attr("content") + "/template/web/images/common/loading.gif'/>");
        },
        success: function(data) {
//        	console.log("通过运营商ID获取它下面的卡号、卡密规则",data);
        	if(data != null && data != "" && data != undefined){
        		//$("#cardRulesNumber").html(data.cardNumberLength);
        		//$("#cardRulesPassword").html(data.cardPasswordLength);
        		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' || data[0].cardPasswordLength == '-1'){
        				$("#recycleRulesWrap").html("【注意事项】面值一定要选择正确，如造成损失后果自负！");
        				$("#batch .card-operation-btn").addClass("no-allowed").attr("title", "该卡暂不支持自动整理，请手动整理");
        			}else{
        				$("#recycleRulesWrap").html('【卡密规则】 <span id="cardRules"></span><span id="cardTips">；面值一定要选择正确，如造成损失后果自负！</span>');
        				$("#batch .card-operation-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 == '25'){
        			$("#cardRules").html("卡号和卡密都是16位，如果没有卡号，在卡号那里也填卡密");
        		}
        		
        		// 提示文字处理
        		setProductRuleTip(operatorId);        		        	
    		}
        },
        complete: function() {
        	//onlyCardPassFn(2);
        	onlyCardPassFn( $.trim($("#type").val()) );
        },
        error: function(e) {}
    });
}

/**
* @description: 通过运营商ID获取它下面的所有面值
*/
function getRecyclePricesByOperatorId(operatorId){
	$.ajax({
        url:ctxPath.domainapi + "/m/recycle/getRecyclePricesByOperatorId.do",
        data:{operatorId:operatorId,submitFrom:$("#submitPlatform").val(), _csrf:$("input[name='_csrf']").val()},
        dataType: "json",
        async: true,
        type: "POST",
        xhrFields: {
        	withCredentials: true
        },
        crossDomain: true,
        beforeSend: function() {
        	$("#priceWrap").html("<div><img valign='middle' src='" + $("meta[name='staticDomain']").attr("content") + "/template/web/images/common/loading.gif'/>&nbsp;加载中，如长时间无法显示请刷新页面</div>");
        },
        success: function(data) {
        	console.log('通过运营商ID获取它下面的所有面值',data);
            var curOpeMainState = $("#operatorsWrap .data-type-operator.active").attr('maintenancestate');
        	
        	if(data != null && data != "" && data != undefined){
        		var html = "";
        		var rateType = "1";	// 默认固定费率类型
                var discountArr = [];
                var sCardType = $.trim($("#productClassifyId").val());//卡类
                var isActiveClass = "";
                var isMaintainClass = "";
                var maintainHtml = "";
        		for(var i = 0; i < data.length; i++){
                    if(i == 0){
                        if(sCardType=="1" || isOperatorMaintain(curOpeMainState) || data[i].maintenanceState === '1'){//话费卡默认不选择面值、运营商维护时默认不选择面值
                            isActiveClass = '';
                            $("#price").val(0);
                        }else{
                            isActiveClass = 'active';
                            $("#price").val(parseFloat(data[i].price).toFixed(0));
                        }

                        rateType = data[i].type;
                    }else{
                        isActiveClass = '';
                    }

                    if(isOperatorMaintain(curOpeMainState)){ // 运营商在维护
                        isMaintainClass = 'price_maintain';
                        maintainHtml = '维护';
                    }else{
                        if(data[i].maintenanceState === 1){ // 面值在维护
                            isMaintainClass = 'price_maintain';
                            maintainHtml = '维护';
                        }else{
                            isMaintainClass = '';
                            maintainHtml = '';
                        }
                    }

                    // 面值的折扣=（该面值回收价格÷面值）X100
                    var discountStr = round(parseFloat(data[i].recyclePrice).toFixed(2) / parseFloat(data[i].price).toFixed(0) * 100, 2);
                    discountArr.push(discountStr);

        			html += '<div class="recovery-par-list '+ isActiveClass + ' '+isMaintainClass+'" val="' + parseFloat(data[i].price).toFixed(0) + '" type="' + data[i].type + '" parMainTain="'+ data[i].maintenanceState +'">' +
								'<span class="maintain_tag">'+ maintainHtml +'</span>' +
								'<i class="max-icon icon-treat"></i>' +
                                '<p class="m_price">￥' + parseFloat(data[i].price).toFixed(0) + '</p>' +
                                '<p class="m_recycle_price">' + (data[i].type == "1" ? '<i class="txt_orange" id = "txtOrangeVal">('+discountStr+'折)/</i><span class="gray9">￥'+parseFloat(data[i].recyclePrice).toFixed(2)+'</span>' : '<i class="txt_orange">回收价由供货折扣定</i>') + '</p>' +
							'</div>';
    			}
                var maxDiscountVal = Math.max.apply(null, discountArr);

        		if(isOperatorMaintain(curOpeMainState)){
                    $("#operatorsWrap .active .max-discount").html('维护');
                    setSubmitBtnBg(false);
                }else{
                    $("#operatorsWrap .active .max-discount").html(maxDiscountVal+'折');
                    var choosedPriceMainObj = $("#priceWrap .recovery-par-list.active");
                    if(choosedPriceMainObj.hasClass('price_maintain')){
                        setSubmitBtnBg(false);
                    }else{
                        setSubmitBtnBg(true);
                    }
                }

        		$("#priceTip").html($("#price").val());
        		$("#priceWrap").html(html);

        		// 如果是区间费率，则查询该区间费率的信息
        		if(rateType == "2") {
        			getRateRangeInfo($("#operatorId").val(), $("#price").val());
    			} else {
        			$("#discountWrap").css("display", "none");
        			$("#discountHidFromId").val('');
            		$("#discountHidEndId").val('');
    			}
                //获取上次提交成功的cookie
                initPageFromCookie(operatorId);

    		} else {
        		var html = "";
        		html += '<div class="null-card-data">暂无可支持面值</div>';
        		$("#priceWrap").html(html);
        		$("#price").val(0);
                $("#operatorsWrap .active .max-discount").hide();
        		$("#recentConsumeDuration").html("");
    		}
        	getrecycleIsParticipate();
        },
        complete: function() {
            // 所有面值均维护时，提交按钮为灰色
            var aPar = $("#priceWrap .recovery-par-list");
            var mArr = [];
            for(var j=0;j<aPar.length;j++){
                if(aPar.eq(j).hasClass('price_maintain')){
                    mArr.push(aPar.eq(j));
                }
            }
            if(mArr.length === aPar.length){
                setSubmitBtnBg(false);
            }else{
                setSubmitBtnBg(true);
            }

            //获取消耗时长
            getRecentConsumeDuration($("#operatorId").val(), $("#price").val());
        },
        error: function(e) {}
    });
}

/**
* @description: 获取支持批量提交的最大数量
*/
function getMaxBatchSubmitCount()
{
	$.ajax({
        url:ctxPath.domainapi + "/m/recycle/getMaxBatchSubmitCount.do",
        data:{_csrf:$("input[name='_csrf']").val()},
        dataType: "json",
        async: true,
        type: "POST",
        xhrFields: {
        	withCredentials: true
        },
        crossDomain: true,
        beforeSend: function() {
        	$("#maxSubmitCount").html("<img valign='middle' src='" + $("meta[name='staticDomain']").attr("content") + "/template/web/images/common/loading.gif'/>");
        },
        success: function(data) {
        	//console.log(data);
        	if(data != null && data != "" && data != undefined && data.code == "000000")
    		{
        		$("#maxSubmitCount").html(data.object);
    		}
        	else
    		{
        		$("#maxSubmitCount").html("0");
    		}
        },
        complete: function() {
        },
        error: function(e) {
        }
    });
}

/**
* @description: 获取运营商及面值对应的费率范围信息
*/
function getRateRangeInfo(operatorId, price)
{
	$.ajax({
        url:ctxPath.domainapi + "/m/recycle/getRateRangeInfo.do",
        data:{operatorId:operatorId, price:price,submitFrom:$("#submitPlatform").val(), _csrf:$("input[name='_csrf']").val()},
        dataType: "json",
        async: true,
        type: "POST",
        xhrFields: {
        	withCredentials: true
        },
        crossDomain: true,
        beforeSend: function() {
        },
        success: function(data) {
        	//console.log(data);
        	if(data != null && data != "" && data != undefined)
    		{
        		$("#discountWrap").css("display", "block");
        		$("#cardDiscount").attr("placeholder", "允许输入的折扣是" + parseFloat(data.from).toFixed(2) + "%到" + parseFloat(data.end).toFixed(2) + "%");
        		$("#discountTip").html("可以输入的折扣值：" + 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
    		{
        		$("#discountWrap").css("display", "none");
        		$("#discountHidFromId").val('');
        		$("#discountHidEndId").val('');
    		}
        },
        complete: function() {
        },
        error: function(e) {
        }
    });
}

/**
 * @description: 获取运营商及面值对应的消耗时长
 */
function getRecentConsumeDuration(operatorId, price) {
    // console.log("获取运营商及面值对应的消耗时长，运营商ID："+operatorId+";面值："+price);
    $.ajax({
        url:ctxPath.domainapi + "/m/recycle/getRecentConsumeDuration.do",
        data:{operatorId:operatorId, price:price, _csrf:$("input[name='_csrf']").val()},
        dataType: "json",
        async: true,
        type: "POST",
        xhrFields: {
        	withCredentials: true
        },
       	crossDomain: true,
        beforeSend: function() {},
        success: function(data) {
            // console.log("消耗时长："+ JSON.stringify(data));
            if(data != null && data != "" && data != undefined && data.price !="0") {
                //只有需要用户输入折扣的才显示折扣
                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").show();
                        $("#recentConsumeDuration").html(data.operatorName+data.price+"元面值最近1张回收成功的卡密"+ discountTxt +"，耗时为"+ meslDurationFormat(data.durationMilliSeconds) +"（仅供参考）");
                    }
                }else{
                    $("#recentConsumeDuration").html("");
                    $("#recentConsumeDuration").hide();
                }

                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("");
                $("#recentConsumeDuration").hide();
                $("#bathConsumeDuration").html("");
                $("#bathConsumeDuration").hide();
            }
        },
        complete: function() {},
        error: function(e) {}
    });
}

/**
 * @description: 读取cookie中的数据初始化页面
 */
function initPageFromCookie(operatorId) {
//    console.log("页面初始化：cardType="+ $.cookie('cardType') +";cardOperator="+ $.cookie('cardOperator') +";cardFaceVal="+ $.cookie('cardFaceVal') +";operatorId:"+operatorId);
    if($.cookie('cardType') != null && $.cookie('cardOperator') != null && $.cookie('cardFaceVal') != null){
        if( $.trim($("#productClassifyId").val()) == $.cookie('cardType') ){
            //判断是否有选择运营商
            if($("#chooseOperatorId").val() == ""){
                // console.log("选择记住的卡种及面值");
                selectOperatorByCookie(operatorId);
                if($.cookie('cardOperator') == operatorId){
                    selectFaceValByCookie($.cookie('cardFaceVal'));
                }

            }else{
            	if($.cookie('cardOperator') == operatorId){
                    //console.log("选择记住的面值");
                    selectFaceValByCookie($.cookie('cardFaceVal'));

				}

            }

        }
    }
}

function selectOperatorByCookie(cardOperator){
    $("#operatorId").val(cardOperator);
    $("#operatorsWrap .data-type-operator").each(function(){
        if($(this).attr("id") == cardOperator){
            $(this).addClass("active");
        }else{
            $(this).removeClass("active");
        }
    });
}

function selectFaceValByCookie(cardFaceVal){
    $("#price").val(cardFaceVal);
    $("#priceTip").html(cardFaceVal);
    $("#priceWrap .recovery-par-list").each(function(){
        if($(this).attr("val") == cardFaceVal){
            $(this).addClass("active");
        }else{
            $(this).removeClass("active");
        }
    });
}

/**
 * 获取用户当天限额
 * 返回值如果为空或者或负数就是不限额;如果为0了就是限额用完了
 */
function clearTodayLimit() {//不限额
    $(".card-recovery-limit").html("");
    $("#memberTodayLimit").val("-1");
}
function getMemberLimitAmount(){
	var memberNumber = $.trim($("#memberNumber").val());
	if(memberNumber!=""&&memberNumber!=null&&memberNumber!=undefined){
		$.ajax({
	        url: ctxPath.domainapi + "/recycle/getMemberLimitAmount.do",
	        data:{_csrf:$("input[name='_csrf']").val()},
	        dataType:'json',
	        type: 'POST',
	        xhrFields: {
	        	withCredentials: true
	        },
	        crossDomain: true,
	        beforeSend: function() {},
	        success: function(data) {
	        	var limitAmount = data.object;
	            if(data != null && data != "" && data != undefined){
					if(limitAmount!= null && limitAmount != "" && limitAmount != undefined){
						if(parseFloat(limitAmount)<0){
	                        clearTodayLimit();
						}else{
	                        $(".card-recovery-limit").html('今天可用额度'+limitAmount+'元');
	                        $("#memberTodayLimit").val(limitAmount);
						}
					}else{
	                    clearTodayLimit();
					}
	            }else{
	                clearTodayLimit();
	            }
	        },
	        complete: function() {},
	        error: function(XMLHttpRequest, textStatus, errorThrown) {}
	    });
	}
   
}
/**
 * 获取新人活动有没有开启
 */
function getrecycleIsParticipate(){
	$.ajax({
        url: ctxPath.domainapi + "/recycle/isParticipateNewMemberActivity.do",
        data:{_csrf:ctxPath.csrf},
        dataType:'json',
        type: 'POST',
        xhrFields: {
            withCredentials: true
        },
       	crossDomain: true,
        beforeSend: function() {},
        success: function(data) {
//        	console.log("获取新人活动有没有开启",data);
        	var yellowTag = '';
        	var activityTips = '';
        	var maxDiscount = '';
        	
        	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("未登录");
        		activityTips = '<div class="triangle_border_left"><span></span></div><span class="retrieve-span">新用户注册，首张话费卡按面值回收</span>	<a class="retrieve-detail" href="' + $("meta[name='domain']").attr("content") +'/retrieveActivity/retrieve.html"><span>查看活动详情</span></a>'
                $("#activityTips").html(activityTips);
        	}
        	else{
//        		console.log("有资格参与新人活动");
        		yellowTag = '<em class = "yellow-tag"></em>'
                $("#yellowTag").html(yellowTag);
        		activityTips = '<div class="triangle_border_left"><span></span></div><span class="retrieve-span">新用户注册，首张话费卡按面值回收</span>	<a class="retrieve-detail" href="' + $("meta[name='domain']").attr("content") +'/retrieveActivity/retrieve.html"><span>查看活动详情</span></a>'
                $("#activityTips").html(activityTips);
//        		判断是否为话费卡
        		if($("#productClassifyId").val()==1){
        			$("#operatorsWrap .max-discount").html('100折');
            		$(".txt_orange").html('按面值回收/');
            		$(".gray9").css("text-decoration","line-through");
        		}
        	}
        },
        complete: function() {
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
//           alert(XMLHttpRequest.status);
        }
    });
}


