/* 
* @Author: anchen
* @Date:   2017-07-14 14:42:33
* @Last Modified by:   anchen
* @Last Modified time: 2017-07-14 15:23:42
*/

$(document).ready(function(){
	contextPath=$("#contextPath").val();
	
	//分享处理
	channelCode=$("#channelCode").val();
	var operationType=$("#operationType").val();
 	var url=$("#webUrl").val()+"/wechat/appUser/execWechatAuth?developId="+$("#developId").val()+"&operationType="+operationType+"&channelCode="+channelCode+"&pageType=fuelVidePage";
 	var imageUrl=$("#imageUrl").val();
 	var title=$("#productCategoriesName").val()+"影视会员仲夏大放血，低至8折";
 	shareAppMessage(title, "超级前台联合"+$("#productCategoriesName").val()+"提供，为您提供专享服务", url, imageUrl);
	 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) : "");
	    };
	init();
    $(".optionamounlist").on("click", "li", function(){
        var _this = $(this);
        _this.addClass("pitchon").siblings("li").removeClass("pitchon");
        calculatedAmount();
    });

    $(".reduce").click(function(){
        var number = parseInt($("#entryaddNumber").val());
        if(number > 1) {
            number --;
        }else {
            number = 1;
        }
         $("#entryaddNumber").val(number);
         calculatedAmount();
    });
    var maxNumber = 100;
    $(".plus").click(function(){
        var number = parseInt($("#entryaddNumber").val());
        if(number < maxNumber){
            number++;
        } else {
            number = maxNumber;
        }
        $("#entryaddNumber").val(number);
        calculatedAmount();
    });
    
    /**
     * 提交充值
     */
    $(".makervipbtn").click(function(){
    	var mobile=$("#mobile").val();
    	if(mobile == null || mobile ==""){
    		layer.open({
    			content : "手机号码不能为空",
    			skin : 'msg',
    			time : 2
    		});
    		$("#mobile").focus();
    		return;
    	}
    	if(!isPhone(mobile)){
    		return;
    	}
    	var productId=$(".pitchon").find("input").attr("id");
    	if(productId=="" || productId==null){
    		layer.open({
    			content : "请选择充值的产品",
    			skin : 'msg',
    			time : 2
    		});
    		return false;
    	}
    	var developId=$("#developId").val();
    	var operationType=$("#operationType").val();
    	var openId=$("#openId").val();
    	var channelCode=$("#channelCode").val();
    	var payWay=$("#payWay").val();
    	var tradeType=$("#tradeType").val();
    	var number=$("#entryaddNumber").val();
    	var contextPath=$("#contextPath").val();
    	if(number=="" || number<=0){
    		layer.open({
    			content : "请填写充值数量",
    			skin : 'msg',
    			time : 2
    		});
    		return false;
    	}
    	$(".makervipbtn").attr("disabled",true);
    	//生成订单
    	$.ajax({
    		type:'POST',
    		url:contextPath+'/wechat/recharge/createOrder',
    		data:{mobile:mobile,productId:productId,
    			developId:developId,openId:openId,tradeType:tradeType,payWay:payWay,type:operationType,channelCode:channelCode
    			,number:number},
    		dataType: 'json',//返回值类型 一般设置为json
    		success: function (data)  //服务器成功响应处理函数
    		{
    			if(data.code == '-1'){
    				layer.open({
    	    			content : data.msg,
    	    			skin : 'msg',
    	    			time : 2
    	    		// 2秒后自动关闭
    	    		});
    				$(".makervipbtn").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 init(){
	var realPrice=$(".pitchon").find(".preferentialPrice").attr("id");
	var entryaddNumber=$("#entryaddNumber").val();
	$(".totalprice").html("¥"+(realPrice*entryaddNumber).formatMoney());
}

//计算金额
function calculatedAmount(){
	var entryaddNumber=$("#entryaddNumber").val();
	if($("#entryaddNumber").val().length==1){
		$("#entryaddNumber").val($("#entryaddNumber").val().replace(/[^1-9]/g,''));
	}else{
		$("#entryaddNumber").val($("#entryaddNumber").val().replace(/\D/g,''));
	} 
	var realPrice=$(".pitchon").find(".preferentialPrice").attr("id");
	if(entryaddNumber>100){
		entryaddNumber=100;
	}
	if(entryaddNumber<0){
		entryaddNumber=1;
	}
	$("#entryaddNumber").val(entryaddNumber);
	$(".totalprice").html("¥"+(realPrice*entryaddNumber).formatMoney());
}

//验证手机号码
function isPhone(val){
	if(val == null || val == "" ){
		layer.open({
			content :"手机号码不能为空",
			skin : 'msg',
			time : 2
		// 2秒后自动关闭
		});
		return false;
	}
	/*中移动手机号码*/
	var PATTERN_CHINAMOBILE = /^1(3[4-9]|5[012789]|8[23478]|4[7]|7[8])\d{8}$/;
	/*联通手机号码*/
	var PATTERN_CHINAUNICOM =/^1(3[0-2]|5[56]|8[56]|4[5]|7[6])\d{8}$/;
	/*电信手机号码*/
	var PATTERN_CHINATELECOM =/^1(3[3])|(8[019])\d{8}$/;
	if(PATTERN_CHINAMOBILE.test(val) || PATTERN_CHINAUNICOM.test(val) || PATTERN_CHINATELECOM.test(val)){
		return true;
	}
	layer.open({
		content :"手机号码格式不正确",
		skin : 'msg',
		time : 2
	// 2秒后自动关闭
	});
	return false;
}

//支付接口
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" ) {
	        	   $("#makervipbtn").attr('disabled',"true");    
	        	   WeixinJSBridge.call('closeWindow');
	        	   $(".makervipbtn").attr("disabled",false);
	           }     
	           else if(res.err_msg == "get_brand_wcpay_request:cancel" ){
	        	   layer.open({
	   	    			content : '您取消了支付，未成功生成订单.',
	   	    			skin : 'msg',
	   	    			time : 4
  	    		   });
	        	   $(".makervipbtn").attr("disabled",false);
	           }
	           else{
	        	   layer.open({
	   	    			content : '调用支付失败(请升级到最新版本或检查网络).',
	   	    			skin : 'msg',
	   	    			time : 4
 	    		   });
	        	   $(".makervipbtn").attr("disabled",false);
	           }
	       }
	   ); 
	}

function searchOrder(){
	var contextPath=$("#contextPath").val();
	var openId=$("#openId").val();
	var developId=$("#developId").val();
	var operationType=$("#operationType").val();
	var channelCode ="0000";
	if(""!=$("#channelCode").val()&&$("#channelCode").val()!=null){
		channelCode=$("#channelCode").val();
	}
	location.href=contextPath+"/wechat/recharge/getRechargeRecord?openId="+openId+"&developId="+developId+"&operationType="+operationType+"&channelCode="+channelCode;	
}