$(function () {
  var ERROR_OK = 200;
  var contextPath = $("#contextPath").val();
  var openId = GetQueryString("openId");
  var userStatus = GetQueryString("userStatus");
  var register = GetQueryString("register");
  var developId = GetQueryString("developId");
  var userId = "";
  var mobile = sessionStorage.getItem("mobile");
  var urls = window.location.href;
  $("#phoneBefore").html(mobile);
  if (GetQueryString("userId")) {
    userId = GetQueryString("userId");
  } else {
    userId = sessionStorage.getItem("userId");
  }
  if (!developId) {
    developId = $("#developId").val();
  }
  if (!openId) {
    openId = sessionStorage.getItem("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"
  }
  
  var timer; //timer变量，控制时间
  var count = 60; //间隔函数，1秒执行
  var curCount = 60; //当前剩余秒数
  var code = ""; //验证码
  var oldLocation = window.location.href;

  function sendMessage() { //设置button效果，开始计时
    curCount = count;
    $("#getCode").attr("disabled", "true");
    console.log($("#getCode").val())
    $("#getCode").text(curCount + "s 重新获取");
    timer = window.setInterval(SetRemainTime, 1000); //启动计时器，1秒执行一次
  };
  /**
   * timer处理函数
   * 
   */
  function SetRemainTime() {
    if (curCount == 0) {
      window.clearInterval(timer); //停止计时器
      $("#getCode").removeAttr("disabled"); //启用按钮
      $("#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, userId,urls) {
    $.ajax({
      url: contextPath + "/wechat/index/changeAccountLogin",
      type: "POST",
      dataType: "json",
      data: {
        openId: openId,
        mobile: mobile,
        mobileCode: mobileCode,
        orgId: organizationId,
        oldUrl: oldLocation,
        userId: userId
      },
      success: function (data) {
        if (data.code == ERROR_OK) {
          if (!!oldUrl) {
            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;
            	 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("accId", data.data.accId);
                 sessionStorage.setItem("mobile",data.data.mobile);
            }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;
              }
              //window.location.href = oldUrl + "?userId=" + userid + "&openId=" + openId + "&developId=" + developId;
              
              var urlStr = oldUrl.split("?");
			  if (urlStr.length > 1) {
					window.location.href = oldUrl + "&userId=" + userid +"&openId="+openId+"&developId="+developId;
			  } else {
					window.location.href = oldUrl + "?userId=" + userid +"&openId="+openId+"&developId="+developId;
			  }  
              
            }
          } else {
            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("系统繁忙..");
      }
    });
  };
  /**
   * 获取验证码
   * @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 {
          layer.open({
            content: data.msg,
            skin: 'msg',
            time: 2 //2秒后自动关闭
          });
        }
      },
      error: function (data) {
        // alert("系统繁忙..");
      }
    });
  }

  $("#getCode").click(function () {
    let 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
    }
    ajaxCode(mobile);
  })
  $(".bind-btn").click(function () {
    console.log(userId);
    let mobile = $("#phone").val();
    let 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, userId,urls);
  })
})