import { reactive, toRefs } from 'vue'
import { getCurrencyTypeInfo, CurrencyType } from '@/constants/diamond'
import { queryRates } from '@/services/api/common'
import { defineStore } from '../store'

/**
 * 汇率存储对象
 */
export const useExrateStore = defineStore(() => {
    const state = reactive({
        loading: false,
        exrateList: <Ermcp.RatesRsp[]>[], // 汇率列表
    })

    // 获取汇率列表
    const getExrateList = async () => {
        try {
            state.loading = true
            const res = await queryRates()
            state.exrateList = res.data
        } finally {
            state.loading = false
        }
    }

    // 获取币种汇率
    const getExrate = (currencyId: number) => {
        const exrate = state.exrateList.find((e) => e.oricurrencyid === currencyId)
        return exrate?.exchangerate ?? 0
    }

    // 汇率转换
    const exchangeRate = (currencyId: number, currencyValue: number, prefix = true) => {
        if (currencyValue) {
            const exrate = 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)
        }
        return '0.00'
    }

    return {
        ...toRefs(state),
        getExrateList,
        getExrate,
        exchangeRate,
    }
})