var imageArray=new Array();
var redirectUrl="";
var imageUrl="";
/**
 * 修改用户 认证或者查看认证资料详情JS
 */
$(function(){
	 wexConfig();//定位
	Array.prototype.contains = function (obj) {
		  var i = this.length;
		  while (i--) {
		    if (this[i] === obj) {
		      return true;
		    }
		  }
		  return false;
		}
	
	//弹出选择企业选项
	 $(".iconwhat").click(function(event) {
         $(".tips-mask").show();
       });
       $(".tip-btn a").click(function(event) {
         $(".tips-mask").hide();
       });
       
    // 点击出现选择公司弹窗
       $(".js_company").click(function(){
    	   var organizationId=$("#organizationId").val();
    	   var appUserStatus=$("#appUserStatus").val();
    	   if(appUserStatus==1){
    		   return;
    	   }
    	   if($("#vpName").val()){
    		   addressVp($(".searchicon"));
    	   }
    	   searchVirtualArch(organizationId);
       });
       // 点击“x” -- 关闭选择公司弹窗
       $(".closeicon").click(function(){
           closeCompany();
       });

       // 点击搜索图标 -- 显示搜索框
       $(".searchicon").click(function(){
           var _this = $(this);
           _this.parents("#vpSearchbar").hide();
           $("#vpSearchbarentry").show();
           $("#vpName").focus();
       });
       
       $("#vpName").bind('input propertychange', function() {
			var value = $(this).val();
			 if(value){
	               $("#vpIconclear").show();
	           } else {;
	               $("#vpIconclear").hide();
	           }
			 var organizationId=$("#organizationId").val();
	          searchVirtualArch(organizationId);
		});

       // 点击搜索框的'x'图标时清楚搜索框里的字
       $("#vpIconclear").click(function(){
           var _this = $(this);
           $("#vpName").val("");
           var organizationId=$("#organizationId").val();
           searchVirtualArch(organizationId);
           _this.hide();
       });

       // 选择公司的值赋值到页面上
       $(".companylist").on("click", "li", function() {
           var _this = $(this);
           var _html = _this.html();
           if(_html){
        	   $("#virtualArchId").val(_this.val());
               $(".js_company").find("strong").html(_html).parent().removeClass("placeholder");
               closeCompany();
           }
       });
       
       //提交认证
       $("#submitUserInfo").click(function(){ 
    	   var contextPath=$("#contextPath").val();
    	   var organizationId=$("#organizationId").val();
    	   var virtualArchId=$("#virtualArchId").val();
    	   var remark = $("#userRemark").val();
    	   var developId=$("#developId").val();
    	   var userId=$("#userId").val();
    	   var openId=$("#openId").val();
    	   var dataUrl=$("#dataUrl").val();
    	   if($.trim(organizationId)==""){
    		   layer.open({
       			content : "请选择项目",
       			skin : 'msg',
       			time : 2
       		// 2秒后自动关闭
       		});
    		 return;
    	   }
    	   if($.trim(virtualArchId)==""){
    		   layer.open({
       			content : "请选择公司",
       			skin : 'msg',
       			time : 2
       		// 2秒后自动关闭
       		});
    		   return;
    	   }
    	   var userName=$("#userName").val();
    	   if($.trim(userName)==""){
    		   layer.open({
       			content : "请填写姓名",
       			skin : 'msg',
       			time : 2
       		// 2秒后自动关闭
       		});
    		   return;
    	   }
    	   var remark=$("#userRemark").val();
    	   if($.trim(remark)==""){
    		   layer.open({ 
       			content : "请填写备注",
       			skin : 'msg',
       			time : 2
       		// 2秒后自动关闭
       		});
    		   return;
    	   }
//    	   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/appUser/submitUserInfo",
   	    	data: {
	   	    		userId:userId,
	   	    		openId:openId,
	   	    		organizationId:organizationId,
	   	    		virtualArchId:virtualArchId,
	   	    		userName:userName,
	   	    		dataUrl:dataUrl,
	   	    		remark:remark
	   	    		},
   	        type: "POST",
   	        dataType: 'json',//返回值类型 一般设置为json
   	        success: function(data){
   	        	if("success"==data.retCode){
   	        		var organizationId = data.organizationId;
   	        		var userMobile = data.userMobile;
   	        		$(".popupmask").show();
   	        		redirectUrl=contextPath+"/wechat/appUser/userInfo?organizationId="+organizationId+"&openId="+openId+"&developId="+developId+"&userId="+userId;
   	        		//同步信息到商城
   	        		$.ajax({
   						type : 'POST',
   						url : contextPath+"/wechat/sikpMall/updateMallCterminal",
   						data : {"userMobile":userMobile,"organizationId":organizationId},
   						dataType : 'json',// 返回值类型 一般设置为json
   						success : function(data) // 服务器成功响应处理函数
   						{
   						}
   					});
   	        	}
   	        	else{
	   	        	 layer.open({
	   	       			content : "请检查网络，提交失败.",
	   	       			skin : 'msg',
	   	       			time : 2
	   	       		});
   	        	}
   	        },
   	        error: function(){
   	        	layer.open({
   	       			content : "请检查网络，提交失败.",
   	       			skin : 'msg',
   	       			time : 2
   	       		});
   	        }
   	    });	
    	 
       });
       
       //解除绑定
       $("#unbundling").click(function(){
    	   var contextPath=$("#contextPath").val();
    	   var organizationId=$("#organizationId").val();
    	   var openId=$("#openId").val();
    	   var developId=$("#developId").val();
    	   var userId=$("#userId").val();
    	   $.ajax({
    			url:contextPath+"/wechat/appUser/removeBinding",
    			type:"POST",
    			data:{userId:userId},
    			success : function(data) {
    				if("success"==data){
      	        		layer.open({
	   	   	       			content : "解绑成功",
	   	   	       			skin : 'msg',
	   	   	       			time : 1
	   	   	       		,end:function(){
	   	   	       			location.href=contextPath+"/wechat/appUser/uauthentication?organizationId="+organizationId+"&openId="+openId+"&developId="+developId+"&userId="+userId;
	   	   	       		}});
      	        	}else{
      	        		layer.open({
          	       			content : "请检查网络，提交失败.",
          	       			skin : 'msg',
          	       			time : 2
          	       		});
      	        	}
    			}, error : function(xhr,textStatus){
    				alert(textStatus);
    		    }
    		})
       });
       /**
        * 确定操作
        */
       $(".okbtn").click(function(){
    	   location.href=redirectUrl;
       })
       //楼宇
       $(".js_build").click(function(){
    	   var appUserStatus=$("#appUserStatus").val();
    	   if(appUserStatus==1){
    		   return;
    	   }
    	if($("#opName").val()!=""){
    		addressOp($(".searchbuild"));
    	}   
    	loadProvincecityByCity();
        $(".buildingmask").show().find(".selectbuilding").animate({
            bottom: 0
        }, 500);
    })
});

