// pages/garden/record.js
const {
  api
} = require("../../utils/api")
import {
  getNavLayout
} from '../../utils/util'; // 引入工具函数

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    list: [],
    picList: [],
    current: 0,
    info: null,
    innerAudioContext: null,
    backButtonStyle: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      current: options.current,
      id: options.id
    })
    this.fetchList()
    this.playMusic()
    // 一行代码搞定计算
    const layout = getNavLayout();
    this.setData({
      backButtonStyle: layout.containerStyle
    });

  },

  playMusic() {
    this.data.innerAudioContext = wx.createInnerAudioContext({
      useWebAudioImplement: true,
      loop: true,
      volume: 0.2
    })
    const list = [
      'https://res.catter.cn/pub/2025/12/17/20251217113514284.mp3',
      'https://res.catter.cn/pub/2025/12/17/20251217151719823.mp3',
      'https://res.catter.cn/pub/2025/12/17/20251217151806179.mp3',
      'https://res.catter.cn/pub/2025/12/17/20251217152125210.mp3',
      'https://res.catter.cn/pub/2025/12/17/20251217152206612.mp3'
    ]
    const randomIndex = Math.floor(Math.random() * list.length);

    // 3. 赋值给 src
    this.data.innerAudioContext.src = list[randomIndex];

  },

  fetchList() {
    const params = {
      current: 1,
      pageSize: 999,
      id: this.data.id,
      keyword: ''
    }
    api('/plant/grow/recordList', 'POST', params, 'json').then(res => {
      if (res.code === 200) {
        const tmps = res.data.list.map(e => {
          e.createdAtStr = e.createdAtStr.substring(0, 10)
          e.pic = e.imgList[0].url
          return e
        })
        const picList = tmps.map(e => e.pic)
        this.setData({
          list: tmps,
          picList: picList,
          info: tmps[0]
        })
      }
    })
  },

  goPreview(e) {
    const index = e.detail.index
    const currentUrl = this.data.picList[index]
    const list = this.data.picList
    wx.previewImage({
      current: currentUrl, // 当前显示图片的http链接
      urls: list // 需要预览的图片http链接列表
    })
  },

  goBack() {
    wx.navigateBack()
  },

  change(e) {
    const current = e.detail.current
    const info = this.data.list[current]
    this.setData({
      current: current,
      info: info
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.data.innerAudioContext.play()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.data.innerAudioContext.destroy() // 释放音频资源
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})