import { defineStore } from 'pinia'
import type { MemberShip, UserMember, UserMemberState } from './helper'
import { defaultSetting, getLocalState, setLocalState } from './helper'
import { fetchMyMember, fetchGetMemberships, fetchMembershipRenew } from '@/api'
import { isAfter, isEqual, format } from 'date-fns'

export const useUserMemberStore = defineStore('userMember-store', {
    state: (): UserMemberState => getLocalState(),
    actions: {
        setUserMember(userInfo: Partial<UserMember>) {
            this.userMember = { ...this.userMember, ...userInfo }
            this.recordState()
        },

        resetUserMembe() {
            this.userMember = { ...defaultSetting().userMember }
            this.recordState()
        },

        recordState() {
            setLocalState(this.$state)
        },

        async fetchMember() {
            const data = await fetchMyMember<UserMember>()
            this.setUserMember(data)
        },

        fetchMembers() {
            return fetchGetMemberships<MemberShip>()
        },

        getExpireAt() {
            if (this.isVip()) {
                return format(new Date(this.userMember.expireAt), 'yyyy年MM月dd日')
            } else if (this.userMember.expireAt) {
                return '会员已过期'
            } else {
                return ''
            }
        },

        isVip() {
            if (this.userMember.memberType!=='TRIAL') {
                return isAfter(new Date(this.userMember.expireAt), new Date())
            }
            return false
        },

        renew(planId: string | number) {
            return fetchMembershipRenew<UserMember>(planId)
        }
    }
})
