import { shallowRef, computed } from 'vue'
import { homeData, queryNotice } from '@/services/api/common'
import { queryMyDeListing } from '@/services/api/trade'
import { BuyOrSell } from '@/constants/order'
import { useLoginStore, useFavoriteStore } from '@/stores'

export function useHomeData() {
    const { getUserId, getLoginId } = useLoginStore()
    const favoriteStore = useFavoriteStore()
    const deListingList = shallowRef<Ermcp.MyDeListingRsp[]>([])
    const noticeList = shallowRef<Ermcp.NoticeRsp[]>([])

    const favoriteList = computed(() => {
        return favoriteStore.favoriteList.value.slice(0, 5)
    })

    const countData = shallowRef<Ermcp.HomeDataRsp>({
        purchasedtransactions: 0, // 已购买的交易
        transactioninpurchase: 0, // 求购中的交易
        transactionsonsale: 0, // 出售中的交易
        transactionssold: 0, // 已卖出的交易
        unhandledmessage: 0, // 未处理消息
    })

    const getCountData = () => {
        return homeData({
            data: {
                userid: getUserId()
            },
            success: (res) => {
                countData.value = res.data
            }
        })
    }

    const getDeListingList = (buyorsell: BuyOrSell) => {
        deListingList.value = []
        return queryMyDeListing({
            data: {
                page: 1,
                pagesize: 5,
                buyorsell,
                userid: getUserId(),
            },
            success: (res) => {
                deListingList.value = res.data
            }
        })
    }

    const getNoticeList = () => {
        return queryNotice({
            data: {
                loginID: getLoginId()
            },
            success: (res) => {
                noticeList.value = res.data.splice(0, 5)
            },
        })
    }

    return {
        countData,
        deListingList,
        favoriteList,
        noticeList,
        getCountData,
        getDeListingList,
        getNoticeList,
    }
}