import { shallowRef } from 'vue'
import { v4 } from 'uuid'
import { ClientType } from '@/constants/client'
import { ScoreConfigType } from '@/constants/credit'
import { loginStore } from '@/stores'
import { queryUserAccount } from '@/services/api/account'
import { queryUserScoreLog, queryTHJScoreConfig, thjRedPacketLottery } from '@/services/api/credit'

const { userId } = loginStore.$mapGetters()

// 积分抽奖
export function useCreditLottery() {
    const loading = shallowRef(false)
    const creditList = shallowRef<Model.UserScoreLogRsp[]>([])
    const creditConfig = shallowRef<Partial<Model.THJScoreConfigRsp>>({})
    const userAccount = shallowRef<Partial<Model.UserAccount>>({})

    const redEnvelope = shallowRef<Partial<Proto.THJRedPacketLotteryRsp>>({
        GearLevel: 0,
        RedPacketAmount: 0,
    })

    const formRefresh = () => {
        queryUserAccount({
            userID: userId.value
        }).then((res) => {
            userAccount.value = res.data
        })
        queryUserScoreLog({
            stype: ScoreConfigType.Lottery,
            userid: userId.value,
            page: 1,
            pagesize: 10,
        }).then((res) => {
            creditList.value = res.data
        })
    }

    const formSubmit = () => {
        loading.value = true
        return thjRedPacketLottery({
            data: {
                UserID: userId.value,
                ClientType: ClientType.Web, // 终端类型
                ClientSerialNo: v4() // 客户端流水号
            },
            success: (res) => {
                redEnvelope.value = res
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    queryTHJScoreConfig({
        stype: ScoreConfigType.Lottery
    }).then((res) => {
        if (res.data.length) {
            creditConfig.value = res.data[0]
        }
    })

    return {
        loading,
        creditConfig,
        userAccount,
        creditList,
        redEnvelope,
        formSubmit,
        formRefresh,
    }
}