$(function () {
  var ERROR_OK = 200;
  var contextPath = $("#contextPath").val();
  var openId = sessionStorage.getItem("openId");
  var userId = GetQueryString("userId");
  var serviceCode = GetQueryString("serviceCode");
  var userStatus = GetQueryString("userStatus");
  var register = GetQueryString("register");
  var developId = GetQueryString("developId");
  var urls = window.location.href;
  if (!developId) {
    developId = $("#developId").val();
  }
  if (!openId) {
    openId = GetQueryString("openId");
  }
  var organizationId = sessionStorage.getItem("orgId");
  var oldUrl = $("#oldUrl").val();
  if (!oldUrl) {
    oldUrl = GetQueryString("oldUrl")
  }
  if (oldUrl == "/wechat/neigou/meetingDo") {
    oldUrl = contextPath + "/wechat/neigou/meetingDo"
  }
  
  if (oldUrl == "/wechat/neigou/wjdcDo") {
	    oldUrl = contextPath + "/wechat/neigou/wjdcDo"
  }
  
  if (oldUrl == "/wechat/neigou/tsbyDo") {
	    oldUrl = contextPath + "/wechat/neigou/tsbyDo"
  }

  if (oldUrl == "/wechat/newneigou/indexPage") {
      oldUrl = contextPath + "/wechat/newneigou/indexPage"
  }

  if(oldUrl == "/wechat/visitor/authorVisitor"){
      oldUrl = contextPath + "/wechat/visitor/authorVisitor"
  }

  var timer; //timer变量，控制时间
  var count = 60; //间隔函数，1秒执行
  var curCount = 60; //当前剩余秒数
  var code = ""; //验证码
  var oldLocation = window.location.href;
  var canClick = true;

  function sendMessage() { //设置button效果，开始计时
    curCount = count;
    $("#getCode").text(curCount + "s 重新获取");
    timer = window.setInterval(SetRemainTime, 1000); //启动计时器，1秒执行一次
  };
  /**
   * timer处理函数
   * 
   */
  function SetRemainTime() {
    if (curCount == 0) {
      window.clearInterval(timer); //停止计时器
      // $("#getCode").removeAttr("disabled"); //启用按钮
      canClick = true;
      $("#getCode").text("获取验证码");
      code = ""; //清除验证码。如果不清除，过时间后，输入收到的验证码依然有效   
      $("#code").val(code);
    } else {
      curCount--;
      $("#getCode").text(curCount + "s 重新获取");
    }
  };
  /**
   * 验证手机号
   * @param phone 参数名
   */
  function isPhoneNo(phone) {
    var pattern = /^1[3456789]\d{9}$/;
    return pattern.test(phone);
  };
  /**
   * 获取url的参数
   * @param name 参数名
   */
  function GetQueryString(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 mobile, mobileCode 参数名
   */
  function ajaxBind(mobile, mobileCode, urls) {
    $.ajax({
      url: contextPath + "/wechat/index/login",
      type: "POST",
      dataType: "json",
      data: {
        openId: openId,
        mobile: mobile,
        mobileCode: mobileCode,
        orgId: organizationId,
        oldUrl: oldLocation
      },
      success: function (data) {
        if (data.code == ERROR_OK) {
          var type = GetQueryString("type");
          checkedPerm(data.data.userId,function(){
            if (!!oldUrl) {
              sessionStorage.setItem('firstEnter', 1); //标志首次进入服务，为1代表首次进入
              //        	  if(type==1){ //跳转会议室
              //        		  window.location.href = oldUrl;
              //        	  }else
              if ((urls.indexOf("/customervoice/h5") != -1) || (urls.indexOf("/wx/outlink") != -1)) { //航电报事/投诉
                var hdUserId = data.data.hdUserId;
                var hdProjectId = data.data.hdProjectId;
                sessionStorage.setItem("userId", data.data.userId);
                sessionStorage.setItem("mobile", data.data.mobile);
                window.location.href = oldUrl + "&userId=" + hdUserId + "&openid=" + openId + "&developid=" + developId + "&projectno=" + hdProjectId;
              }else if(urls.indexOf("weChatOath/redirectHdReportRepair") != -1){
            	var hdUserId = data.data.hdUserId;
            	var hdVoiceProjectId = data.data.hdVoiceProjectId;
            	window.location.href = oldUrl + "&openId=" + openId + "&developid=" + developId + "&projectId=" 
                  	+ hdVoiceProjectId+"&sendType="+"01"+ "&userCode=" + hdUserId;
              }else {
                var userid = data.data.userId;
                var username = data.data.userName;
                sessionStorage.setItem("userId", data.data.userId);
                sessionStorage.setItem("userName", data.data.userName);
                sessionStorage.setItem("virId", data.data.virId);
                sessionStorage.setItem("virName", data.data.virName);
                sessionStorage.setItem("address", data.data.address);
                sessionStorage.setItem("accId", data.data.accId);
                sessionStorage.setItem("mobile", data.data.mobile);
                if (!!data.data.oldUrl) {
                  oldUrl = data.data.oldUrl;
                }
  
                //根据oldUrl 是否有"?" 来拼接
                //正常可以通过 encodeURIComponent oldurl + oldurl里方法前移 来判断 拼接"?" or "&"
                //下面方法如最后是参数 再加+ "?userId=" 会使最后一个参数 拼接 encodeURIComponent("?userId=") 使用参数失效
                //方法前移参考
                //http://wx.palmnest.com:8088/?token=96AD0BA85533D9584B65E8A76CDAAD38F58AC11C05957B53286E77B3959C8762FA02360B1C2175D01067F77E0ABAD4FC#/selecttime?resrId=RS00000166&detail=1
                //如遇方法不好移动 可在链接后面加一个无用参数
                //http%3A%2F%2Fwx.palmnest.com%2Favicfile%2Fsuper_wechat%2Fdinner%2Findex.html#/shoppingcar?temp=1
                //add by qzy
  
                var urlStr = oldUrl.split("?");
                if (urlStr.length > 1) {
                  window.location.href = oldUrl + "&userId=" + userid + "&openId=" + openId + "&developId=" + developId + "&userMobile=" + data.data.mobile + "&virId=" + data.data.virId + "&orgId=" + organizationId;
                } else {
                  window.location.href = oldUrl + "?userId=" + userid + "&openId=" + openId + "&developId=" + developId + "&userMobile=" + data.data.mobile + "&virId=" + data.data.virId + "&orgId=" + organizationId;
                }
              }
            } else {
            	sessionStorage.setItem("userId", data.data.userId);
            	getToken(function(token){
            		var findUrl = "https://s.phone580.com/center/platform/qhcjqt4411.html?token=" + token ;//生产
					//var findUrl = "https://s.phone580.com/test/center/platform/qhcjqt4411.html?token=" + token ;//测试
					//var findUrl = "http://test.s.phone580.com:8000/service/test/center/platform/qhcjqt4411.html?token=" + token ;//测试-1
					sessionStorage.setItem('findUrl',findUrl)	
            	})
              window.location.href = contextPath + "/wechat/appUser/newmine?openId=" + openId + "&developId=" + developId + "&userStatus=" + userStatus + "&userId=" + userId + "&register=" + register + "&organizationId=" + organizationId;
            }  
          })
        } else {
          layer.open({
            content: data.msg,
            skin: 'msg',
            time: 2
          });
        }
      },
      error: function (data) {
        // alert("系统繁忙..");
      }
    });
  };
//获取token
 function getToken(callback){
		$.ajax({
			url: contextPath + "/wechat/index/createToken",
			type: "POST",
			dataType: "json",
			data: {
				userId: sessionStorage.getItem("userId")
			},
			success: function (data) {
				if(data && data.code==200 ){
					callback && callback(data.data);
				}
			},
			error: function (data) {
				// alert("系统繁忙..");
			}
		});
	};
  /**
   * 获取验证码
   * @param mobile 参数名
   */
  function ajaxCode(mobile) {
    $.ajax({
      url: contextPath + "/wechat/index/getSmsCode",
      type: "POST",
      dataType: "json",
      data: {
        openId: openId,
        mobile: mobile,
        orgId: organizationId,
        oldUrl: oldLocation
      },
      success: function (data) {
        if (data.code == ERROR_OK) {
          sendMessage();
        } else {
          canClick = true;
          layer.open({
            content: data.msg,
            skin: 'msg',
            time: 2 //2秒后自动关闭
          });
        }
      },
      error: function (data) {
        canClick = true;
        alert("系统繁忙..");
      }
    });
  }
  $("#phone").bind("input propertychange", function () {
    // console.log($("#phone").val().length);
    if ($("#code").val() && $("#phone").val().length == 11) {
      $(".bind-btn").addClass("active")
    } else {
      $(".bind-btn").removeClass("active")
    }
  });
  $("#code").bind("input propertychange", function () {
    // console.log($("#code").val().length);
    if ($("#phone").val() && $("#code").val().length == 4) {
      $(".bind-btn").addClass("active")
    } else {
      $(".bind-btn").removeClass("active")
    }
  });
  // 点击获取验证码
  document.getElementById("getCode").addEventListener("click", getCode);

  function getCode() {
    if (!canClick) {
      return false
    }
    var mobile = $("#phone").val();
    if (!mobile) {
      layer.open({
        content: '请输入手机号码',
        skin: 'msg',
        time: 2 //2秒后自动关闭
      });
      return false
    }
    if (!isPhoneNo(mobile)) {
      layer.open({
        content: '请输入正确的手机号码',
        skin: 'msg',
        time: 2
      });
      return false
    }
    canClick = false;
    ajaxCode(mobile);
  };
  /**
 校验用户权限
 */

function checkedPerm(id,callback) {
      if (id){
          id = ""
      }
	$.ajax({
		url: $("#contextPath").val() + "/wechat/index/checkedHasFuncPerm",
		type: "POST",
		dataType: "json",
		data: {
			id: id,
			serviceCode: sessionStorage.getItem('serviceCode'),
			accountType: 1
		},
		success: function (data) {
			if (data.code == "200") {
        // alert(data.data)
				if(data.data){
					callback()
				}else{
          layer.open({
            content: '抱歉，你暂无该功能的使用权限，请联系企业管理员或客服人员！',
            skin: 'msg',
            time: 2
          });
				}
			} else {
				alert(data.msg)
			}
		},
		error: function (data) {
			alert("系统繁忙,菜单加载失败..");
		}
	});
}
  $(".bind-btn").click(function () {
    var mobile = $("#phone").val();
    var codeNumber = $("#code").val();
    if (!mobile) {
      layer.open({
        content: '请输入手机号码',
        skin: 'msg',
        time: 2
      });
      return false
    }
    if (!isPhoneNo(mobile)) {
      layer.open({
        content: '请输入正确的手机号码',
        skin: 'msg',
        time: 2
      });
      return false
    }
    if (!codeNumber) {
      layer.open({
        content: '请输入有效的验证码',
        skin: 'msg',
        time: 2
      });
      return false
    }
    ajaxBind(mobile, codeNumber, urls);
  })
})