<template>
    <div class="page page-shadow">
        <div class="fixed-right" @click="goRechargeRecord">
            <icon name="icon_history" :size="24" color="#000" />
        </div>
        <div v-if="rechargeCurrencyInfoList.length > 0">
            <div class="g">
                <img src="../assets/images/apply-record-1.png" alt="" />
                <div class="g-l">
                    <div class="g-item">
                        <div class="label">Visa Virtual Card (Precious Card)</div>
                    </div>
                    <div class="g-item">
                        <div class="label">{{ cardNo }}</div>
                    </div>
                </div>
            </div>
            <div class="currency">
                <remit-input
                    v-model:value="amount"
                    fkey="amount"
                    type="number"
                    :label="t('card-recharge.amount')"
                    :required="true"
                    :clearable="false"
                    :max="maxAmount"
                    @change="handleChange"
                    :placeholder="t('card-recharge.amountPlaceholder')"
                >
                </remit-input>
                <div class="currency-r" @click="setModelValue">
                    <img :src="imageSrc(currencyT)" alt="" srcset="" />
                    <div class="r">
                        <p>{{ currencyT }}</p>
                    </div>
                    <icon name="icon_dropdown" :size="24" />
                </div>
            </div>

            <div class="balance-info">
                <span class="balance-key">{{ t('card-recharge.walletBalance') }}：</span>
                <span class="balance-value">{{ balance }} {{ currency }}</span>
                <span class="all-btn" @click="useAll">{{ t('card-recharge.all') }}</span>
            </div>
            <div class="balance-info">
                <span class="balance-key">{{ t('card-recharge.rate') }}：</span>
                <span class="balance-value">{{ exchangeRate }}%</span>
                <span></span>
            </div>
            <div class="balance-info">
                <span class="balance-key">{{ t('card-recharge.fee') }}：</span>
                <span class="balance-value">{{ fee }}</span>
                <span></span>
            </div>

            <div class="fixed-btn">
                <div class="cwg-button">
                    <van-button type="primary" block :disabled="!canRecharge" @click="handleRecharge">{{ t('card-recharge.recharge') }}</van-button>
                </div>
            </div>
        </div>
        <SuccessPrompt
            v-if="isShow"
            :btnClick="btnClick"
            :title="t('card-recharge.tips1')"
            :desc="t('card-recharge.tips2')"
            :btn-title="t('card-recharge.tips3')"
        />
        <CurrencySelect :showSearch="false" :options="rechargeCurrencyInfoList" v-model="modelValue" @select="changeSelect" />
    </div>
</template>

<script setup lang="ts">
import { useI18n } from 'vue-i18n'
import { useRoute } from 'vue-router'
import { ucardApi } from '@/api/ucard'
import { userApi } from '@/api/user'
import { showToast } from 'vant'
import { CardInfo } from '@/api/ucard'
const router = useRouter()
const { t } = useI18n()
const infoForm = ref({
    cardNo: undefined,
    uniqueId: undefined,
    amount: undefined,
    currency: undefined,
    currencyT: undefined,
})
const formData = ref<typeof infoForm.value>({} as any)
const route = useRoute()
const { id } = route.query as { id: string }
const cardInfo = ref<CardInfo | null>(null)
const cardNo = ref('')
const currency = ref('')
const currencyT = ref('USD')
const exchangeRate = ref(1)
const modelValue = ref(false)
const rechargeCurrencyInfoList = ref<{ text: string; value: string }[]>([
    {
        text: '',
        value: 'USD',
    },
])
const isShow = ref(false)
const btnClick = () => {
    isShow.value = false
    router.back()
}
const images = import.meta.glob('@/assets/images/currency/*.png', { eager: true })

const imageSrc = (currency: string) => {
    return images[`/src/assets/images/currency/${currency}.png`]?.default || fallbackImg
}

const changeSelect = (e) => {
    currencyT.value = e.value
}
const setModelValue = () => {
    modelValue.value = true
}
const amount = ref('')
const balance = ref(0)
const maxAmount = computed(() => {
    const rate = Number(exchangeRate.value) / 100
    return Number((balance.value / (1 + rate)).toFixed(2))
})
const getCardInfo = async () => {
    if (!id) return
    try {
        const res = await ucardApi.cardSingle({ id })
        if (res.code === 200 && res.data) {
            cardInfo.value = res.data
            cardNo.value = cardInfo.value?.cardNo || ''
            if (cardInfo.value?.cardNo) {
                getBalance()
            }
        }
    } catch (error) {
        showToast(t('common.error'))
    }
}

const handleChange = (value: any) => {
    formData.value = { ...formData.value, [value.key]: value.value }
}

const goRechargeRecord = () => {
    router.push(`/recharge/record/list?cardNo=${cardInfo.value?.cardNo}`)
}

const canRecharge = computed(() => {
    const amt = Number(amount.value)
    const feeVal = Number(fee.value)
    return amt >= 10 && amt + feeVal <= balance.value
})
function useAll() {
    const rate = Number(exchangeRate.value) / 100
    amount.value = (balance.value / (1 + rate)).toFixed(2)
}

// 手续费
const fee = computed(() => {
    return Number(amount.value) === 0 ? 0 : ((Number(amount.value) * exchangeRate.value) / 100).toFixed(2)
})

