let app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    type: 'log',
    getCodeTime: 40, //发送短信的间隔时间
    verifyCodeTime: '获取验证码',
    passwordfocus: false,
    mobilefocus: false,
    codefocus: false,
    typeName: 'password',
    park: ['请选择园区'],
    parkindex: 0,
    passFlag: 1
  },

  onShow() {
    if (wx.getStorageSync('token')) {
      wx.reLaunch({
        url: '/pages/index/index',
      })
    }
  },

  // 性别选择
  parkChange: function (e) {
    this.setData({
      parkindex: e.detail.value
    })
  },

  tapType: function (e) {
    var type = e.currentTarget.dataset.type;
    this.setData({
      type
    })
  },

  foget() {
    wx.reLaunch({
      url: '/pages/login/login',
    })
  },

  navlogs() {
    wx.navigateTo({
      url: '/pages/logs/logs',
    })
  },

  codelog() {
    this.setData({
      codelog: 1
    })
  },

  getphone(e) {
    this.setData({
      mobile: e.detail.value
    })
  },

  passWordInput(e) {
    var type = e.currentTarget.dataset.type
    if (this.data.typeName = 'text') {
      this.setData({
        typeName: 'password'
      })
    } else if (this.data.typeName = 'password') {
      this.setData({
        typeName: 'text'
      })
    }
  },

  showPass() { // 显示密码而非*号
    console.log(this.data.storePass)
    if (this.data.passFlag == 1) { // 第一次点击
      this.setData({
        passFlag: 2,
        typeName: 'text'
      });
    } else { // 第二次点击
      this.setData({
        passFlag: 1,
        typeName: 'password'
      });
    }
  },

  bindGetUserInfo(e) {
    var userInfo = e.detail.userInfo
    console.log(11)
    wx.showLoading({
      title: '加载中',
    })
    wx.cloud.init()
    wx.cloud.callFunction({
      // 云函数名称
      name: 'pay',
    }).then(res => {
      console.log(res)
      app.AjaxRequest('POST', {
        'content-type': 'application/json'
      }, '/wx/login', {
        avatar: userInfo.avatarUrl,
        username: userInfo.nickName,
        gender: userInfo.gender === 1 ? '0' : '1',
        openid: res.result.OPENID
      }, function (res) {
        if (res.code == 0) {
          wx.setStorageSync('userId', res.userId)
          wx.setStorageSync('token', res.token)
          wx.reLaunch({
            url: '/pages/index/index',
          })
        }
      })
    })
  },

  getuser() {
    let cloudID = e.detail.cloudID //开放数据ID
    if (!cloudID) {
      app.showError('用户未授权')
      return
    }
    wx.showLoading({
      title: '加载中',
    })
    wx.cloud.init()
    wx.cloud.callFunction({
      name: 'getMobile',
      data: {
        cloudID: cloudID
      }
    }).then(res => {
      console.log(res)
      this.getuser()
      wx.hideLoading()
      let phone = res.result.list[0].data.phoneNumber
    }).catch(error => {
      console.log(error)
      wx.hideLoading()
    })
  },

  // 获取手机号
  getPhoneNumber: function (event) {
    let cloudID = event.detail.cloudID //开放数据ID

    if (!cloudID) {
      app.showToast('用户未授权')
      return
    }

    //loading
    app.showLoading()

    //获取手机号
    wx.cloud.callFunction({
      name: 'getPhone',
      data: {
        cloudID: cloudID
      }
    }).then(res => {
      app.hideLoading()

      let phone = res.result.list[0].data.phoneNumber

      if (phone) {
        wx.setStorageSync('phone', phone)

        //更新UI
        this.setData({
          phone: phone
        })
      }

      this.triggerEvent('applyTap')
    }).catch(error => {
      app.hideLoading()
      this.triggerEvent('applyTap')
    })
  },

  /**
   * 执行发送验证码
   */
  verifyCodeEvent: function (e) {
    var that = this;
    //验证手机号
    if (that.data.buttonDisable == true) return false;
    var mobile = that.data.mobile;
    var regMobile = /^[1]([3-9])[0-9]{9}$/;
    if (!regMobile.test(mobile)) {
      wx.showToast({
        title: '手机号错误',
        duration: 3000,
        icon: 'none'
      });
      that.setData({
        mobilefocus: true
      });
      return false;
    }
    that.Countdown()
    //验证手机号 END
    wx.showLoading();
    wx.request({
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'GET',
      url: app.DOMAIN_NAME + '/sms/send',
      data: {
        username: mobile,
        type: 'MEMBER_REGISTER'
      },
      success: res => {
        var mes = res.data.message,
          code = mes.slice(21, 25)
        that.setData({
          code
        })
        wx.hideLoading()
        that.Countdown();
      }
    })
  },

  /**
   * 发送短信倒计时,防止恶意刷短信
   */
  Countdown() {
    var that = this;
    that.setData({
      buttonDisable: true
    });
    var getCodeTime = wx.getStorageSync('getCodeTime');
    var intervalId = setInterval(function () {
      getCodeTime--;
      wx.setStorageSync('getCodeTime', getCodeTime);
      that.setData({
        verifyCodeTime: '重新获取' + '(' + getCodeTime + 's' + ')'
      });
      //倒计时完成
      if (getCodeTime == 0) {
        wx.setStorageSync('getCodeTime', that.data.getCodeTime);
        clearInterval(intervalId);
        that.setData({
          verifyCodeTime: '获取验证码',
          buttonDisable: false
        })
      }
    }, 1000);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(e) {
    var that = this;
    //限制发送验证码的时间，防止恶意刷短信
    var getCodeTime = wx.getStorageSync('getCodeTime');
    if (getCodeTime <= that.data.getCodeTime - 1 && getCodeTime > 0) {
      that.Countdown(that);
    } else {
      wx.setStorageSync('getCodeTime', that.data.getCodeTime)
      that.setData({
        buttonDisable: false
      })
    }
  },

  /**
   * 授权登录
   */
  authorLogin(e) {
    let _this = this;
    if (e.detail.errMsg !== 'getUserInfo:ok') {
      return false;
    }
    wx.showLoading({
      title: "正在登录",
      mask: true
    });
    // 执行微信登录
    wx.login({
      success: function (res) {
        //发送请求
        wx.request({
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          method: 'POST',
          url: app.DOMAIN_NAME + '/social_user_login/login',
          data: {
            code: res.code,
            rawData: e.detail.rawData,
            encryptedData: e.detail.encryptedData,
            ivStr: e.detail.iv,
            signature: e.detail.signature
          },
          success(ret) {
            if (ret.data.status != 200 || !ret.data.status) {
              wx.showModal({
                confirmText: '好的',
                content: ret.data.errmsg || '服务器开小差去了，请重试',
                showCancel: false
              });
            } else if (ret.data.status == 200) {
              wx.setStorageSync('MemberInfo', e.detail)
              wx.setStorageSync('token', ret.data.data.token)
              wx.setStorageSync('familyInfo', ret.data.data.familyInfo)
              wx.hideLoading()
              wx.reLaunch({
                url: '/pages/index/index',
              })
            }
          },
          fail(ret) {}
        })
      }
    });
  },

  /**
   * 授权成功 跳转回原页面
   */
  navigateBack() {
    wx.navigateBack();
    // let currentPage = wx.getStorageSync('currentPage');
    // wx.redirectTo({
    //   url: '/' + currentPage.route + '?' + App.urlEncode(currentPage.options)
    // });
  },

})