/* 
* @Author: anchen
* @Date:   2017-07-06 14:48:06
* @Last Modified by: yubing
* @Last Modified time: 2017-07-07 16:30:31
*/
var contextPath;
var visitPrefix;
var userId;			//用户ID
var virtualId;		//企业ID
var imageArray=new Array();

$(document).ready(function(){
	contextPath=$("#contextPath").val();
	visitPrefix=$("#visitPrefix").val();
	userId=$("#userId").val();
	virtualId=$("#virtualId").val();
	
	var status=$("#status").val();
	if("1"==status){
		$("#alertMsg").show();
		$("#alertMsg em").html("您当前已在"+$("#appUserVname").val()+"认证，提交申请后原认证信息将失效");
	}
	
	$(".iconwhat").click(function(event) {
		$(".tips-mask").show();
	});
	$(".tip-btn a").click(function(event) {
		$(".tips-mask").hide();
	});
	
	 /*
     * js手机号码正则校验
     * value -- 获取手机号
     */
    function checkTel(value){
        //var isMob=/^(?:13\d|15\d|18\d|17\d|14\d)-?\d{5}(\d{3}|\*{3})$/; //手机号码
        var isMob=/^(?:13\d|15\d|18\d|17\d|14\d|19\d|16\d)-?\d{5}(\d{3}|\*{3})$/; //手机号码
		if(!(isMob.test(value))){
			 return false;
		}
		else{
			 return true;
		}
    }
    
    //点击获取验证码
    $(".vericode").click(function(event){
    	var telVal  = $("#userMobile").val();
    	if(!telVal) {
    		showMessage("请输入正确的手机号");
        }
    	else{
    		time(this);
    		var contextPath=$("#contextPath").val();
    		$.ajax({
    	    	url: contextPath+"/wechat/sms/getAuthCode",
    	    	data: {
	    			userMobile:telVal,
	    			openId: $("#openId").val(),
	    			orgId: sessionStorage.getItem("orgId")
	    		},
    	        type: "POST",
    	        dataType: "json",
    	        success: function(json){
    	        },
    	        error: function(){
    	        }
    	    });	
    	}
    });
    
    //确定操作
    $("#sureBtn").click(function(){
    	$(".popupmask").hide();
    	WeixinJSBridge.call("closeWindow"); 
    })
    
      //确定操作
    $("#configBtn").click(function(){
    	$(".popupmask").hide();
    })
    
    //提交认证
    $(".superbtn").click(function(){
    	$(".superbtn").attr("disabled","disabled");
    	
    	var openId=$("#openId").val();
    	var developId=$("#developId").val();
 	   	var virtualId=$("#virtualId").val();
 	   	var manageUserId=$("#manageUserId").val();
 	   	var userId=$("#userId").val();
 	   	var userName=$("#userName").val();
 	   	if($.trim(userName)==""){
 	   		showMessage("请填写您的姓名");
 	   		$(".superbtn").removeAttr("disabled");
 	   		return
 	   	}
 	   	
 		var userMobile=$("#userMobile").val();
 	   	var authCode=$("#authCode").val();
 	   	if(userId==null||userId==""){
 	   		if($.trim(userMobile)==""){
 	   			showMessage("请填写您的手机号");
 	   			$(".superbtn").removeAttr("disabled");
	   			return
 	   		}
 	   		if($.trim(authCode)==""){
 	   			showMessage("请填写验证码");
 	   			$(".superbtn").removeAttr("disabled");
 	   			return;
 	   		}
 	   	}
 	   	var dataUrl=$("#dataUrl").val();
 	   	var faceImage=$("#faceImage").val();	//头像
 	   	var zhengjianImage="";					//证件照
 	   	$(".number").each(function(){
 	   		if($(this).val()!=1){
 	   			var number=$(this).val();
 	   			zhengjianImage+=$("#heard_"+number).val()+";";
 	   		}
 	   	});
 	   	$.ajax({
	    	url: contextPath+"/wechat/memberManage/assignJoinCompay",
	    	data: {openId:openId,developId:developId,virtualId:virtualId,manageUserId:manageUserId,userId:userId,
	    		name:userName,zhengjianImage:zhengjianImage,headRelativeUrl:faceImage,dataUrl:dataUrl,
	    		userMobile:userMobile,authCode:authCode},
	        type: "POST",
	        dataType: 'json',
	        success: function(data){
	        	var flag=data.flag;
	        	if("success"==flag){
	        		$("#sureMsg").show();
	        	}
	        	else{
	        		showMessage(data.resultDesc);
	        	}
	        },
	        error: function(){
	        	$(".superbtn").removeAttr("disabled");
	        	showMessage("请检查网络，提交失败");
	        }
	    });	
    });
	
});

