import { toRefs, shallowReadonly } from 'vue'
import { queryMyFavorite } from '@/services/api/favorite'
import { useLoginStore } from './login'
import { VueStore } from '../base'

interface StoreState {
    loading: boolean;
    favoriteList: Ermcp.MyFavoriteRsp[]; // 收藏列表
}

/**
 * 商品收藏存储类
 */
const store = new (class extends VueStore<StoreState>{
    constructor() {
        const state: StoreState = {
            loading: false,
            favoriteList: [],
        }
        super(state)
    }

    actions = {
        /** 获取收藏列表 */
        getFavoriteList: () => {
            const { getUserId } = useLoginStore()
            this.state.loading = true
            return queryMyFavorite({
                data: {
                    userid: getUserId(),
                },
                success: (res) => {
                    this.state.favoriteList = res.data
                },
                complete: () => {
                    this.state.loading = false
                }
            })
        },
        /** 是否已收藏 */
        hasFavorite: (goodsno: string) => {
            return this.state.favoriteList.some((e) => e.goodsno === goodsno)
        }
    }
})

export function useFavoriteStore() {
    return shallowReadonly({
        ...toRefs(store.state),
        ...store.actions,
        ...store.methods,
    })
}