管灌系统农户端微信小程序(嘉峪关应用)
zuoxiao
2025-03-06 91751b1b9b16c0044e16ad80c237b7275a409046
pages/login/login.js
@@ -1,4 +1,8 @@
const app = getApp();
const storage = require('../../utils/storage.js');
const {
  post
} = require('../../api/request.js');
Page({
@@ -6,79 +10,217 @@
   * 页面的初始数据
   */
  data: {
    mobile: '',
    code: '',
    codeSent: false,
    countdown: 60,
    phone: '',
    verificationCode: '',
    codeText: '获取验证码',
    counting: false,
    countDown: 60,
    projectName: '嘉峪关项目', // 默认项目名称
    selectedProject: 'JYG', // 默认项目代码
    showErrorDialog: false
  },
  bindMobileInput: function (e) {
  /**
   * 绑定手机号输入
   */
  bindPhoneInput: function (e) {
    this.setData({
      mobile: e.detail.value,
      phone: e.detail.value
    });
  },
  sendCode: function () {
    if (!this.data.mobile) {
  /**
   * 绑定验证码输入
   */
  bindCodeInput: function (e) {
    this.setData({
      verificationCode: e.detail.value
    });
  },
  /**
   * 发送验证码
   */
  sendVerificationCode: function () {
    const {
      phone,
      counting
    } = this.data;
    // 如果正在倒计时,则不允许再次发送
    if (counting) {
      return;
    }
    // 验证手机号格式
    if (!/^1\d{10}$/.test(phone)) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none',
        duration: 2000,
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }
    // 在这里处理发送验证码的逻辑,可以调用后台接口实现
    // 以下是一个简单的示例,仅作参考
    wx.showToast({
      title: '验证码已发送',
      icon: 'success',
      duration: 2000,
    });
    // 开始倒计时
    this.startCountDown();
    this.setData({
      codeSent: true,
    });
    // 启动倒计时
    this.startCountdown();
    // 发送验证码请求
    this.postCode();
  },
  //倒计时
  startCountdown: function () {
    let that = this;
    let timer = setInterval(function () {
      let countdown = that.data.countdown - 1;
      that.setData({
        countdown: countdown,
  /**
   * 开始倒计时
   */
  startCountDown: function () {
    this.setData({
      counting: true,
      countDown: 60
      });
      if (countdown <= 0) {
    const timer = setInterval(() => {
      if (this.data.countDown <= 1) {
        clearInterval(timer);
        that.setData({
          codeSent: false,
          countdown: 60,
        this.setData({
          counting: false,
          codeText: '获取验证码'
        });
      } else {
        this.setData({
          countDown: this.data.countDown - 1,
          codeText: `${this.data.countDown - 1}秒后重发`
        });
      }
    }, 1000);
    // 保存timer引用,以便在页面卸载时清除
    this.countDownTimer = timer;
  },
  /**
   * 停止倒计时
   */
  stopCountDown: function () {
    if (this.countDownTimer) {
      clearInterval(this.countDownTimer);
    }
    this.setData({
      counting: false,
      codeText: '获取验证码'
    });
  },
  /**
   * 登录
   */
  login: function (e) {
    console.log("login")
    let userName = "张三"
    wx.navigateTo({
      url: '/pages/wxbind/wxbind'
    })
  login: function () {
    const {
      phone,
      verificationCode
    } = this.data;
    // 验证手机号和验证码
    if (!/^1\d{10}$/.test(phone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }
    if (!/^\d{6}$/.test(verificationCode)) {
      wx.showToast({
        title: '请输入6位验证码',
        icon: 'none'
      });
      return;
    }
    // 显示加载中
    wx.showLoading({
      title: '登录中...',
      mask: true
    });
    this.wsLogin();
    // 发送登录请求
    post('/api/loginByCode', {
      phone: phone,
      code: verificationCode,
      projectCode: this.data.selectedProject
    }).then(res => {
      wx.hideLoading();
      if (res.code === 0 && res.data) {
        // 保存用户信息和token
        storage.setUserInfo(res.data);
        storage.setToken(res.data.token);
        // 跳转到首页
        wx.switchTab({
          url: '/pages/index/index'
        });
      } else {
        wx.showToast({
          title: res.msg || '登录失败,请重试',
          icon: 'none'
        });
      }
    }).catch(err => {
      wx.hideLoading();
      console.error('登录失败', err);
      wx.showToast({
        title: '网络异常,请重试',
        icon: 'none'
      });
    });
  },
  /**
   * 跳转到注册页面
   */
  goToRegister: function () {
    wx.showToast({
      title: '注册功能暂未开放',
      icon: 'none',
      duration: 2000
    });
  },
  /**
   * 跳转到忘记密码页面
   */
  goToForgetPassword: function () {
    wx.showToast({
      title: '找回密码功能暂未开放',
      icon: 'none',
      duration: 2000
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
  onLoad: function (options) {
    // 获取选择的项目
    if (options.project) {
      this.setData({
        selectedProject: options.project,
        projectName: options.project === 'JYG' ? '嘉峪关项目' : '民勤项目'
      });
    } else {
      // 尝试从本地存储获取已选择的项目
      storage.getItem('selectedProject').then(project => {
        if (project) {
          this.setData({
            selectedProject: project,
            projectName: project === 'JYG' ? '嘉峪关项目' : '民勤项目'
          });
        }
      }).catch(err => {
        console.error('获取已选择项目失败:', err);
      });
    }
  },
  /**
@@ -106,7 +248,11 @@
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 清除验证码倒计时定时器
    if (this.countDownTimer) {
      clearInterval(this.countDownTimer);
      this.countDownTimer = null;
    }
  },
  /**
@@ -129,7 +275,83 @@
  onShareAppMessage() {
  },
  //获取验证码
  postCode: function () {
    const params = {
      url: 'wx/client/send_sms?phoneNumber=' + this.data.phone
    };
    post(params)
      .then((data) => {
        wx.showToast({
          title: '验证码已发送',
          icon: 'success',
          duration: 2000,
        });
        this.setData({
          codeSent: true,
        });
        // 启动倒计时
        this.startCountdown();
      })
      .catch((error) => {
        wx.showToast({
          title: error.msg,
          icon: 'none'
        });
        console.error('Failed to add item:', error);
      });
  },
  wsLogin() {
    wx.login({
      success: res => {
        if (res.code) {
          console.log('登录成功,获取到的code:', res.code);
          // 发送 res.code 到后台服务器换取 openId, sessionKey, unionId
          this.verify(res.code)
        } else {
          console.log('登录失败!' + res.errMsg);
        }
      }
    });
  },
  //用户绑定
  verify(wxCode) {
    const params = {
      url: 'wx/client/verify',
      data: {
        phoneNumber: this.data.phone,
        securityCode: this.data.verificationCode,
        code: wxCode
      }
    };
    post(params)
      .then((data) => {
        wx.hideLoading();
        getApp().globalData.sessionId = String(data.content.sessionId)
        storage.setItem("sessionId", String(data.content.sessionId))
        getApp().globalData.clientId = String(data.content.clientId)
        storage.setItem("clientId", String(data.content.clientId))
        this.bindSuccess();
      })
      .catch((error) => {
        wx.hideLoading();
        wx.showToast({
          title: error.msg,
          icon: 'error',
          duration: 3000,
        });
        console.error('Failed to add item:', error);
      });
  },
  bindSuccess: function () {
    if (!this.data.isButtonEnabled) return;
    wx.showToast({
      title: '绑定成功',
      icon: 'success'
    });
    // 跳转到 TabBar 页面
    wx.redirectTo({
      url: '/pages/home/home' // 这里填写你想要跳转的 TabBar 页面路径
    });
  },
})