管灌系统农户端微信小程序(嘉峪关应用)
pages/createIrrigation/createIrrigation.js
@@ -1,4 +1,6 @@
const app = getApp();
const { get, post } = require('../../api/request');
const dayjs = require('dayjs');
Page({
  /**
@@ -10,119 +12,145 @@
    startTime: '', // 灌溉开始时间
    pickerValue: '', // 时间选择器的值
    timePickerVisible: false, // 时间选择器是否可见
        timeInfoVisible: false, // 时间提示弹窗是否可见
    // 项目选择器相关
    projectPickerVisible: false,
    projectPickerValue: [],
    selectedProject: null,
    projectOptions: [],
    totalDuration: 0, // 添加总灌溉时间
    // 测试数据
    projectList: [
      {
        id: 1,
        name: '测试项目一',
        groups: [
          {
            id: 101,
            name: '轮灌组A',
            duration: 30,
            selected: false
          },
          {
            id: 102,
            name: '轮灌组B',
            duration: 45,
            selected: false
          },
          {
            id: 103,
            name: '轮灌组C',
            duration: 60,
            selected: false
          }
        ]
      },
      {
        id: 2,
        name: '测试项目二',
        groups: [
          {
            id: 201,
            name: '轮灌组1',
            duration: 40,
            selected: false
          },
          {
            id: 202,
            name: '轮灌组2',
            duration: 50,
            selected: false
          }
        ]
      },
      {
        id: 3,
        name: '测试项目三',
        groups: [
          {
            id: 301,
            name: '东区轮灌组',
            duration: 35,
            selected: false
          },
          {
            id: 302,
            name: '西区轮灌组',
            duration: 55,
            selected: false
          },
          {
            id: 303,
            name: '南区轮灌组',
            duration: 25,
            selected: false
          }
        ]
      }
    ]
        // 项目列表
        projectList: [],
        // 时间选择器选项
        timeOptions: [],
        // 轮灌组列表刷新状态
        isRefreshing: false
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 初始化项目选择器选项
    const projectOptions = this.data.projectList.map(project => ({
        // 生成计划编号
        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('YYYYMMDD');
        const randomNum = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
        const planCode = `${dateStr}${randomNum}`;
        this.setData({ planCode });
    },
    /**
     * 获取项目列表
     */
    fetchProjects: function () {
        return get({
            url: '/wx/irrigation/getSimpleProjects',
            isShowLoding: true
        }).then(res => {
            if (res.success) {
                const projectList = res.content.obj.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({
      projectOptions: projectOptions // 直接使用一维数组,不需要包装成二维数组
                    projectList,
                    projectOptions
                });
            } 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);
    });
  },
  /**
   * 获取项目和轮灌组数据
     * 获取轮灌组列表
   */
  fetchProjectsAndGroups: function () {
    // 这里可以添加API请求逻辑,获取真实数据
    // wx.request({
    //   url: 'your-api-url',
    //   success: (res) => {
    //     this.setData({
    //       projectList: res.data
    //     });
    //   }
    // });
    fetchGroups: function (projectId) {
        return get({
            url: '/wx/irrigation/getSimpleGroups',
            data: {
                projectId: projectId,
  },
            isShowLoding: true
        }).then(res => {
            if (res.success) {
                console.log('轮灌组数据:', res.content.obj);
  /**
   * 处理计划编号输入
   */
  onPlanCodeInput: function (e) {
                // 更新选中项目的轮灌组信息
                const projectList = this.data.projectList.map(project => {
                    if (project.id === projectId) {
                        return {
                            ...project,
                            groups: res.content.obj.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({
      planCode: e.detail.value
                    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);
    });
  },
@@ -130,6 +158,14 @@
   * 显示时间选择器
   */
  showTimePicker: function () {
        // 如果没有选择时间,使用当前时间
        if (!this.data.pickerValue) {
            const now = dayjs();
            this.setData({
                pickerValue: now.format('YYYY-MM-DD HH:mm')
            });
        }
    this.setData({
      timePickerVisible: true
    });
@@ -240,8 +276,11 @@
  /**
   * 阻止事件冒泡
   */
  stopPropagation: function () {
    // 阻止事件冒泡,防止点击输入框时触发父元素的点击事件
    stopPropagation: function (e) {
        if (e && e.stopPropagation) {
            e.stopPropagation();
        }
        return false;
  },
  /**
@@ -266,14 +305,6 @@
      return;
    }
    
    if (!startTime) {
      wx.showToast({
        title: '请选择灌溉开始时间',
        icon: 'none'
      });
      return;
    }
    if (!selectedProject) {
      wx.showToast({
        title: '请选择项目',
@@ -282,11 +313,52 @@
      return;
    }
    // TODO: 实现确认逻辑
    console.log('提交数据:', {
      planCode,
      startTime,
      project: selectedProject
        // 构建上报数据
        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(() => {
                    wx.navigateBack();
                }, 1500);
            } else {
                wx.showToast({
                    title: res.msg || '创建失败',
                    icon: 'none'
                });
            }
        }).catch(err => {
            console.error('创建计划失败:', err);
            wx.showToast({
                title: '创建失败',
                icon: 'none'
            });
    });
  },
@@ -300,15 +372,19 @@
  // 项目选择器确认
  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
    }, () => {
      // 选择项目后计算总时间
      this.calculateTotalDuration();
            // 选择项目后获取轮灌组列表
            if (selectedProject) {
                this.fetchGroups(selectedProject.id);
            }
    });
  },
@@ -319,8 +395,10 @@
    });
  },
  // 计算总灌溉时间
  calculateTotalDuration() {
    /**
     * 计算总灌溉时间
     */
    calculateTotalDuration: function () {
    if (!this.data.selectedProject) return;
    
    const totalDuration = this.data.selectedProject.groups.reduce((sum, group) => {
@@ -331,4 +409,42 @@
      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
        });
    },
});