/**
 * 上传图片
 * @param val
 * @param fileObj
 */
function selectFileImage(fileObj,id,paramDiv) {
    var file = fileObj.files['0'];  
    var Orientation = null;  
    if (file) {  
        console.log("正在上传,请稍后...");  
        var rFilter = /^(image\/jpeg|image\/png)$/i; // 检查图片格式  
        if (!rFilter.test(file.type)) {  
            //showMyTips("请选择jpeg、png格式的图片", false);  
            return;  
        }  
        // var URL = URL || webkitURL;  
        //获取照片方向角属性，用户旋转控制  
        EXIF.getData(file, function() {  
           // alert(EXIF.pretty(this));  
            EXIF.getAllTags(this);   
            //alert(EXIF.getTag(this, 'Orientation'));   
            Orientation = EXIF.getTag(this, 'Orientation');  
            //return;  
        });  
          
        var oReader = new FileReader();  
        oReader.onload = function(e) {  
            //var blob = URL.createObjectURL(file);  
            //_compress(blob, file, basePath);  
            var image = new Image();  
            image.src = e.target.result;  
            image.onload = function() {  
                var expectWidth = this.naturalWidth;  
                var expectHeight = this.naturalHeight;  
                  
                if (this.naturalWidth > this.naturalHeight && this.naturalWidth > 800) {  
                    expectWidth = 800;  
                    expectHeight = expectWidth * this.naturalHeight / this.naturalWidth;  
                } else if (this.naturalHeight > this.naturalWidth && this.naturalHeight > 1200) {  
                    expectHeight = 1200;  
                    expectWidth = expectHeight * this.naturalWidth / this.naturalHeight;  
                }  
                var canvas = document.createElement("canvas");  
                var ctx = canvas.getContext("2d");  
                canvas.width = expectWidth;  
                canvas.height = expectHeight;  
                ctx.drawImage(this, 0, 0, expectWidth, expectHeight);  
                var base64 = null;
                var clearBase64=null;
                var mpImg = new MegaPixImage(image);  
                mpImg.render(canvas, {  
                    maxWidth: 800,  
                    maxHeight: 1200,  
                    quality: 0.6,  
                    orientation: Orientation  
                }); 
                base64 = canvas.toDataURL("image/jpeg", 0.6);  
                if(base64!=null){
                	clearBase64=base64.substr( base64.indexOf(',') + 1 )
                }
                addImage(base64,clearBase64,paramDiv,id);
            };  
        };  
        oReader.readAsDataURL(file);  
    }  
}

/**
 * 动态添加图片
 * @param base64
 * @param clearBase64
 * @param id
 */
function addImage(base64,clearBase64,paramDiv,id){
	if(paramDiv=="uploadDiv"){
		validateImage(base64,clearBase64,paramDiv);
	}else{
		if(id==1){
			$(".number").each(function(){
				if($(this).val()!=1){
					imageArray.push($(this).val());
				}
			});
			var number=1;
			if(imageArray.length==0){
				number+=1;
			}else{
				number=Number(Math.max.apply(null, imageArray))+ 1;
			}
			uploadImage(base64,clearBase64,number,paramDiv,id);
		}
		else{
			uploadImage(base64,clearBase64,number,paramDiv,id);
		}
		$("#file_1").val('');
	}
}

/**
 * 删除图片
 */
function delImage(id,paramDiv){
	if(paramDiv=="uploadDiv"){
		var addHtml="<div class='addButton' id='addButton'>";
		addHtml+="<img src='../../images/userlogin/addimg.png' class='js_prevImg'  />";
		addHtml+=" <i class='prev-del' style='display: none;'></i>";
		addHtml+="<input type='hidden' id='faceImage' value='' class='headImage'>"
		addHtml+=" <input  type='file' accept='image/*' capture='camera' class='entryImgInput' onchange='selectFileImage(this,1,\"" + paramDiv+ "\")'/>";
		addHtml+="</div>";
		$("#uploadDiv").html(addHtml);
	}else{
		$("#headUrl_"+id).remove();
		var addButtonSize=$(".addButtons").length;
		if(addButtonSize<4){
			$("#headUrl_1").show();
		}
		imageArray.splice(imageArray.indexOf(id),1);
	}
}

