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

Page({
  data: {
    status: '准备就绪',
    reportSummary: '',
  },
  async run() {
    this.setData({ status: '读取档案…' })
    try {
      const children = await api.listChildren()
      const child = (children.list || [])[0]
      if (!child) throw new Error('暂无儿童档案')

      this.setData({ status: '获取上传凭证…' })
      const tokenData = await api.request('/api/videos/upload-token', {
        method: 'POST',
        data: {
          childId: child.id,
          fileName: 'mini.mp4',
          contentType: 'video/mp4',
          size: 1024,
        },
      })

      if (tokenData.storage === 'local') {
        this.setData({ status: '直传本地存储…' })
        await new Promise((resolve, reject) => {
          wx.request({
            url: tokenData.uploadUrl,
            method: 'PUT',
            header: {
              'Content-Type': 'video/mp4',
              'X-Upload-Token': tokenData.uploadToken,
              'X-Object-Key': tokenData.objectKey,
            },
            data: new Uint8Array([0, 0, 0, 24, 102, 116, 121, 112, 105, 115, 111, 109]).buffer,
            success(res) {
              if (res.statusCode === 204) resolve()
              else reject(new Error('直传失败'))
            },
            fail: reject,
          })
        })
      }

      this.setData({ status: '提交分析…' })
      const video = await api.request('/api/videos', {
        method: 'POST',
        data: {
          childId: child.id,
          objectKey: tokenData.objectKey,
          scene: 'front_posture',
        },
      })

      const task = await api.request('/api/analysis/tasks', {
        method: 'POST',
        header: { 'Idempotency-Key': `mini-${Date.now()}` },
        data: {
          childId: child.id,
          videoId: video.id,
          taskType: 'posture_screening',
        },
      })

      const report = await api.request(`/api/reports/${task.reportId}`)
      this.setData({
        status: '完成',
        reportSummary: report.summary,
      })
    } catch (err) {
      this.setData({ status: err.message || '失败' })
    }
  },
})
