// pages/tool/tool.js
const app = getApp()

Page({
  data: {
    // 表单数据
    formData: {
      name: '诺言',
      age: '6',
      height: '120',
      boneAge: '6',
      fatherHeight: '32',
      motherHeight: '28',
      igf: '334',
      lh: '0.6',
      thickness: '11'
    },
    // 计算结果
    result: '',
    // 结果弹窗显示状态
    show: false
  },

  // =============== 表单输入处理 ===============
  
  // 统一的输入处理函数
  handleInput(e) {
    const { field } = e.currentTarget.dataset
    this.setData({
      [`formData.${field}`]: e.detail.value
    })
  },

  // =============== 登录检查 ===============
  
  checkLogin() {
    if (!wx.getStorageSync('phone')) {
      wx.setStorageSync('uidFlag', false)
      this.showLoginModal()
      return false
    }
    return true
  },

  showLoginModal() {
    wx.showModal({
      title: '提示',
      content: '请先登录',
      success(res) {
        if (res.confirm) {
          wx.switchTab({
            url: '/pages/my/my'
          })
        }
      }
    })
  },

  // =============== 计算相关 ===============
  
  // 开始计算
  calculate() {
    if (!this.checkLogin()) return
    
    if (!this.validateForm()) return
    
    this.setData({ show: true })
    this.submitCalculation()
  },

  // 表单验证
  validateForm() {
    const { name } = this.data.formData
    if (!name.trim()) {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      })
      return false
    }
    return true
  },

  // 提交计算请求
  submitCalculation() {
    const { formData } = this.data
    
    wx.request({
      url: app.globalData.url + 'app/Ruilaiwechat/calculate',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        uid: wx.getStorageSync('uid'),
        name: formData.name,
        age: formData.age,
        height: formData.height,
        bone_age: formData.boneAge,
        father_height: formData.fatherHeight,
        mother_height: formData.motherHeight,
        IGF: formData.igf,
        LH: formData.lh,
        uterus_thickness: formData.thickness
      },
      success: this.handleCalculationResponse.bind(this)
    })
  },

  // 处理计算响应
  handleCalculationResponse(res) {
    if (res.data.erro === 0) {
      this.setData({
        result: res.data.calculate_resutlt
      })
    } else {
      wx.showToast({
        title: res.data.msg,
        icon: 'error',
        duration: 2000
      })
    }
  },

  // =============== 其他功能 ===============
  
  // 重置表单
  reset() {
    if (!this.checkLogin()) return
    
    this.setData({
      formData: {
        name: '',
        age: '',
        height: '',
        boneAge: '',
        fatherHeight: '',
        motherHeight: '',
        igf: '',
        lh: '',
        thickness: ''
      }
    })
  },

  // 查看历史记录
  go_history() {
    wx.navigateTo({
      url: '/pages/order/order'
    })
  },

  // 弹窗控制
  pintuan() {
    this.setData({ show: true })
  },

  tiaoguo() {
    this.setData({ show: false })
  }
})