沙盘演示系统应用的微信小程序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
// pages/home/home.js
const storage = require('../../utils/storage.js');
const {
  get,
  post
} = require('../../api/request.js');
const app = getApp();
Page({
 
  /**
   * 页面的初始数据
   */
  data: {
    sessionId: "",
    showConfirm: false,
    myItem: {},
    waterIntakeName: "",
    image: "/images/ic_head_bg.jpg",
    userPhone: "未登录",
    userName: "点击登录",
    scrollViewHeight: 0,
    listData: [],
    isRefreshing: false,
    isWXRefreshing: false,
    errorData: '', //错误内容
    showErrorDialog: false,
    confirmBtn: {
      content: '确认'
    },
    errorDialogTitle: "关阀错误",
    showForceConfirm: false, //是否强制开阀
    lastIntakeName: "",
    isLogin: false, //是否已经登录
    showInfoDialog: false,
    showTipDialog: false,
    options: '',
    showUnBind: false
  },
 
  openValve: function (e) {
    if (this.data.isLogin) {
      wx.navigateTo({
        url: '/pages/waterIntake/waterIntake',
      })
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'error'
      })
    }
  },
  calculateScrollViewHeight: function () {
    wx.createSelectorQuery().selectAll('.list-item').boundingClientRect((rects) => {
      let totalHeight = rects.reduce((sum, rect) => sum + rect.height, 0);
      this.setData({
        scrollViewHeight: totalHeight,
      });
    }).exec();
  },
  startPullDownRefresh() {
    if (this.data.isLogin) {
      if (!this.data.isWXRefreshing) {
        var self = this;
        console.log(this.data.isRefreshing);
        this.setData({
          isRefreshing: true
        });
        this.getOpenList();
      }
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'error'
      })
    }
  },
  //获取用户数据
  getUserData() {
    get('/items')
      .then((data) => {
        this.setData({
          items: data
        });
      })
      .catch((error) => {
        console.error('Failed to fetch data:', error);
      });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    //当开阀成功后调用刷新
    console.log("onLoad:" + options.param);
    if (options.param === "1" || options.param === "2") {
      this.setData({
        options: options,
        isLogin: true,
      })
    }
 
  },
 
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    //判断本地是否保存sessionId
    if (storage.isHasKeySync("sessionId")) {
      const app = getApp();
      storage.getItem('sessionId').then((data) => {
        app.globalData.sessionId = data;
        this.setData({
          isLogin: true
        })
        if (app.globalData.sessionId) {
          this.getUserDataBySession();
        }
      }).catch((err) => {});
      storage.getItem('clientId').then((data) => {
        app.globalData.clientId = data;
        this.getOpenList();
      }).catch((err) => {});
    } else {
      //本地没有缓存微信登录
      this.wxLogin();
    }
    if (this.data.options.param === "1") {
      this.setData({
        showTipDialog: true,
        tipData: "开阀命令下发成功,因开阀需要时间,约20-60秒后可刷新快速关阀列表查看执行结果。"
      })
      setTimeout(() => {
        this.getOpenList();
      }, 20000)
 
    } else if (this.data.options.param === "2") {
      this.setData({
        showTipDialog: true,
        tipData: "预约开阀命令下发成功,当到达预约时间并且成功开阀后快速关阀列表会显示未关阀记录"
      })
      this.getOpenList();
    }
  },
  wxLogin() {
    // if (!this.data.isLogin) {
      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/wxbind/wxbind'
          })
        } 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 {
 
      }
    }).catch(error => {
      // 加载完成后隐藏加载动画
      wx.hideLoading();
      // 处理错误响应
      console.error('请求失败:', error);
    });
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    // 下拉刷新触发的逻辑,可以是请求数据等操作
    // 例如,请求数据后更新页面内容
    console.log(this.data.isRefreshing);
    this.setData({
      isWXRefreshing: true
    });
    console.log(this.data.isRefreshing);
    // 数据请求完成后,停止下拉刷新的动画
    this.getOpenList();
  },
  // 充值
  recharge() {
    if (this.data.isLogin) {
      wx.navigateTo({
        url: '/pages/rechargeCard/rechargeCard',
      })
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'error'
      })
    }
  },
  //开关阀记录
  openValveList() {
    if (this.data.isLogin) {
      wx.navigateTo({
        url: '/pages/valveList/valveList',
      })
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'error'
      })
    }
 
  },
  //问题反馈
  feedBack() {
    if (this.data.isLogin) {
      wx.navigateTo({
        url: '/pages/feedback/feedback',
      })
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'error'
      })
    }
  },
  handleChange(e) {
    const item = e.currentTarget.dataset.item;
    console.log(item);
    this.setData({
      showConfirm: true,
      waterIntakeName: item.intakeNum,
      myItem: item
    });
  },
  closeDialog() {
    console.log("closeDialog");
    this.setData({
      showConfirm: false,
      showErrorDialog: false,
      showForceConfirm: false,
      showTipDialog: false
    });
  },
  cancelDialog() {
    this.setData({
      showForceConfirm: false,
      showConfirm: false,
      showTipDialog: false,
      showUnBind: false
    });
  },
  /**
   * 关闭阀门
   * @param {*} orderNo 订单号
   * @param {*} rtuAddr 阀控器地址
   * @param {*} vcNum 虚拟卡编号
   */
  postCloseValaue(orderNo, rtuAddr, vcNum) {
    wx.showLoading({
      title: '正在关阀请稍候...', // 加载提示文字
      mask: true // 是否显示透明蒙层,防止触摸穿透,默认为 false
    });
    const app = getApp();
    const data = {
      rtuAddr: rtuAddr,
      vcNum: vcNum, //虚拟卡ID
      orderNo: orderNo,
      operator: app.globalData.sessionId //操作员
    };
    console.log("postCloseValaue" + data);
    post({
      url: "wx/valve/close_wx",
      data: data,
      isShowLoding: false,
      timeout: 185000
    }).then(response => {
 
      // 处理成功响应
      console.log('请求成功:', response);
      // 加载完成后隐藏加载动画
      wx.hideLoading();
      this.getOpenList();
      if (response.content.data.success) {
        this.setData({
          isLogin: true,
          showTipDialog: true,
          tipData: "关阀命令下发成功,约20-60秒后可刷新快速关阀列表查看执行结果。"
        })
        setTimeout(() => {
          this.getOpenList();
        }, 40000)
      } else {
        wx.showToast({
          title: '命令执行失败',
          icon: 'error',
          duration: 3000
        })
      }
 
    }).catch(error => {
      wx.hideLoading();
      this.setData({
        showErrorDialog: true,
        errorData: error.msg,
        errorDialogTitle: "关阀错误"
      })
      // 处理错误响应
      console.error('请求失败:', error);
    });
  },
  /**
   * 获取为关阀记录
   */
  getOpenList() {
    if (this.data.isLogin) {
      const app = getApp();
      const params = {
        url: 'wx/valve/get',
        data: {
          operator: app.globalData.clientId
        }
      };
      get(params).then(data => {
        this.setData({
          listData: data.content,
          isRefreshing: false, // 将triggered属性设置为false,表示下拉刷新已完成
          isWXRefreshing: false, // 将triggered属性设置为false,表示下拉刷新已完成
        })
        this.updateDisplayText();
      }).catch(err => {
        // 错误回调
        this.setData({
          isRefreshing: false, // 将triggered属性设置为false,表示下拉刷新已完成
          isWXRefreshing: false, // 将triggered属性设置为false,表示下拉刷新已完成
        })
        wx.showToast({
          title: err.msg,
          icon: 'error',
          duration: 3000
        })
      });
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'error'
      })
      this.setData({
        isRefreshing: false, // 将triggered属性设置为false,表示下拉刷新已完成
        isWXRefreshing: false, // 将triggered属性设置为false,表示下拉刷新已完成
      })
    }
 
  },
  /**
   * 确认关闭回调
   * @param {} item 
   */
  confirmDialog() {
    this.setData({
      showConfirm: false
    });
    this.postCloseValaue(this.data.myItem.orderNo, this.data.myItem.rtuAddr, this.data.myItem.vcNum);
  },
  //根据session获取农户信息
  getUserDataBySession() {
    const app = getApp();
    const params = {
      url: 'wx/client/simple_info',
      data: {
        sessionId: app.globalData.sessionId
      }
    };
    get(params).then(data => {
      this.setData({
        userName: data.content.clientName,
        userPhone: this.maskPhoneNumber(data.content.phone),
        isLogin: true
      })
    }).catch(err => {
      // 错误回调
      wx.showToast({
        title: err.msg,
        icon: 'error',
        duration: 3000
      })
    })
  },
  maskPhoneNumber(phoneNumber) {
    if (phoneNumber.length !== 11) {
      throw new Error("Phone number must be 11 digits");
    }
    // 使用正则表达式替换中间四位数字为星号
    const maskedPhoneNumber = phoneNumber.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2");
    return maskedPhoneNumber;
  },
 
  closeDialog() {
    this.setData({
      showErrorDialog: false
    })
  },
  /**
   * 扫码开阀
   */
  scenCode() {
    if (this.data.isLogin) {
      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 {
            wx.navigateTo({
              url: '/pages/openCard/openCard?intakeName=' + res.result,
            })
            // that.postOppenValva()
          }
        },
        fail(err) {
          console.error(err);
        }
      })
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'error'
      })
    }
 
  },
  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.sessionId, //操作员
      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');
    }
 
  },
  //强制删除
  onDelete(e) {
    const item = e.currentTarget.dataset.item;
    const that = this;
    wx.showLoading({
      title: '正在强制删除请稍候...', // 加载提示文字
      mask: true // 是否显示透明蒙层,防止触摸穿透,默认为 false
    });
    const data = {
      vcNum: item.vcNum, //取水口ID
      rtuAddr: item.rtuAddr, //阀控器地址
    };
    post({
      url: "wx/valve/deleteUnclosed",
      data: data,
      timeout: 180000
    }).then(response => {
      // 处理成功响应
      console.log('请求成功:', response);
      // 加载完成后隐藏加载动画
      wx.hideLoading();
      //重新获取列表刷新数据
      this.getOpenList();
    }).catch(error => {
      // 加载完成后隐藏加载动画
      wx.hideLoading();
      // 处理错误响应
      console.error('请求失败:', error);
    });
  },
  //修改按钮文字
  updateDisplayText() {
    const updatedList = this.data.listData.map(item => {
      let displayText = '';
      if (item.planned) {
        displayText = '取消';
      } else {
        displayText = "关阀"
      }
      let deleteText = "删除"
      let time;
      if (!item.dt) {
        time = "暂无"
      } else {
        time = this.extractTime(item.dt)
      }
      if (item.waterInstant===null) {
        item.waterInstant = "暂无"
      }
 
      return {
        ...item,
        displayText,
        deleteText,
        time
      }; // 保留所有其他字段,并添加 displayText 字段
    });
    // 更新列表数据
    this.setData({
      listData: updatedList
    });
  },
  //解绑
  unbind() {
    this.setData({
      showUnBind: true
    })
  },
  //确认解绑
  unBindPost() {
    this.setData({
      showUnBind: false
    })
    wx.showLoading({
      title: '正在解绑请稍候...', // 加载提示文字
      mask: true // 是否显示透明蒙层,防止触摸穿透,默认为 false
    });
    const data = {
      sessionId: getApp().globalData.sessionId //取水口ID
    };
    post({
      url: 'wx/client/unbind',
      data: data,
      useParams: true
    }).then(response => {
      // 处理成功响应
      console.log('请求成功:', response);
      // 加载完成后隐藏加载动画
      wx.hideLoading();
      //清空数据
      this.setData({
        userPhone: "请登录",
        userName: "未登录",
        listData: [],
        isLogin: false
      })
      app.globalData.sessionId = "";
      app.globalData.clientId = ""
      storage.removeItem("sessionId")
      storage.removeItem("clientId")
      wx.showToast({
        title: '解绑成功',
        icon: 'success',
        duration: 3000
      })
    }).catch(error => {
      // 加载完成后隐藏加载动画
      wx.hideLoading();
      // 处理错误响应
      console.error('请求失败:', error);
      wx.showToast({
        title: '解绑失败',
        icon: 'error',
        duration: 3000
      })
    });
  },
  //点击提示按钮
  infoShow() {
    this.setData({
      showInfoDialog: true
    })
  },
  //提示窗确认按钮
  confirmBtnInfoDialog() {
    this.setData({
      showInfoDialog: false
    })
  },
  //处理时间去掉年月日
  extractTime(datetimeString) {
    const formattedDate = datetimeString.replace(" ", "T");
    const date = new Date(formattedDate);
    // 获取小时、分钟和秒
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    return `${hours}:${minutes}:${seconds}`;
  }
})