/**
 * 我的页面
 * created by liufang 2018/8/17
 */
$(function () {
	var tpl = {
		mineTpl: '<div class="vir-wp">\
					<div class="vir-name">\
						<span class="title">企业账号信息</span>\
					</div>\
					<div class="vir-item">\
						<div class="tips">企业账号</div>\
						<% if(isLogin==2){%>\
							<div class="item-text check-account"><%=account%></div>\
						<%}else if(isLogin==1){%>\
							<div class="item-text ubind-vir">未登录</div>\
							<div class="arrow-icon"></div>\
						<%}%>\
					</div>\
					<% if(isLogin==2){%>\
						<div class="vir-item">\
							<div class="tips">企业名称</div>\
							<div class="item-text"><%=compName%></div>\
						</div>\
					<%}%>\
				</div>\
				</div>',
		mineTplMe: '<div class="vir-wp">\
				<div class="vir-name">\
					<span class="title">我的账号信息</span>\
				</div>\
				<div class="vir-item">\
					<div class="tips">手机号码</div>\
					<% if(isLogin==2){%>\
						<div class="item-text"><%=mobile%></div>\
					<%}else if(isLogin==1){%>\
						<div class="item-text phone-login">马上登录</div>\
						<div class="arrow-icon"></div>\
					<%}%>\
				</div>\
				<% if(isLogin==2 && isWhite==1){%>\
					<div class="vir-item">\
						<div class="tips">姓名</div>\
						<div class="item-text"><%=userName%></div>\
					</div>\
					<div class="vir-item">\
						<div class="tips">部门</div>\
						<div class="item-text"><%=deptName%></div>\
					</div>\
					<div class="vir-item" style="height: auto;min-height: 50px">\
						<div class="tips">地址</div>\
						<div class="item-text"><%=address%></div>\
					</div>\
					<% if(passType==1){%>\
						<div class="vir-item">\
							<div class="tips">人脸识别图片</div>\
							<div class="item-text look_face">查看图片</div>\
						</div>\
					<%}%>\
				<%}%>\
			</div>\
			</div>',
		imgWrap: '<div class="mask">\
					<div class="pic_wrap">\
						<img class="pic" src="<%=pic%>" />\
					</div>\
				 </div>'
	};
	var ERROR_OK = 200;
	var contextPath = $("#contextPath").val();
	var openId, developId, organId, userId, userStatus, register, colName, isLogin;
	var _userId, passType;
	var mine = {
		init: function () {
			this.render();
			this.bindEvent();
		},
		render: function () {
			this.renderInfo();
			openId = this.GetQueryString("openId");
			developId = this.GetQueryString("developId");
			organId = this.GetQueryString("organizationId");
			if(organId == 663){
				$(".weal").hide()
				$(".logo-icon").css("background-image",'url("../../images/index_v1.0/groupLogo_663.png")')
				$(".card").css("margin-left",'110%')
				$(".headerArea .swiper-icon").addClass("fude-icon")
			}else if(organId == 691){
        $(".weal").hide()
        $(".logo-icon").css("background",'url("../../images/index_v1.0/suoke_logo.jpg") no-repeat center/contain')
        $(".card").css("margin-left",'110%')
        $(".headerArea .swiper-icon").addClass("suoke-icon")
      }else{
				$(".weal").show()
			}
			userId = this.GetQueryString("userId");
			userStatus = this.GetQueryString("userStatus");
			register = this.GetQueryString("register");
			//取下passType
			passType = sessionStorage.getItem("passType")
			if (!passType) {
				passType = this.GetQueryString("passType");
			}
			//跳转服务
			$(".nav-btn.service").on("click", function () {
				window.location.href = $("#contextPath").val() + "/wechat/index/serviceListPage?openId=" + openId + "&developId=" + developId + "&userStatus=" + userStatus + "&userId=" + userId + "&register=" + register + "&organId=" + organId;
			});
			//跳转首页
			$(".nav-btn.home").on("click", function () {
				// window.location.href = $("#contextPath").val() + "/wechat/index/homePageView?openId=" + openId + "&developId=" + developId + "&organizationId=" + organId + "&userId=" + userId;
				window.location.href = $("#contextPath").val() + "/wechat/index/homePageView?openId=" + openId + "&developId=" + developId + "&organizationId=" + organId;
			});
			// 跳转商圈
			$(".nav-btn.trade_area").on("click", function () {
//				var u = navigator.userAgent;
//		        var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
//		        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
//		        if(isiOS){
//		        	var findUrl = sessionStorage.getItem('findUrl')
//					window.location.href = findUrl ;
//		        }else{
		        	window.location.href = $("#contextPath").val() + "/wechat/index/tradeArea?openId=" + openId + "&developId=" + developId + "&userStatus=" + userStatus + "&userId=" + $("#userId").val() + "&register=" + register + "&organId=" + organId;
					
//		        }

				//window.location.href = $("#contextPath").val() + "/wechat/index/tradeArea?openId=" + openId + "&developId=" + developId + "&userStatus=" + userStatus + "&userId=" + $("#userId").val() + "&register=" + register + "&organId=" + organId;
			});

			//$(".newmine-wp").append(template.render(tpl.mineTpl))
			$(".code-info").on("click", function () { //点击显示二维码弹框
				if (passType == 2) { //如果是令令走这里。不是走以前
					if (isLogin == undefined) {
						return
					} else if (isLogin == 1) {
						window.location.href = $("#contextPath").val() + "/wechat/appUser/userLoginPage?openId=" + openId + "&developId=" + developId + "&userStatus=" + userStatus + "&userId=" + userId + "&register=" + register + "&organizationId=" + organId;
						return
					}
					// 先跳转
					window.location.href = $("#contextPath").val()+'/wechat/lingling/indexQrCode?openId=' + openId
					// 弹窗形式的预留
					// $('.part_2').show()
					// $(".cover").addClass("coverShow");
					// // 设置定时器
					// if (typeof (cutDown) != "undefined") {
					// 	clearTimeout(cutDown);
					// }
					// cutDown = setInterval(function () {
					// 	getQrcode()
					// }, 3600000);
					// getQrcode()
				} else {
					$('.part_1').show()
					$(".cover").addClass("coverShow");
				}
			});
			$(".cover").on("click", function () { //点击弹框消失
				$(".cover").removeClass("coverShow");
				$('.part_1').hide()
				$('.part_2').hide()
				if (typeof (cutDown) != "undefined") {
					clearTimeout(cutDown);
				}
			})
			// $(".refresh").on("click", function () { //点击弹框消失
			// 	// 设置定时器
			// 	event.stopPropagation();
			// 	if (typeof (cutDown) != "undefined") {
			// 		clearTimeout(cutDown);
			// 	}
			// 	cutDown = setInterval(function () {
			// 		getQrcode()
			// 	}, 3600000);
			// 	getQrcode()
			// })

//			$(".weal ").on("click", function () {
//				//alert('企业暂未开通福利商城');
//				// layui.use("layer",function(){
//				// 	var layer = layui.layer;  //layer初始化
//				// 	layer.msg('企业暂未开通福利商城');
//				// })
//				//alert(sessionStorage.getItem("foodCardNo"));
//				 window.location.href ="https://wcard.hstydev.com/external_get_welfare?spid="+sessionStorage.getItem("foodCardNo")+"&out_account_id="+openId+"&name="+$(".nickName").html()+"&mobile="+sessionStorage.getItem("mobile");
//			})
		},
		/**
		 * 绑定事件
		 * @param openId
		 * @param organizationId
		 * @param developId
		 * @param userId
		 * @param compName 企业名称
		 * @param accountId 企业账号id
		 * @param account 企业账号
		 */
		bindEvent: function (openId, organizationId, developId, userId, compName, accountId, account, mobile, isLogin, isWhite) {
			var _this = this;
			var compName = !compName ? "" : compName;
			//企业登录
			$(".ubind-vir").on("click", function () {
				window.location.href = $("#contextPath").val() + "/wechat/appUser/virAccount?openId=" + openId + "&developId=" + developId + "&userStatus=" + userStatus + "&userId=" + userId + "&register=" + register + "&organizationId=" + organId + "&compName=" + compName + "&accountId=" + accountId;
			});
			//查看企业账号
			$(".check-account").on("click", function () {
				window.location.href = $("#contextPath").val() + "/wechat/release/mine?openId=" + openId + "&developId=" + developId + "&userStatus=" + userStatus + "&userId=" + userId + "&register=" + register + "&organizationId=" + organId + "&compName=" + compName + "&accountId=" + accountId + "&virAccount=" + account;
			});
			//更换手机号码
			$(".change-phone").on("click", function () {
				window.location.href = contextPath + '/wechat/release/changePhone?mobile=' + mobile + '&openId=' + openId + '&developId=' + developId + '&userId=' + userId + '&organizationId=' + organizationId;
			});
			//解绑
			// $(".untie").on("click",function(){
			// 	_this.untiePhone(userId);
			// });
			//修改密码
			// $(".untie").on("click", function () {
			// 	window.location.href = $("#contextPath").val() + "/wechat/appUser/virChangePsd?openId=" + openId + "&developId=" + developId + "&userStatus=" + userStatus + "&userId=" + userId + "&register=" + register + "&organizationId=" + organId + "&virAccount=" + account;
			// });
			//绑定电话号码
			$(".ubind-phone").on("click", function () {
				window.location.href = $("#contextPath").val() + "/wechat/appUser/bindphone?openId=" + openId + "&developId=" + developId + '&userId=' + userId + '&organizationId=' + organizationId;
			})
			// 跳转个人账号登录
			$(".phone-login").on("click", function () {
				window.location.href = $("#contextPath").val() + "/wechat/appUser/userLoginPage?openId=" + openId + "&developId=" + developId + "&userStatus=" + userStatus + "&userId=" + userId + "&register=" + register + "&organizationId=" + organizationId;
			})
			// 跳转设置页面
			$(".add-icon").on("click", function () {
        //  && isWhite != 0
        sessionStorage.setItem("isWhite",isWhite)
				if (isLogin == 2) {
					window.location.href = $("#contextPath").val() + "/wechat/appUser/mySetUp?openId=" + openId + "&developId=" + developId + "&userStatus=" + userStatus + "&userId=" + userId + "&register=" + register + "&organizationId=" + organId + "&virAccount=" + account + "&accountId=" + accountId;
				}
			})
			// 关闭弹层
			$('body').on('click', '.pic', function(event) {
				$('.mask').remove()
			});
			$('body').on('click', '.mask', function(event) {
				$('.mask').remove()
			});
		},
		//渲染我的页面
		renderInfo: function () {
			var _this = this;
			var openId = this.GetQueryString("openId");
			var organizationId = this.GetQueryString("organizationId");
			var developId = this.GetQueryString("developId");
			var userId = this.GetQueryString("userId");
			var accountType = sessionStorage.getItem("accountType");
			//判断是否显示商圈/发现
			var isEnabled = sessionStorage.getItem("isEnabled");
			var name = sessionStorage.getItem("name");
			if (isEnabled == "true") {
				$(".trade_area").show();
				$(".trade_area .name").html(name);
			}
			this.ajaxInfo(openId, organizationId, accountType, function (data) {
				isLogin = data.isLogin
				if (data.isLogin == 1) {
					$(".acountName").html("");
				}
				_this.judgeShow();
				if (data.isLogin == 2) {
					data.userName ? $(".nickName").html(data.userName) : _this.judgeShow();
					data.compName ? $(".acountName").html(data.compName) : $(".acountName").html("");
					// 单独给一个全局userId
					_userId = data.userId
				} else if (data.isLogin == 1) {
					$(".acountName").html("");
				}
				_this.bindEvent(openId, organizationId, developId, data.userId, data.compName, data.accountId, data.account, data.mobile, data.isLogin, data.isWhite);
			})
		},
		/**
		 * 获取url的参数
		 * @param name 参数名
		 */
		GetQueryString: function (name) {
			var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
			var r = window.location.search.substr(1).match(reg);
			if (r != null) return unescape(r[2]);
			return null;
		},


		/**
		 * 获取用户信息接口
		 *
		 * @param openid
		 * @param organizationId 楼栋id
		 * @param callback
		 */
		ajaxInfo: function (openId, organizationId, accountType, callback) {
			var _this = this;
			$.ajax({
				url: contextPath + "/wechat/appUser/getUserInfo",
				type: "POST",
				dataType: "json",
				data: {
					openId: openId,
					organizationId: organizationId
				},
				success: function (data) {
					
					if (data.code == ERROR_OK) {
						
						if (accountType == 0) {
							
							$(".newmine-wp").append(template.render(tpl.mineTpl)(data.data))
						} else if (accountType == 1) {
							$(".newmine-wp").append(template.render(tpl.mineTplMe)(data.data));
							
							
							sessionStorage.setItem("foodCardNo", data.data.foodCardNo);
							sessionStorage.setItem("userName", data.data.userName);
							sessionStorage.setItem("deptName", data.data.deptName);
							sessionStorage.setItem("deptId", data.data.deptId);
							sessionStorage.setItem("address", data.data.address);
							sessionStorage.setItem("addressId", data.data.addressId);
							
							//个人退出时 更新公司及账号 sessionStorage qzy
							sessionStorage.setItem("accId", data.data.accountId);
							sessionStorage.setItem("account", data.data.account);
							sessionStorage.setItem("virId", data.data.compId);
							sessionStorage.setItem("virName", data.data.compName);

							sessionStorage.setItem("mobile", data.data.mobile);
							sessionStorage.setItem("passType", data.data.passType);
							if(data.data.facePicList){
								sessionStorage.setItem("facePicList", JSON.stringify(data.data.facePicList));
							}
									
						}
						$(".weal ").on("click", function () {
							if(data.data.foodCardNo){
								window.location.href =data.data.foodCardH5+"?spid="+data.data.foodCardNo+"&out_account_id="+openId+"&name="+data.data.userName+"&mobile="+data.data.mobile;
							}else{
								alert('未开通企业饭卡，请联系客服开通:0755-88600765')
							}
						});
						$('.look_face').on('click', function(event) {
							event.preventDefault();
							/* Act on the event */
							var facePicList = data.data.facePicList
							if(facePicList){
								$("body").append(template.render(tpl.imgWrap)({pic:facePicList[0]['imageUrl']}));
							}else{
								alert('暂无人脸图片')
							}
						});
						callback(data.data)
					} else {
						alert(data.msg)
					}
				},
				error: function (data) {
					// alert("系统繁忙,菜单加载失败..");
				}
			});
		},
		/**
		 * 解绑
		 * @param userid
		 */
		untiePhone: function (userId) {
			layer.open({
				cancel: function () {
					layer.open({
						content: '你点了x',
						time: 1
					});
				},
				btn: ['确认', '取消'],
				shadeClose: false, //默认：true，是否点击遮罩时关闭层
				yes: function () {
					$.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.reload();
									}
								});
							} else {
								layer.open({
									content: "请检查网络，提交失败.",
									skin: 'msg',
									time: 2
								});
							}
						},
						error: function (xhr, textStatus) {
							alert(textStatus);
						}
					});
				},
				no: function () {

				},
				content: '您确定要解除绑定'
			});
		},
		judgeShow: function () {
			var nickName = sessionStorage.getItem("nickName");
			var nickPic = sessionStorage.getItem("nickPic");
			$(".nickName").html(nickName);
			$(".nickPic").attr("src", nickPic);
		},
	};

	function getQrcode() {
		if (isLogin == undefined) {
			return
		} else if (isLogin == 1) {
			window.location.href = $("#contextPath").val() + "/wechat/appUser/userLoginPage?openId=" + openId + "&developId=" + developId + "&userStatus=" + userStatus + "&userId=" + userId + "&register=" + register + "&organizationId=" + organId;
			return
		}
		var res;
		$.ajax({
			type: "get",
			url: $("#contextPath").val() + '/wechat/lingling/createQrCode',
			async: false,
			data: {
				'userId': _userId
			},
			//dataType: "jsonp",
			//jsonp: "callback",
			//jsonpCallback: "success_jsonpCallback",
			xhrFields: {
				withCredentials: true
			},
			crossDomain: true,
			complete: function (data) {
				res = data.responseJSON;
			},
		});
		if (res && res.code == 200) {
			var data = res.data
			if (data) {
				$('.nodata').hide()
				$('.qrcode_wrap').show()
				$('#code').empty();
				$('#code').qrcode(data)
				$('#code').append('<img class="lyzc_icon" src="'+ $("#contextPath").val()+'/images/lyzc.png" alt="" />')
			} else {
				$('.qrcode_wrap').hide()
				$('.nodata').show()
				$('#code').empty();
			}
		} else {
			$('.qrcode_wrap').hide()
			$('.nodata').show()
			$('#code').empty();
		}
	}
	mine.init();

})