//关闭选择公司弹窗
function closeCompany(){
    $(".selectcompany").animate({
        bottom: "-38.14rem"
    }, 500, function(){
        $("#vpSearchbar").show();
        $("#vpSearchbarentry").hide();
        $(this).parents(".companymask").hide();
        $(".companymask").unbind("click");
    });
//    $(".companymask").unbind("click");
}

//根据项目ID查询企业
function searchVirtualArch(organizationId){
	var contextPath=$("#contextPath").val();
	var params=$("#vpName").val();
	$.ajax({
		type:'POST',
		url:contextPath+'/wechat/appUser/getVirtualArchitectureListByName',
		data:{organizationId:organizationId,type:"1",params:params},
		dataType: 'json',
		success: function (data){
			$(".companylist").empty();
			if(data!=null && data!="" && data.length>0){
				$.each(data,function(index,item){
					var html="<li value='"+item.id+"'>"+item.name+"</li>";
					$(".companylist").append(html);
				});
			}
			console.log(data);
			$(".companymask").show().find(".selectcompany").animate({
                bottom: 0
            }, 500);
	        // 点击空白处关闭选择公司弹窗
	        $(".companymask").click(function(e){
	            var _con = $(".selectcompany");   // 设置目标区域
	            if(!_con.is(e.target) && _con.has(e.target).length === 0){
	                closeCompany();
	            }
	        });
		}
	});
}