/**
 * 验证头像是否是人脸
 * @param Base64
 * @param clearBase64
 * @returns
 */
function validateImage(Base64,clearBase64,paramDiv){
	$.ajax({
		url:$("#contextPath").val()+"/wechat/visitor/validateImage",
		type:"POST",
		dataType:"json",
		data:{imageUrl:clearBase64},
		timeout:100000,
		beforeSend: function( xhr ) {
			layer.open({
			    type: 2
			    ,content:'上传图片中'
			  });
		  },
		success : function(data) {
			layer.closeAll();
			if(data.flag){
				 var html="<img src='"+ data.url+"' class='js_prevImg'>";
				 	html+="<input type='hidden' value='"+data.url+"' class='headImage' id='dataUrl'>";
					html+=" <i class='prev-del' style='display: block;' onclick='delImage(0,\"" + paramDiv+ "\")' ></i>";
					html+="<input type='hidden' value='"+data.imageUrl+"' class='headImage' id='faceImage'>"
					html+="<input type='hidden' value='"+data.id+"' class='headImage' id='imageFacePlusId'>"
					html+=" <input id='headImage' type='file' accept='image/*' capture='camera' class='entryImgInput' onchange='selectFileImage(this,1,\"" + paramDiv+ "\")'/>";
					$("#addButton").html(html);
        	}else{
        		layer.open({
        		    content: data.desc,
        		    skin: 'msg',
        		    time: 2 //2秒后自动关闭
        		});
        		var addHtml="<div class='addButton' id='addButton'>";
        		addHtml+="<img src='../../images/userlogin/addimg.png' class='js_prevImg'  />";
        		addHtml+=" <i class='prev-del' style='display: none;'></i>";
        		addHtml+="<input type='hidden' id='faceImage' value='' class='headImage'>"
        		addHtml+="<input type='hidden' id='imageFacePlusId' value='' class='headImage'>"
        		addHtml+=" <input  type='file' accept='image/*' capture='camera' class='entryImgInput' onchange='selectFileImage(this,1,\"" + paramDiv+ "\")'/>";
        		addHtml+="</div>";
        		$("#uploadDiv").html(addHtml);
        	}
		}, error : function(xhr,textStatus){
			
	    }
	});
}

/**
 * 上传图片
 * @param Base64
 * @param clearBase64
 * @returns {String}
 */
function uploadImage(base64,clearBase64,number,paramDiv,id){
	$.ajax({
		url:$("#contextPath").val()+"/wechat/appUser/uploadImage",
		type:"POST",
		data:{imageUrl:clearBase64},
		timeout:100000,
		beforeSend: function( xhr ) {
			layer.open({
			    type: 2
			    ,content:'上传图片中'
			  });
		  },
		success : function(data) {
			layer.closeAll();
			if(id==1){
				var html="<div class='addButtons' id='headUrl_"+number+"'>";
				html+="<img src='"+base64+"' class='js_prevImg' id='js_prevImg_"+number+"'>";
				html+=" <i class='prev-del' style='display: block;' onclick='delImage("+number+",\"" + paramDiv+ "\")'></i>";
				html+="<input type='hidden' class='number' value='"+number+"'/>"
				html+="<input type='hidden' id='heard_"+number+"' value='"+data+"' class='headImage'>";
				html+=" <input type='file' id='file_"+number+"' accept='image/*' capture='camera' class='entryImgInput' onchange='selectFileImage(this,"+number+",\"" + paramDiv+ "\")'/>";
				html+="</div>"
				$("#headUrl_1").before(html);
				var addButtonSize=$(".addButtons").length;
				if(addButtonSize==4){
					$("#headUrl_1").hide();
				}
				imageArray.push(number);
			}else{
				$("#heard_"+id).val(data);
				$("#js_prevImg_"+id).attr("src",base64);
			}
			
		}, error : function(xhr,textStatus){
			
	    }
	});
}

var wait=60;
function time(o) {
	if (wait == 0) {
		o.removeAttribute("disabled");			
		o.value="获取验证码";
		wait = 60;
	} else {
		o.setAttribute("disabled", true);
		o.value="重新发送(" + wait + ")";
		wait--;
		setTimeout(function() {
			time(o)
		},
		1000)
	}
}
