/* 
* @Author: anchen
* @Date:   2017-07-14 14:04:54
* @Last Modified by:   anchen
* @Last Modified time: 2017-07-14 14:26:58
*/

var currentScode="";	//当前产品类型
var contextPath="";
var channelCode="";

$(document).ready(function(){
	contextPath=$("#contextPath").val();
	
	//分享处理
	channelCode=$("#channelCode").val();
 	var url=$("#webUrl").val()+"/wechat/appUser/execWechatAuth?developId="+$("#developId").val()+"&pageType=fuelChargePage"+"&channelCode="+channelCode+"&operationType=JYK";
 	var imageUrl=$("#webUrl").val()+"/images/visitor/log.png?v=1.0";
 	var title="男神专享，为自己加油，请接力99折";
 	shareAppMessage(title, "超级前台联合中石化中石油推出，为您提供专享服务", url, imageUrl);

    // 选择加油卡供应商
    $(".cardlist").on("click", "li", function(){
        var _this = $(this);
        _this.addClass("fuelcard").siblings("li").removeClass("fuelcard");
        
        //切换不同供应商，重新查询产品信息
        currentScode=_this.attr("sCode");
        initEntrycardRemak(currentScode);
        
        queryProduce(currentScode);
        
        //初始化输入框
        $("#cardCode").val("");
        $("#sbBtn").attr("class","fuelbtn fuelbtn-disable");
    });
    // 输入卡号
    $('#cardCode').bind('input propertychange', function() {
		var cardCode = $("#cardCode").val();
		if(!validateCardCode(cardCode, currentScode)){
			$("#sbBtn").attr("class","fuelbtn fuelbtn-disable");
		}
		else{
			$("#sbBtn").attr("class","fuelbtn js_fuelbtn");
		}
	});

    // 选择加油卡充值面额
    $(".fuelprice").on("click", "li", function(){
        var _this = $(this);
        _this.addClass("fuelpitchon").siblings("li").removeClass("fuelpitchon");
        
        var cardCode = $("#cardCode").val();
        if(validateCardCode(cardCode, currentScode)){
        	//充值按钮启用
        	$("#sbBtn").attr("class","fuelbtn js_fuelbtn");
        }
    });

 	//初始化产品信息
 	currentScode=$(".fuelcard").attr("sCode");
 	
 	initEntrycardRemak(currentScode);
 	
 	queryProduce(currentScode);
});

String.prototype.startWith=function(str){     
  var reg=new RegExp("^"+str);     
  return reg.test(this);        
}

Number.prototype.formatMoney = function (places, symbol, thousand, decimal) {
    places = !isNaN(places = Math.abs(places)) ? places : 2;
    symbol = symbol !== undefined ? symbol : "";
    thousand = thousand || ",";
    decimal = decimal || ".";
    var number = this,
        negative = number < 0 ? "-" : "",
        i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
};

//充值提交按钮
function submitOrder(){
    var cardCode=$("#cardCode").val();
    var productId=$(".fuelpitchon").attr("proId");
    if(!validateCardCode(cardCode,currentScode)){
    	showMessage("加油卡号码格式不对，请检查");
    	return;
    }
    if(productId==null||productId==""){
    	showMessage("请选择产品");
    	return;
    }
    var developId = $("#developId").val();
	var openId = $("#openId").val();
	$("#sbBtn").attr("disabled",true);
	//生成订单
	$.ajax({
		type:'POST',
		url:contextPath+'/wechat/recharge/createOrder',
		data:{mobile:cardCode,productId:productId,developId:developId,openId:openId,
				tradeType:"JSAPI",payWay:"wxpay",type:currentScode,channelCode:channelCode,number:"1"},
		dataType: 'json',
		success: function (data){
			console.log(data);
			if(data.code == '-1'){
				layer.open({
	    			content : data.msg,
	    			skin : 'msg',
	    			time : 2
	    		});
				$("#sbBtn").attr("disabled",false);
			}
			if(data.code == '200'){
				var obj= eval('(' + data.rechargePayStr + ')');
				onBridgeReady(obj.returnDTO.appId,obj.returnDTO.timeStamp,obj.returnDTO.nonceStr,obj.returnDTO.paySign,obj.returnDTO.package);
			}
		}
	});
}