/**
 * 上传图片
 * @param val
 * @param fileObj
 */
function selectFileImage(fileObj,id,paramDiv) {
	var appUserStatus=$("#appUserStatus").val();
	   if(appUserStatus==1){
		   return;
	   }
    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' pictype='30010003' data-role='none' accept='image/*' 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' pictype='30010003' data-role='none' accept='image/*' 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' pictype='30010003' data-role='none' accept='image/*' 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+"' pictype='30010003' data-role='none' accept='image/*' 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){
			
	    }
	});
}

function addressVp(_this){
    _this.parents("#vpSearchbar").hide();
    $("#vpSearchbarentry").show();
    $("#vpName").focus();
    if($("#vpName").val()){
        $("#vpIconclear").show();
    } else {
        $("#vpIconclear").hide();
    }
}

/*
 * 注入微信
 */
function wexConfig() {
	$.ajax({
		url : $("#contextPath").val() + "/wechat/visitor/fenxiang",
		type : "POST",
		async : true,
		cache : false,
		dataType : "json",
		data : {
			url : location.href.split('#')[0],
			developId : $("#developId").val()
		},
		success : function(data) {
			wx.config({
				debug : false, // 开启调试模式
				appId : data.appid, // 必填，公众号的唯一标识
				timestamp : data.timestamp, // 必填，生成签名的时间戳
				nonceStr : data.nonceStr, // 必填，生成签名的随机串
				signature : data.signature,// 必填，签名，见附录1
				jsApiList : [ 'getLocation', 'hideOptionMenu' ]
			// 必填，需要使用的JS接口列表，所有JS接口列表见附录2
			});
			//隐藏右上角菜单
			wx.hideOptionMenu();
			wx.ready(function(){
					wx.checkJsApi({  
		 	             jsApiList: [   
		 	               'getLocation',
		 	               'hideOptionMenu'
		 	             ],  
		 	             success: function (res) {  
		 	               //alert(res.errMsg);  
		 	             }
					});
				wx.getLocation({
						success : function(res) {
							var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
							var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
							var speed = res.speed; // 速度，以米/每秒计
							var accuracy = res.accuracy; // 位置精度
							//定位项目
							initOrgSelect(latitude,longitude);
						},
						cancel : function(res) {
							initOrgSelect(0.00,0.00);
						}
					});
			});

		}
			
	});
}

/**
 * 定位项目
 */
function initOrgSelect(lat, lng) {
	if(lat==null || lng==null || lat=="" || lng==""){
		return;
	}
	var developId=$("#developId").val();
	$.ajax({
		url :$("#contextPath").val()+"/wechat/index/initOrgSelect",
		type : "POST",
		dataType : "json",
		data : {
			latitude : lat,
			longitude : lng,
			developId : developId
		},
		timeout:100000,
		beforeSend: function( xhr ) {
			
		  },
		success : function(data) {
			if (data != null && data != "") {
				$("#locationiconName").html(data.name);
				$("#locationiconId").val(data.id);
				$("#cityCode").val(data.cityCode);
			}
				
		}

	});
}

/**
 * 跳转申请新的项目
 */
function saveProject(){
	var params="?developId="+$("#developId").val()+"&userId="+$("#userId").val()+"&openId="+$("#openId").val();
	location.href=$("#contextPath").val()+"/wechat/property/organizationView"+params;
}

/**
 * 跳转申请新的企业
 */
function saveCompany(){
	var params="?developId="+$("#developId").val()+"&userId="+$("#userId").val()+"&openId="+$("#openId").val()+"&organizationId="+$("#organizationId").val();
	location.href=$("#contextPath").val()+"/wechat/property/virtualarchitectureView"+params;
}


	
	
