import { computed, toRefs, shallowReadonly } from 'vue'
import { queryTaAccounts } from '@/services/api/account'
import { useLoginStore } from './login'
import { VueStore } from '../base'
import eventBus from '@/services/bus'

interface StoreState {
    loading: boolean;
    accountList: Model.TaAccountsRsp[]; // 资金账户列表
    accountId: number; // 当前资金账户ID
}

/**
 * 账号存储类
 */
const store = new (class extends VueStore<StoreState> {
    constructor() {
        const state: StoreState = {
            loading: false,
            accountList: [],
            accountId: 0,
        }
        super(state)

        // 接收资金变动通知
        eventBus.$on('MoneyChangedNotify', () => {
            this.actions.getAccountList()
        })
    }

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

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

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

    getters = {
        accountInfo: this.accountInfo,
        freezeMargin: this.freezeMargin,
        avaiableMoney: this.avaiableMoney
    }

    actions = {
        /** 获取资金账户列表 */
        getAccountList: () => {
            const { getLoginId } = useLoginStore()
            this.state.loading = true

            return queryTaAccounts({
                data: {
                    loginID: getLoginId()
                },
                success: (res) => {
                    const dataList = res.data
                    if (dataList.length) {
                        this.state.accountList = dataList
                        // 查找当前选中的资金账户
                        const account = dataList.find((e) => e.accountid === this.state.accountId)
                        if (account) {
                            this.state.loading = false
                        } else {
                            // 如果不存在，默认选中第一个账户
                            this.state.accountId = dataList[0].accountid
                        }
                    } else {
                        this.state.loading = false
                        this.actions.reset()
                    }
                },
                fail: () => {
                    this.state.loading = false
                }
            })
        },
        /** 重置数据 */
        reset: () => {
            this.state.accountList = []
            this.state.accountId = 0
        }
    }
})

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