// 充值
async function handleRecharge() {
    try {
        const params = {
            cardNo: cardInfo.value?.cardNo,
            uniqueId: cardInfo.value?.uniqueId,
            amount: Number(amount.value),
            currency: currencyT.value + 'T',
        }
        const response = await ucardApi.ucardRecharge(params)
        if (response.code === 200) {
            isShow.value = true
            amount.value = ''
        } else {
            showToast(response.msg)
        }
    } catch (error) {
        showToast(t('common.error'))
    }
}
const getBalance = async () => {
    try {
        const res = await userApi.walletBalance()
        currency.value = 'USD'
        balance.value = res.data || 0
    } catch (error) {}
}
onMounted(() => {
    getCardInfo()
})

watch(amount, (val) => {
    const num = Number(val)
    const max = Number(maxAmount.value)
    if (num > max) {
        if (amount.value !== maxAmount.value) {
            amount.value = maxAmount.value
            showToast(t('card-recharge.maxAmountTip', { max: maxAmount.value }))
        }
    }
})
</script>

<style scoped lang="scss">
.card-recharge-page {
    min-height: 100vh;
    background: linear-gradient(135deg, #232323 0%, #2a2a2a 100%);
    display: flex;
    flex-direction: column;
    align-items: center;
}

.form-group {
    width: 100%;
    margin-bottom: 18px;
}
.form-label {
    color: #fff;
    font-size: 15px;
    margin-bottom: 8px;
    display: block;
}
.form-select,
.form-input {
    width: 100%;
    padding: 10px 12px;
    border-radius: 10px;
    border: 1px solid var(--main-yellow);
    background: #181818;
    color: #fff;
    font-size: 16px;
    margin-top: 4px;
}
.form-input::-webkit-input-placeholder {
    color: #bdbdbd;
}
.balance-info {
    width: 100%;
    color: #bdbdbd;
    font-size: 14px;
    margin-bottom: 24px;
    display: flex;
    align-items: center;
    /* justify-content: space-between; */
}
.balance-value {
    width: 130px;
    color: var(--white);
    font-weight: bold;
    margin: 0 8px;
}
.balance-key {
    color: #8e8a8a;
    width: 130px;
}
.all-btn {
    display: flex;
    padding: 4px 12px;
    justify-content: center;
    align-items: center;
    gap: 10px;
    border-radius: 35px;
    border: 1px solid #ea002a;
    color: var(--Brand-color, #ea002a);
    font-family: Roboto;
    font-size: 14px;
    font-style: normal;
    font-weight: 600;
    line-height: 20px;
    letter-spacing: 0.07px;
}
.confirm-btn {
    width: 100%;
    height: 44px;
    background: linear-gradient(90deg, var(--main-yellow) 0%, var(--main-yellow-dark) 100%);
    color: #232323;
    border: none;
    border-radius: 22px;
    font-size: 18px;
    font-weight: bold;
    margin-top: 18px;
    cursor: pointer;
    box-shadow: 0 2px 12px 0 rgba(73, 247, 166, 0.1);
    letter-spacing: 2px;
    transition: background 0.2s, box-shadow 0.2s;
}
.confirm-btn:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}
.fee-info {
    color: #bdbdbd;
    font-size: 13px;
    margin-top: 10px;
    text-align: center;
}
.transactions {
    background: var(--action-bg, #181818);
    border-radius: 16px;
    margin-bottom: 16px;
    padding: 16px 12px;
    width: 100%;
    max-width: 340px;
}
.trans-title {
    font-size: 16px;
    margin-bottom: 10px;
    color: var(--main-yellow);
}
.transaction {
    display: flex;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid var(--border, #333);
    font-size: 16px;
}
.transaction:last-child {
    border-bottom: none;
}
.trans-icon {
    width: 40px;
    height: 40px;
    border-radius: 6px;
    background-color: var(--border);
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 12px;
}
.trans-icon-inner {
    width: 24px;
    height: 24px;
    background-color: #232323;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
}
.trans-icon-inner i {
    color: var(--main-yellow);
    font-size: 16px;
}
.trans-left {
    flex: 1;
    min-width: 0;
}
.trans-right {
    text-align: right;
    margin-left: 12px;
}
.trans-type {
    color: #fff;
    font-size: 15px;
    margin-bottom: 4px;
}
.trans-desc {
    color: #bdbdbd;
    font-size: 13px;
}
.trans-amount {
    font-size: 16px;
    color: var(--white);
    margin-bottom: 4px;
}
.trans-date {
    color: #bdbdbd;
    font-size: 13px;
}
.currency {
    position: relative;
}
.currency-r {
    position: absolute;
    bottom: 2px;
    right: 0;
    display: flex;
    /* width: 164px; */
    padding: 16px 16px 16px 10px;
    height: 46px;
    align-items: center;
    gap: 12px;
    border-radius: 12px;
    color: var(--white);
    p {
        color: #000;
        font-family: Roboto;
        font-size: 16px;
        font-style: normal;
        font-weight: 600;
        line-height: 24px;
    }
    img {
        width: 32px;
        height: 32px;
        border: 1px solid #f4f4f4;
        border-radius: 50%;
    }
}
</style>
