管灌系统农户端微信小程序(嘉峪关应用)
pages/home/home.js
@@ -4,6 +4,7 @@
  get,
  post
} = require('../../api/request.js');
const { PROJECT_URLS } = require('../../api/config.js');
Page({
  /**
@@ -15,12 +16,23 @@
    myItem: {},
    waterIntakeName: "",
    image: "/images/ic_head_bg.jpg",
    userPhone: "158****0723",
    userName: "张三",
    userPhone: "",
    userName: "请登录",
    scrollViewHeight: 0,
    listData: [],
    isRefreshing: false,
    isWXRefreshing: false
    isWXRefreshing: false,
    errorData: '', //错误内容
    showErrorDialog: false,
    confirmBtn: {
      content: '确认'
    },
    errorDialogTitle: "关阀错误",
    showForceConfirm: false, //是否强制开阀
    lastIntakeName: "",
    showProjectDialog: false,
    selectedProject: '',
    avatarTapCount: 0
  },
  openValve: function (e) {
@@ -67,41 +79,74 @@
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 使用 wx.nextTick 等待页面渲染完成
    wx.nextTick(() => {
      this.calculateScrollViewHeight();
    // 检查是否已选择项目
    const { PROJECT_URLS } = require('../../api/config.js');
    storage.getItem('selectedProject').then((project) => {
      if (project) {
        this.setData({
          selectedProject: project
        });
        // 确保全局变量存在
        getApp().globalData = getApp().globalData || {};
        // 设置 baseUrl
        const baseUrl = PROJECT_URLS[project];
        getApp().globalData.baseUrl = baseUrl;
        getApp().globalData.selectedProject = project;
        // 根据项目设置对应的tag
        if (project === 'JYG') {
          getApp().globalData.tag = 'ym'; // 嘉峪关项目对应tag为ym
        } else if (project === 'MQ') {
          getApp().globalData.tag = 'mq'; // 民勤项目对应tag为mq
        }
        console.log('加载已保存的项目:', project, '域名:', baseUrl, 'tag:', getApp().globalData.tag);
        // 检查登录状态
        if (!getApp().globalData.isLoggedIn) {
          this.checkLoginStatus();
          return; // 如果未登录,等待跳转到登录页面
        }
      } else {
        // 首次进入,显示项目选择弹窗
        this.setData({
          showProjectDialog: true
        });
        return; // 等待用户选择项目
      }
      //判断本地是否保存sessionId
      // 使用 wx.nextTick 等待页面渲染完成
      wx.nextTick(() => {
        this.calculateScrollViewHeight();
      });
      //当开阀成功后调用刷新
      console.log("onLoad:" + options.param);
      if (options.param) {
        wx.showToast({
          title: '开阀成功',
          icon: 'success',
          duration: 3000
        })
        this.getOpenList();
      }
      this.initData();
    }).catch(err => {
      console.error('Failed to get selectedProject:', err);
      // 出错时也显示项目选择弹窗
      this.setData({
        showProjectDialog: true
      });
    });
    //当开阀成功后调用刷新
    console.log("onLoad:" + options.param);
    if (options.param) {
      wx.showToast({
        title: '开阀成功',
        icon: 'success',
        duration: 3000
      })
      this.getOpenList();
    }
    this.getUserDataBySession();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    //判断本地是否保存sessionId
    if (storage.isHasKeySync("sessionId")) {
      storage.getItem('sessionId').then((data) => {
        this.setData({
          sessionId: data
        });
        if (sessionId !== "") {}
      }).catch((err) => {
        console.error('Failed to load parameter:', err);
      });
    } else {
      console.log('Failed to load parameter:false');
    }
    this.getOpenList();
  },
  /**
@@ -154,13 +199,21 @@
  },
  recharge() {
    wx.navigateTo({
      url: '/pages/rechargeCard/rechargeCard',
    // wx.navigateTo({
    //   url: '/pages/rechargeCard/rechargeCard',
    // })
    wx.showToast({
      title: '暂未开放',
      icon: 'none'
    })
  },
  openValveList() {
    wx.navigateTo({
      url: '/pages/valveList/valveList',
    // wx.navigateTo({
    //   url: '/pages/valveList/valveList',
    // })
    wx.showToast({
      title: '暂未开放',
      icon: 'none'
    })
  },
  feedBack() {
@@ -179,7 +232,16 @@
    });
  },
  closeDialog() {
    console.log("closeDialog");
    this.setData({
      showConfirm: false,
      showErrorDialog: false,
      showForceConfirm: false
    });
  },
  cancelDialog() {
    this.setData({
      showForceConfirm: false,
      showConfirm: false
    });
  },
@@ -199,13 +261,14 @@
      rtuAddr: rtuAddr,
      vcNum: vcNum, //虚拟卡ID
      orderNo: orderNo,
      operator: app.globalData.sessionId //操作员
      operator: app.globalData.operator //操作员
    };
    console.log("postCloseValaue" + data);
    post({
      url: "wx/valve/close_wx",
      data: data,
      isShowLoding: false
      isShowLoding: false,
      timeout: 185000
    }).then(response => {
      // 处理成功响应
@@ -220,13 +283,11 @@
      })
    }).catch(error => {
      wx.hideLoading();
      if (error.code === "1002") {
        wx.showToast({
          title: '关阀失败',
          icon: 'error',
          duration: 3000 // 提示的持续时间,单位毫秒
        })
      }
      this.setData({
        showErrorDialog: true,
        errorData: error.msg,
        errorDialogTitle: "关阀错误"
      })
      // 处理错误响应
      console.error('请求失败:', error);
@@ -240,7 +301,7 @@
    const params = {
      url: 'wx/valve/get',
      data: {
        operator: app.globalData.sessionId
        operator: app.globalData.operator
      }
    };
    get(params).then(data => {
@@ -253,6 +314,12 @@
      // 错误回调
      this.setData({
        isRefreshing: false, // 将triggered属性设置为false,表示下拉刷新已完成
        isWXRefreshing: false, // 将triggered属性设置为false,表示下拉刷新已完成
      })
      wx.showToast({
        title: err.msg,
        icon: 'error',
        duration: 3000
      })
    });
  },
@@ -270,7 +337,7 @@
  getUserDataBySession() {
    const app = getApp();
    const params = {
      url: 'sell/client/simple_info',
      url: 'wx/client/simple_info',
      data: {
        sessionId: app.globalData.sessionId
      }
@@ -282,7 +349,11 @@
      })
    }).catch(err => {
      // 错误回调
      wx.showToast({
        title: err.msg,
        icon: 'error',
        duration: 3000
      })
    })
  },
  maskPhoneNumber(phoneNumber) {
@@ -292,8 +363,329 @@
    // 使用正则表达式替换中间四位数字为星号
    const maskedPhoneNumber = phoneNumber.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2");
    return maskedPhoneNumber;
  }
  },
  closeDialog() {
    this.setData({
      showErrorDialog: false
    })
  },
  /**
   * 扫码开阀
   */
  scenCode() {
    const that = this;
    wx.scanCode({
      success(res) {
        console.log(res.result); // 当且仅当扫码为非微信二维码时,会返回result
        if (res.result.startsWith("content://")) {
          let jsonStr = res.result.replace("content://", "")
          try {
            that.saveData(jsonStr)
          } catch (error) {
            console.error('Error parsing JSON:', error);
          }
        } else {
          that.postOppenValva(res.result)
        }
      },
      fail(err) {
        console.error(err);
      }
    })
  },
  confirmForceDialog() {
    console.log("confirmForceDialog");
    this.setData({
      showForceConfirm: false
    })
    this.postOppenValva(this.data.lastIntakeName, true)
  },
  /**
   *
   * @param {*} intakeName
   */
  postOppenValva(intakeName, isforce) {
    const that = this;
    wx.showLoading({
      title: '正在开阀请稍候...', // 加载提示文字
      mask: true // 是否显示透明蒙层,防止触摸穿透,默认为 false
    });
    const app = getApp();
    that.setData({
      lastIntakeName: intakeName
    })
    const data = {
      intakeName: intakeName, //取水口ID
      // vcId: vcId, //虚拟卡ID
      operator: app.globalData.operator, //操作员
      forceOpen: !!isforce // 使用逻辑非操作符 !! 来确保 isForce 是布尔值
    };
    post({
      url: "wx/valve/open_wx",
      data: data,
      timeout: 180000
    }).then(response => {
      // 处理成功响应
      console.log('请求成功:', response);
      // 加载完成后隐藏加载动画
      wx.hideLoading();
      //完成后回到首页
      wx.reLaunch({
        url: '/pages/home/home?param=true' // 首页的路径,根据实际情况填写
      });
    }).catch(error => {
      // 加载完成后隐藏加载动画
      wx.hideLoading();
      // 处理错误响应
      console.error('请求失败:', error);
      if (error.code === "10005") {
        that.setData({
          showForceConfirm: true
        })
      } else {
        that.setData({
          showErrorDialog: true,
          errorData: error.msg,
          errorDialogTitle: "开阀错误"
        })
      }
    });
  },
  /**
   * 扫描后保存用户id和tag
   */
  saveData(userData) {
    storage.setItem("userData", userData).then(() => {
      this.initData();
    }).catch((error) => {});
  },
  //进入界面获取界面数据
  initData() {
    const app = getApp();
    console.log("tag>>>>:" +app.globalData.tag)
    if (storage.isHasKeySync("userData")) {
      storage.getItem('userData').then((data) => {
        let jsonObj = JSON.parse(data);
        app.globalData.sessionId = jsonObj.sessionId;
        app.globalData.tag = jsonObj.tag;
        this.getUserDataBySession();
        this.getOpenList();
        console.log("userData>>>>>>>" + data)
      }).catch((err) => {
        console.error('Failed to load parameter:', err);
      });
    } else {
      this.getUserDataBySession();
      this.getOpenList();
      console.log('Failed to load parameter:false');
    }
  },
  // 处理头像点击
  handleAvatarTap() {
    this.setData({
      avatarTapCount: this.data.avatarTapCount + 1
    });
    if (this.data.avatarTapCount >= 5) {
      this.setData({
        showProjectDialog: true,
        avatarTapCount: 0
      });
    }
  },
  // 处理弹窗可见性变化
  onVisibleChange(e) {
    // 如果尝试关闭弹窗且没有选择项目,则阻止关闭
    if (!e.detail.visible && !this.data.selectedProject) {
      return;
    }
    this.setData({ showProjectDialog: e.detail.visible });
  },
  // 处理项目选择变化
  onProjectChange(event) {
    console.log('选择的项目:', event.detail.value);
    this.setData({
      selectedProject: event.detail.value
    });
  },
  // 处理项目选择确认
  handleProjectConfirm() {
    if (!this.data.selectedProject) {
      wx.showToast({
        title: '请选择项目',
        icon: 'none'
      });
      return;
    }
    const projectName = this.data.selectedProject === 'JYG' ? '嘉峪关项目' : '民勤项目';
    // 保存项目选择到本地存储
    storage.setItem('selectedProject', this.data.selectedProject).then(() => {
      // 更新 BASEURL
      const { PROJECT_URLS } = require('../../api/config.js');
      const baseUrl = PROJECT_URLS[this.data.selectedProject];
      // 直接修改全局变量
      getApp().globalData = getApp().globalData || {};
      getApp().globalData.baseUrl = baseUrl;
      getApp().globalData.selectedProject = this.data.selectedProject;
      // 根据项目设置对应的tag
      if (this.data.selectedProject === 'JYG') {
        getApp().globalData.tag = 'ym'; // 嘉峪关项目对应tag为ym
      } else if (this.data.selectedProject === 'MQ') {
        getApp().globalData.tag = 'mq'; // 民勤项目对应tag为mq
      }
      console.log('已切换到项目:', projectName, '域名:', baseUrl, 'tag:', getApp().globalData.tag);
      this.setData({
        showProjectDialog: false
      });
      wx.showToast({
        title: `已选择${projectName}`,
        icon: 'success',
        duration: 2000
      });
      // 检查登录状态
      // setTimeout(() => {
      //   this.checkLoginStatus();
      // }, 500);
    }).catch(err => {
      console.error('保存项目选择失败:', err);
      wx.showToast({
        title: '保存失败,请重试',
        icon: 'success',
        duration: 2000
      });
    });
  },
  // 检查登录状态
  checkLoginStatus() {
    const app = getApp();
    // 检查是否已登录
    if (app.globalData.isLoggedIn && app.globalData.sessionId) {
      // 已登录,重新加载页面
      wx.reLaunch({
        url: '/pages/home/home'
      });
    } else {
      // 尝试从本地存储获取用户信息
      storage.getItem('userInfo').then(userInfoStr => {
        if (userInfoStr) {
          try {
            const userInfo = JSON.parse(userInfoStr);
            // 验证用户信息是否有效
            if (userInfo && userInfo.sessionId) {
              // 恢复登录状态
              app.globalData.sessionId = userInfo.sessionId;
              app.globalData.token = userInfo.token;
              app.globalData.userInfo = userInfo;
              app.globalData.isLoggedIn = true;
              // 已登录,重新加载页面
              wx.reLaunch({
                url: '/pages/home/home'
              });
              return;
            }
          } catch (e) {
            console.error('解析用户信息失败:', e);
          }
        }
        // 未登录,跳转到登录页面
        wx.redirectTo({
          url: `/pages/login/login?project=${this.data.selectedProject}`
        });
      }).catch(err => {
        console.error('获取用户信息失败:', err);
        // 未登录,跳转到登录页面
        wx.redirectTo({
          url: `/pages/login/login?project=${this.data.selectedProject}`
        });
      });
    }
  },
  wxLogin(){
    if(!getApp().globalData.isLoggedIn){
      const that = this;
      wx.login({
        success: function (res) {
          if (res.code) {
            var code = res.code;
            console.log(code);
            // 将code发送到服务器获取openid
            that.codeLogin(code);
          } else {
            console.log('登录失败!' + res.errMsg);
          }
        }
      });
    }
  },
  //微信code登录
  codeLogin(codeData) {
    wx.showLoading({
      title: '正在登录请稍候...', // 加载提示文字
      mask: true // 是否显示透明蒙层,防止触摸穿透,默认为 false
    });
    const data = {
      code: codeData, //临时登录凭证
    };
    post({
      url: "wx/client/code_login",
      data: data,
    }).then(response => {
      // 处理成功响应
      console.log('请求成功:', response);
      // 加载完成后隐藏加载动画
      wx.hideLoading();
      if (response.code === "0001") {
        //假如为空则跳转到绑定界面
        if (response.content.client.clientId === "") {
          wx.navigateTo({
            url: '/pages/login/login'
          })
        } else {
          //缓存在本地
          this.setData({
            isLogin: true
          })
          getApp().globalData.sessionId = response.content.client.sessionId
          storage.setItem("sessionId", response.content.client.sessionId)
          getApp().globalData.clientId = response.content.client.clientId
          storage.setItem("clientId", response.content.client.clientId)
          this.initData();
        }
      } else {
        wx.showToast({
          title: 'title',
          icon: 'error',
          duration: 2000
        })
      }
    }).catch(error => {
      // 加载完成后隐藏加载动画
      wx.hideLoading();
      // 处理错误响应
      console.error('请求失败:', error);
    });
  },
})