管灌系统农户端微信小程序(嘉峪关应用)
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
const app = getApp();
const {
  get,
  post
} = require('../../api/request');
const dayjs = require('dayjs');
 
Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 表单数据
    planCode: '', // 计划编号
    startTime: '', // 灌溉开始时间
    pickerValue: '', // 时间选择器的值
    timePickerVisible: false, // 时间选择器是否可见
    timeInfoVisible: false, // 时间提示弹窗是否可见
    // 项目选择器相关
    projectPickerVisible: false,
    projectPickerValue: [],
    selectedProject: null,
    projectOptions: [],
    totalDuration: 0, // 添加总灌溉时间
    // 项目列表
    projectList: [],
    // 时间选择器选项
    timeOptions: [],
    // 轮灌组列表刷新状态
    isRefreshing: false
  },
 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 生成计划编号
    this.generatePlanCode();
    // 设置时间选择器的初始值
    const now = dayjs();
    this.setData({
      pickerValue: now.add(8.5, 'hour').format('YYYY-MM-DD HH:mm')
    });
    // 获取项目列表
    this.fetchProjects();
  },
 
  /**
   * 生成计划编号
   */
  generatePlanCode: function () {
    const now = dayjs();
    const dateStr = now.format('YYYY-MM-DD');
    const randomNum = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
    const planCode = `${dateStr}${-randomNum}`;
    this.setData({
      planCode
    });
  },
 
  /**
   * 获取项目列表
   */
  fetchProjects: function (isShowDiaolog) {
    return get({
      url: '/wx/irrigation/getSimpleProjects',
      isShowLoding: true
    }).then(res => {
      if (res.success) {
        const projectList = res.content.map(project => ({
          id: project.projectId,
          name: project.projectName,
          groupCount: project.groupCount,
          groups: []
        }));
 
        const projectOptions = projectList.map(project => ({
          label: project.name,
          value: project.id
        }));
 
        this.setData({
          projectList,
          projectOptions
        });
        if (isShowDiaolog) {
          this.setData({
            projectPickerVisible: true
          });
        }
      } else {
        wx.showToast({
          title: res.msg || '获取项目列表失败',
          icon: 'none'
        });
        return Promise.reject(new Error(res.msg || '获取项目列表失败'));
      }
    }).catch(err => {
      console.error('获取项目列表失败:', err);
      wx.showToast({
        title: '获取项目列表失败',
        icon: 'none'
      });
      return Promise.reject(err);
    });
  },
 
  /**
   * 获取轮灌组列表
   */
  fetchGroups: function (projectId) {
    return get({
      url: '/wx/irrigation/getSimpleGroups',
      data: {
        projectId: projectId,
      },
      isShowLoding: true
    }).then(res => {
      if (res.success) {
        console.log('轮灌组数据:', res.content);
 
        // 更新选中项目的轮灌组信息
        const projectList = this.data.projectList.map(project => {
          if (project.id === projectId) {
            return {
              ...project,
              groups: res.content.map(group => ({
                id: group.groupId,
                name: group.groupCode,
                duration: group.defaultDuration || 0,
                selected: false,
                intakeCount: group.intakeCount
              }))
            };
          }
          return project;
        });
 
        // 更新选中的项目
        const selectedProject = projectList.find(project => project.id === projectId);
        console.log('更新后的选中项目:', selectedProject);
 
        this.setData({
          projectList,
          selectedProject
        }, () => {
          // 计算总时间
          this.calculateTotalDuration();
        });
      } else {
        wx.showToast({
          title: res.msg || '获取轮灌组列表失败',
          icon: 'none'
        });
        return Promise.reject(new Error(res.msg || '获取轮灌组列表失败'));
      }
    }).catch(err => {
      console.error('获取轮灌组列表失败:', err);
      wx.showToast({
        title: '获取轮灌组列表失败',
        icon: 'none'
      });
      return Promise.reject(err);
    });
  },
 
  /**
   * 显示时间选择器
   */
  showTimePicker: function () {
    // 如果没有选择时间,使用当前时间
    if (!this.data.pickerValue) {
      const now = dayjs();
      this.setData({
        pickerValue: now.format('YYYY-MM-DD HH:mm')
      });
    }
 
    this.setData({
      timePickerVisible: true
    });
  },
 
  /**
   * 时间选择器确认回调
   */
  onTimePickerConfirm: function (e) {
    const {
      value
    } = e.detail;
    this.setData({
      timePickerVisible: false,
      startTime: value
    });
  },
 
  /**
   * 时间选择器取消回调
   */
  onTimePickerCancel: function () {
    this.setData({
      timePickerVisible: false
    });
  },
 
  /**
   * 切换项目展开/折叠状态
   */
  toggleProject: function (e) {
    const index = e.currentTarget.dataset.index;
    const currentValue = this.data.projectList[index].expanded;
 
    // 创建新的项目列表,先将所有项目设为折叠状态
    const newProjectList = this.data.projectList.map((item, idx) => {
      return {
        ...item,
        expanded: false
      };
    });
 
    // 如果当前点击的项目已经是展开状态,则保持所有项目折叠
    // 否则,将当前点击的项目设为展开状态
    if (!currentValue) {
      newProjectList[index].expanded = true;
    }
 
    this.setData({
      projectList: newProjectList
    });
  },
 
  /**
   * 切换轮灌组选中状态
   */
  toggleGroupSelection: function (e) {
    const projectIndex = e.currentTarget.dataset.projectIndex;
    const groupIndex = e.currentTarget.dataset.groupIndex;
    const key = `projectList[${projectIndex}].groups[${groupIndex}].selected`;
    const currentValue = this.data.projectList[projectIndex].groups[groupIndex].selected;
 
    this.setData({
      [key]: !currentValue
    });
 
    // 更新项目总时长
    this.updateProjectTotalDuration(projectIndex);
  },
 
  /**
   * 处理时长输入
   */
  onDurationInput: function (e) {
    const {
      groupIndex
    } = e.currentTarget.dataset;
    const duration = parseInt(e.detail.value) || 0;
 
    const selectedProject = {
      ...this.data.selectedProject
    };
    selectedProject.groups[groupIndex].duration = duration;
 
    this.setData({
      selectedProject
    }, () => {
      // 输入时长后重新计算总时间
      this.calculateTotalDuration();
    });
  },
 
  /**
   * 计算并更新项目总时长
   */
  updateProjectTotalDuration: function (projectIndex) {
    const project = this.data.projectList[projectIndex];
    let totalDuration = 0;
 
    // 计算所有选中的轮灌组的时长总和
    project.groups.forEach(group => {
      if (group.selected) {
        totalDuration += parseInt(group.duration) || 0;
      }
    });
 
    // 更新项目总时长
    const totalDurationKey = `projectList[${projectIndex}].totalDuration`;
    this.setData({
      [totalDurationKey]: totalDuration
    });
  },
 
  /**
   * 阻止事件冒泡
   */
  stopPropagation: function (e) {
    if (e && e.stopPropagation) {
      e.stopPropagation();
    }
    return false;
  },
 
  /**
   * 跳转到轮灌组详情页
   */
  navigateToGroupDetail: function (e) {
    const { groupIndex } = e.currentTarget.dataset;
    const group = this.data.selectedProject.groups[groupIndex];
    
    // 构建URL参数
    const params = {
      projectName: this.data.selectedProject.name,
      groupName: group.name,
      groupId: group.id
    };
    
    // 构建URL查询字符串
    const queryString = Object.keys(params)
      .map(key => `${key}=${encodeURIComponent(params[key])}`)
      .join('&');
    
    // 跳转到轮灌组详情页
    wx.navigateTo({
      url: `/pages/groupDetail/groupDetail?${queryString}`
    });
  },
 
  /**
   * 确认按钮点击事件
   */
  onConfirm: function () {
    const {
      planCode,
      startTime,
      selectedProject
    } = this.data;
 
    if (!planCode) {
      wx.showToast({
        title: '请输入计划编号',
        icon: 'none'
      });
      return;
    }
 
    if (!selectedProject) {
      wx.showToast({
        title: '请选择项目',
        icon: 'none'
      });
      return;
    }
 
    // 构建上报数据
    const schedules = selectedProject.groups.map(group => ({
      groupId: group.id,
      duration: parseInt(group.duration) || 0
    }));
 
    const requestData = {
      projectId: selectedProject.id,
      planName: planCode,
      startupMode: startTime ? 2 : 1,
      operatorId: app.globalData.clientId,
      schedules: schedules
    };
 
    // 如果有开始时间,添加到请求数据中
    if (startTime) {
      requestData.planStartTime = startTime;
    }
 
    // 发送请求
    post({
      url: '/wx/plan/createPlan',
      data: requestData,
      isShowLoding: true
    }).then(res => {
      if (res.success) {
        wx.showToast({
          title: '创建成功',
          icon: 'success'
        });
        // 返回上一页,并传递参数指示需要刷新列表并切换到当前计划列表
        setTimeout(() => {
          // 使用全局变量标记需要刷新
          const app = getApp();
          app.globalData.needRefreshIrrigationList = true;
 
          // 直接返回上一页
          wx.navigateBack({
            delta: 1
          });
        }, 1500);
      } else {
        wx.showToast({
          title: res.msg || '创建失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      console.error('创建计划失败:', err);
      wx.showToast({
        title: '创建失败',
        icon: 'none'
      });
    });
  },
 
  // 显示项目选择器
  showProjectPicker() {
    this.fetchProjects(true)
 
  },
 
  // 项目选择器确认
  onProjectPickerConfirm(e) {
    const {
      value
    } = e.detail;
    console.log('选择的项目ID:', value[0]); // 添加日志查看数据
    const selectedProject = this.data.projectList.find(project => project.id === value[0]);
    console.log('找到的项目:', selectedProject); // 添加日志查看数据
 
    this.setData({
      projectPickerVisible: false,
      selectedProject: selectedProject,
      projectPickerValue: value
    }, () => {
      // 选择项目后获取轮灌组列表
      if (selectedProject) {
        this.fetchGroups(selectedProject.id);
      }
    });
  },
 
  // 项目选择器取消
  onProjectPickerCancel() {
    this.setData({
      projectPickerVisible: false
    });
  },
 
  /**
   * 计算总灌溉时间
   */
  calculateTotalDuration: function () {
    if (!this.data.selectedProject) return;
 
    const totalDuration = this.data.selectedProject.groups.reduce((sum, group) => {
      return sum + (parseInt(group.duration) || 0);
    }, 0);
 
    this.setData({
      totalDuration
    });
  },
 
  /**
   * 轮灌组列表下拉刷新
   */
  onGroupListRefresh: function () {
    if (!this.data.selectedProject) {
      this.setData({
        isRefreshing: false
      });
      return;
    }
 
    this.setData({
      isRefreshing: true
    });
 
    this.fetchGroups(this.data.selectedProject.id)
      .then(() => {
        this.setData({
          isRefreshing: false
        });
      })
      .catch(() => {
        this.setData({
          isRefreshing: false
        });
      });
  },
 
  /**
   * 显示时间提示弹窗
   */
  showTimeInfo: function () {
    this.setData({
      timeInfoVisible: true
    });
  },
 
  /**
   * 关闭时间提示弹窗
   */
  onTimeInfoConfirm: function () {
    this.setData({
      timeInfoVisible: false
    });
  },
});