// pages/threshold/threshold.js
Page({
  data: {
    refluxThreshold: null,  // 反酸阈值
    reduceAcidThreshold: null, // 降酸阈值
    newReflux: null,        // 新反酸阈值输入
    newReduce: null,       // 新降酸阈值输入
    loading: true
  },

  onLoad() {
    this.getThresholds();
  },

  // 获取双阈值
  getThresholds() {
    this.setData({ loading: true });
    wx.request({
      url: 'https://soilgd.com:5000/get-threshold',
      method: 'GET',
      success: (res) => {
        if (res.statusCode === 200 && res.data) {
          this.setData({
            reduceThreshold: res.data.reduce.current_threshold || null,
            refluxThreshold: res.data.reflux.current_threshold || null
          });
        }
      },
      fail: (err) => {
        wx.showToast({ title: '获取失败', icon: 'error' });
      },
      complete: () => {
        this.setData({ loading: false });
      }
    });
  },

  // 统一输入处理
  onInput(e) {
    const type = e.currentTarget.dataset.type;
    const value = Number(e.detail.value);
    const field = `new${type.charAt(0).toUpperCase() + type.slice(1)}`;
    
    if (!isNaN(value)) {
      this.setData({ [field]: value });
    }
  },

  // 统一更新处理
  updateThreshold(e) {
    const type = e.currentTarget.dataset.type;
    const field = `new${type.charAt(0).toUpperCase() + type.slice(1)}`;
    const value = this.data[field];

    if (value === 0) {
      wx.showToast({ title: '阈值不能为0', icon: 'error' });
      this.setData({ [field]: null }); // 清空非法输入
      return;
    }

    if (value === null || isNaN(value)) {
      wx.showToast({ title: '请输入有效数字', icon: 'error' });
      return;
    }

    wx.showLoading({ title: '更新中...' });
    wx.request({
      url: 'https://soilgd.com:5000/update-threshold',
      method: 'POST',
      data: {
        data_type: type === 'reduce' ? 'reduce' : 'reflux',
        threshold: value
      },
      success: (res) => {
        if (res.statusCode === 200) {
          wx.showToast({ title: '更新成功' });
          this.setData({ [`${type}Threshold`]: value });
        }
      },
      complete: () => wx.hideLoading()
    });
  }
});