import { toRefs, computed, reactive } from 'vue'
import { queryTaAccounts } from '@/services/api/account'
import { useLoginStore } from './login'
import { defineStore } from '../store'
import eventBus from '@/services/bus'

/**
 * 账号存储对象
 * @returns 
 */
export const useAccountStore = defineStore(() => {
    const loginStore = useLoginStore()

    const state = reactive({
        loading: false,
        accountList: <Ermcp.TaAccountsRsp[]>[],
        accountId: 0,
    })

    // 当前资金账户信息
    const accountInfo = computed(() => {
        return state.accountList.find((e) => e.accountid === state.accountId)
    })

    // 冻结资金
    const freezeMargin = computed(() => {
        const { freezecharge = 0, freezemargin = 0, otherfreezemargin = 0, outamountfreeze = 0 } = accountInfo.value ?? {}
        return freezecharge + freezemargin + otherfreezemargin + outamountfreeze
    })

    // 可用资金
    const avaiableMoney = computed(() => {
        const { currentbalance = 0 } = accountInfo.value ?? {}
        return currentbalance - freezeMargin.value
    })

    // 获取资金账户列表
    const getAccountList = async () => {
        try {
            state.loading = true
            const res = await queryTaAccounts({
                loginID: loginStore.loginId
            })
            const dataList = res.data
            if (dataList.length) {
                state.accountList = dataList
                // 查找当前选中的资金账户
                const account = dataList.find((e) => e.accountid === state.accountId)
                if (account) {
                    state.loading = false
                } else {
                    // 如果不存在，默认选中第一个账户
                    state.accountId = dataList[0].accountid
                }
            } else {
                state.loading = false
                state.accountList = []
                state.accountId = 0
            }
        } catch {
            state.loading = false
        }
    }

    // 接收资金变动通知
    const moneyChangedNotify = eventBus.$on('MoneyChangedNotify', () => getAccountList())

    return {
        ...toRefs(state),
        accountInfo,
        freezeMargin,
        avaiableMoney,
        moneyChangedNotify,
        getAccountList,
    }
})