const api = require('../../utils/api')

Page({
  data: {
    goal: '',
    exerciseName: '',
    planId: null,
    score: 82,
    status: '准备就绪',
  },
  onShow() {
    this.loadPlan()
  },
  async loadPlan() {
    try {
      const children = await api.listChildren()
      const child = (children.list || [])[0]
      if (!child) return
      const plans = await api.request(`/api/training/plans?childId=${child.id}`)
      const plan = (plans.list || [])[0]
      if (!plan) return
      this.setData({
        planId: plan.id,
        goal: plan.detail.goal,
        exerciseName: (plan.detail.exercises[0] || {}).name || '训练动作',
      })
    } catch (err) {
      this.setData({ status: err.message || '加载失败' })
    }
  },
  async submit() {
    if (!this.data.planId) return
    this.setData({ status: '提交打卡…' })
    try {
      await api.request(`/api/training/plans/${this.data.planId}/records`, {
        method: 'POST',
        data: {
          exerciseId: 1,
          completed: true,
          score: this.data.score,
          durationSeconds: 300,
          note: '小程序跟练打卡',
        },
      })
      this.setData({ status: '打卡成功 ✓' })
    } catch (err) {
      this.setData({ status: err.message || '打卡失败' })
    }
  },
})