//根据类型查询产品列表信息
function queryProduce(productType){
	$.ajax({
		type:'POST',
		url:contextPath+"/wechat/recharge/findProduct",
		data:{"mobile":"","operationType":currentScode},
		dataType: "json",
		async : false,
		beforeSend: function( xhr ) {
			layer.open({
			    type: 2,
			    content:"加载中"
			});
		},
		success: function (data){
			var subs = data.list;// 获取data中list的数组
			if(subs!=null&&subs.length>0){
				$(".entrycard").show();
				$(".fuelprice").show();
				$(".nogoods").hide();
				var container=$("#container");
				container.html("");
				var containerHtmlStr="";
				$.each(subs,function(index,obj){
					if(index==0){
						containerHtmlStr+="<li class='fuelpriceitem  fuelpitchon' proId="+obj.id+" ><span>"+obj.productName+"</span> <em>售价"+jisuan(obj.realPrice)+"元</em></li>";
					}
					else{
						containerHtmlStr+="<li class='fuelpriceitem' proId="+obj.id+" ><span>"+obj.productName+"</span> <em>售价"+jisuan(obj.realPrice)+"元</em></li>";
					}
				});
				container.html(containerHtmlStr);
			}
			else{
				$(".fuelprice").hide();
				$(".nogoods").show();
				//充值按钮禁用
				$("#sbBtn").attr("class","fuelbtn fuelbtn-disable");
				//充值卡号区域
				$(".entrycard").hide();
			}
			layer.closeAll();
		}
	});
}

//初始化提示文字
function initEntrycardRemak(productType){
	//中石化
	if("SINOPEC"==productType){
		$(".entrycard span").html("请输入19位加油卡号");
	}
	//中石油
	else if("CNPC"==productType){
		$(".entrycard span").html("请输入16位加油卡号");
	}
}

//验证充值卡格式
function validateCardCode(cardCode,productType){
	var checkFlag=false;
	if(cardCode!=null&&cardCode!=""){
		//中石化
		if("SINOPEC"==productType){
			if(cardCode.length==19&&cardCode.startWith("100011")){
				checkFlag=true;
			}
		}
		//中石油
		else if("CNPC"==productType){
			if(cardCode.length==16&&cardCode.startWith("9")){
				checkFlag=true;
			}
		}
		else{
			checkFlag=true;
		}
	}
	return checkFlag;
}

//格式化费用
function jisuan(realPrice){
	var realPrice_ = Math.floor(realPrice * 100) / 100;
	return realPrice_.formatMoney();
}

//支付接口
function onBridgeReady(appId,timeStamp,nonceStr,paySign,packageStr){
	   WeixinJSBridge.invoke(
	       'getBrandWCPayRequest', {
	       "appId":appId,     			//公众号名称，由商户传入     
	       "timeStamp":timeStamp,      	//时间戳，自1970年以来的秒数     
	       "nonceStr":nonceStr, 		//随机串     
	       "package":packageStr,     
	       "signType":"MD5",         	//微信签名方式：     
	       "paySign":paySign 			//微信签名 
	       },
	       function(res){     
	    	   // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
	    	   if(res.err_msg == "get_brand_wcpay_request:ok" ) {
	    		   $("#sbBtn").attr("disabled",false);    
	        	   WeixinJSBridge.call('closeWindow');
	           }     
	           else if(res.err_msg == "get_brand_wcpay_request:cancel" ){
	        	   $("#sbBtn").attr("disabled",false);
	        	   layer.open({
	   	    			content : '您取消了支付，未成功生成订单.',
	   	    			skin : 'msg',
	   	    			time : 4
	    		   });
	           }
	           else{
	        	   $(".#bBtn").attr("disabled",false);
	        	   layer.open({
	   	    			content : '调用支付失败(请升级到最新版本或检查网络).',
	   	    			skin : 'msg',
	   	    			time : 4
	    		   });
	           }
	       }
   ); 
}
