import { defineStore } from 'pinia'
import { listPerson } from '@/api/health/person'

/**
 * 健康模块公共 Store
 * 缓存频繁使用的数据（如成员列表），避免每个页面重复请求
 */
const useHealthStore = defineStore('health', {
  state: () => ({
    personList: [] as any[],
    personListLoaded: false,
    personListLoading: false
  }),
  actions: {
    /**
     * 获取成员列表（带缓存）
     * @param {boolean} forceRefresh - 是否强制刷新
     * @returns {Promise<Array>}
     */
    async fetchPersonList(forceRefresh = false) {
      // 已加载且不强制刷新，直接返回缓存
      if (this.personListLoaded && !forceRefresh) {
        return this.personList
      }

      // 正在加载中，等待完成
      if (this.personListLoading) {
        return new Promise((resolve) => {
          const timer = setInterval(() => {
            if (!this.personListLoading) {
              clearInterval(timer)
              resolve(this.personList)
            }
          }, 100)
        })
      }

      this.personListLoading = true
      try {
        const res = await listPerson({ pageNum: 1, pageSize: 100 })
        this.personList = res.rows || []
        this.personListLoaded = true
        return this.personList
      } catch (error) {
        console.error('获取成员列表失败:', error)
        return []
      } finally {
        this.personListLoading = false
      }
    },

    /**
     * 清除成员缓存（如新增/删除成员后调用）
     */
    clearPersonCache() {
      this.personList = []
      this.personListLoaded = false
    }
  },
  persist: {
    key: 'health-store',
    paths: ['personList', 'personListLoaded'],
    storage: {
      getItem(key) {
        return uni.getStorageSync(key)
      },
      setItem(key, value) {
        uni.setStorageSync(key, value)
      }
    }
  }
})

export default useHealthStore
