const { request } = require('../../utils/request')

Page({
  data: {
    form: {
      weight: '',
      body_fat: '',
      exercise_kcal: '',
      intake_kcal: '',
      sleep_hours: '7',
      note: ''
    },
    latestId: null,
    loading: false
  },

  onShow() {
    this.loadLatest()
  },

  async loadLatest() {
    try {
      const latest = await request({ url: '/diet/status/latest' })
      if (latest && latest.id) {
        this.setData({
          latestId: latest.id,
          form: {
            weight: String(latest.weight),
            body_fat: String(latest.body_fat),
            exercise_kcal: String(latest.exercise_kcal),
            intake_kcal: String(latest.intake_kcal),
            sleep_hours: String(latest.sleep_hours || 7),
            note: latest.note || ''
          }
        })
      }
    } catch (err) {
      // ignore
    }
  },

  onInput(e) {
    const field = e.currentTarget.dataset.field
    this.setData({ [`form.${field}`]: e.detail.value })
  },

  buildPayload() {
    const f = this.data.form
    return {
      weight: Number(f.weight),
      body_fat: Number(f.body_fat),
      exercise_kcal: Number(f.exercise_kcal),
      intake_kcal: Number(f.intake_kcal),
      sleep_hours: Number(f.sleep_hours),
      note: f.note
    }
  },

  async saveNew() {
    if (this.data.loading) return
    this.setData({ loading: true })
    try {
      await request({ url: '/diet/status', method: 'POST', data: this.buildPayload() })
      wx.showToast({ title: '已新增状态', icon: 'success' })
      this.loadLatest()
    } catch (err) {
      // handled
    } finally {
      this.setData({ loading: false })
    }
  },

  async updateLatest() {
    if (this.data.loading) return
    this.setData({ loading: true })
    try {
      await request({ url: '/diet/status/latest', method: 'PUT', data: this.buildPayload() })
      wx.showToast({ title: '已更新最新状态', icon: 'success' })
      this.loadLatest()
    } catch (err) {
      // handled
    } finally {
      this.setData({ loading: false })
    }
  }
})
