import { defineStore } from "pinia";
import { fetchBabyInfo } from "../api/user.js";

export const useFeedStore = defineStore("feed", {
  state: () => {
    return {
      // 宝宝列表和当前选中宝宝的管理
      babyList: [],
      currentBabyIndex: 0,
    };
  },
  actions: {
    /**
     * 获取宝宝信息
     */
    async loadBabyInfo() {
      const { data } = await fetchBabyInfo();
      console.log("babyInfo", data);
      if (data?.memberId !== "not_login") {
        // 处理宝宝列表数据
        this.processBabyList(data);
      }
    },

    /**
     * 处理宝宝列表数据
     */
    processBabyList(data) {

      if (data.allBabyBaseInfo && Array.isArray(data.allBabyBaseInfo)) {
        // 转换接口数据格式为组件需要的格式
        this.babyList = data.allBabyBaseInfo.map(baby => ({
          id: baby.id,
          name: baby.babyName || baby.content?.babyName || '未命名',
          avatar: baby.content?.babyAvatar ,
          gender: baby.content?.babyGender,
          birthday: baby.content?.babyBirthday,
          babyStage: baby.babyStage,
          babyType: baby.babyType,
          typeName: baby.typeName,
          selected: baby.selected
        }))
        
        // 找到选中的宝宝，如果没有选中的则选择第一个
        const selectedIndex = this.babyList.findIndex(baby => baby.selected)
        this.currentBabyIndex = selectedIndex >= 0 ? selectedIndex : 0
        
        console.log('处理后的宝宝列表:', this.babyList)
        console.log('当前选中的宝宝索引:', this.currentBabyIndex)
      } else {
        // 如果没有宝宝数据，使用默认数据
        this.babyList = [{
          id: 1,
          name: '默认宝宝',
          avatar: '/static/feedingIndex/v1/avatar.png',
          gender: null,
          birthday: null,
          babyStage: 1,
          babyType: null,
          typeName: '默认',
          selected: true
        }]
        this.currentBabyIndex = 0
      }
    },

    /**
     * 切换宝宝
     */
    switchBaby(index) {
      if (index >= 0 && index < this.babyList.length) {
        this.currentBabyIndex = index
        console.log('切换到宝宝:', this.babyList[index].name, '索引:', index)
      }
    },

    /**
     * 获取当前选中的宝宝
     */
    getCurrentBaby() {
      return this.babyList[this.currentBabyIndex] || null
    },

    /**
     * 获取当前选中的宝宝ID
     */
    getCurrentBabyId() {
      const currentBaby = this.getCurrentBaby()
      return currentBaby ? currentBaby.id : 1
    },
  },
}); 