import { reactive, toRefs } from 'vue'
import { queryMyFavorite } from '@/services/api/favorite'
import { useLoginStore } from './login'
import { defineStore } from '../store'

/**
 * 商品收藏存储对象
 */
export const useFavoriteStore = defineStore(() => {
    const state = reactive({
        loading: false,
        favoriteList: <Ermcp.MyFavoriteRsp[]>[], // 收藏列表
    })

    // 获取收藏列表
    const getFavoriteList = async () => {
        try {
            const loginStore = useLoginStore()
            state.loading = true
            const res = await queryMyFavorite({
                userid: loginStore.userId,
            })
            state.favoriteList = res.data
        } finally {
            state.loading = false
        }
    }

    // 是否已收藏
    const hasFavorite = (goodsno: string) => {
        return state.favoriteList.some((e) => e.goodsno === goodsno)
    }

    return {
        ...toRefs(state),
        getFavoriteList,
        hasFavorite,
    }
})