import { toRefs, shallowReadonly } from 'vue'
import { getCurrencyTypeInfo, CurrencyType } from '@/constants/diamond'
import { queryRates } from '@/services/api/common'
import { VueStore } from '../base'

interface StoreState {
    loading: boolean;
    exrateList: Ermcp.RatesRsp[]; // 汇率列表
}

/**
 * 汇率存储类
 */
const store = new (class extends VueStore<StoreState>{
    constructor() {
        const state: StoreState = {
            loading: false,
            exrateList: [],
        }
        super(state)
    }

    actions = {
        /** 获取汇率列表 */
        getExrateList: () => {
            this.state.loading = true
            return queryRates({
                success: (res) => {
                    this.state.exrateList = res.data
                },
                complete: () => {
                    this.state.loading = false
                }
            })
        },
        /** 获取币种汇率 */
        getExrate: (currencyId: number) => {
            const exrate = this.state.exrateList.find((e) => e.oricurrencyid === currencyId)
            return exrate?.exchangerate ?? 0
        },
        /** 汇率转换 */
        exchangeRate: (currencyId: number, currencyValue: number, prefix = true) => {
            const exrate = this.actions.getExrate(currencyId)
            const currency = getCurrencyTypeInfo(currencyId)
            const cny = getCurrencyTypeInfo(CurrencyType.CNY) // 人民币
            const unit = prefix && exrate ? cny?.param2 : currency?.param2 // 币种单位符号

            return unit + (exrate ? currencyValue * exrate : currencyValue).toFixed(2)
        }
    }
})

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