<template>
    <div class="page page-shadow">
        <StepList :current-step="currentStep" :options="stepOptions" />
        <van-form ref="formRef" :model="paymentForm" class="payment-form" v-if="targetBankOptions.length > 0 && countryOptions.length > 0">
            <!-- 第一步：基本信息 -->
            <div v-show="currentStep === 3" class="form-section">
                <h3 class="section-title">{{ t('eur-remit.item6') }}</h3>
                <div class="amount-fee">
                    <remit-input
                        v-model:value="paymentForm.amount"
                        type="number"
                        fkey="amount"
                        :label="t('eur-remit.item9', { feeRate1 })"
                        @change="handleBankChange"
                        :required="true"
                        :rules="rules['amount']"
                    />
                    <div class="balance-info">
                        <span class="balance-key">{{ t('card-recharge.walletBalance') }}：</span>
                        <span class="balance-value">{{ balance }} USD</span>
                        <span class="all-btn" @click="useAll">{{ t('card-recharge.all') }}</span>
                    </div>
                    <div class="fee">{{ t('eur-remit.item9_1', { allFee, feeRate2, feeAmount1 }) }}</div>
                </div>
                <remit-input
                    v-model:value="paymentForm.postscript"
                    type="text"
                    fkey="postscript"
                    :label="t('eur-remit.item10')"
                    :required="true"
                    :rules="rules['postscript']"
                    @change="handleBankChange"
                />
                <remit-input
                    v-model:value="paymentForm.relationship"
                    type="select"
                    fkey="relationship"
                    :label="t('eur-remit.item11')"
                    :columns="relationshipOptions"
                    :loading="loadingStates.validateStep1"
                    @change="handleBankChange"
                />
                <remit-input
                    v-model:value="paymentForm.sourceFunds"
                    type="select"
                    fkey="sourceFunds"
                    :label="t('eur-remit.item33')"
                    :columns="sourceFundsOptions"
                    :loading="loadingStates.validateStep1"
                    @change="handleBankChange"
                />
                <remit-input
                    v-model:value="paymentForm.payPurpose"
                    type="select"
                    fkey="payPurpose"
                    :label="t('eur-remit.item41')"
                    :columns="payPurposeOptions"
                    :loading="loadingStates.validateStep1"
                    @change="handleBankChange"
                />
            </div>
            <!-- 第二步：付款人信息 -->
            <div v-show="currentStep === 2" class="form-section">
                <h3 class="section-title">{{ t('eur-remit.item50') }}</h3>
                <remit-input
                    v-model:value="paymentForm.payerType"
                    type="select"
                    fkey="payerType"
                    :label="t('eur-remit.item51')"
                    :columns="payerTypeOptions"
                    :loading="loadingStates.validateStep2"
                    @change="handleBankChange"
                />
                <remit-input
                    v-model:value="paymentForm.payerLastName"
                    type="text"
                    fkey="payerLastName"
                    :label="t('eur-remit.item53')"
                    :required="true"
                    :rules="rules['payerLastName']"
                    @change="handleBankChange"
                />
                <remit-input
                    v-model:value="paymentForm.payerFirstName"
                    type="text"
                    fkey="payerFirstName"
                    :label="t('eur-remit.item54')"
                    :required="true"
                    :rules="rules['payerFirstName']"
                    @change="handleBankChange"
                />
                <remit-input
                    v-model:value="paymentForm.payerIdNo"
                    type="text"
                    fkey="payerIdNo"
                    :label="t('eur-remit.item55')"
                    :required="true"
                    :rules="rules['payerIdNo']"
                    @change="handleBankChange"
                />
                <remit-input
                    v-model:value="paymentForm.payerIdNoType"
                    type="select"
                    fkey="payerIdNoType"
                    :label="t('eur-remit.item56')"
                    :columns="idNoTypeOptions"
                    :required="true"
                    :rules="rules['payerIdNoType']"
                    :loading="loadingStates.validateStep2"
                    @change="handleBankChange"
                />
                <remit-input
                    v-model:value="paymentForm.payerIdCountry"
                    type="select"
                    fkey="payerIdCountry"
                    :label="t('eur-remit.item59')"
                    :show-search="true"
                    :columns="countryOptions"
                    :required="true"
                    :rules="rules['payerIdCountry']"
                    :loading="loadingStates.validateStep2"
                    @change="handleBankChange"
                />
                <remit-input
                    v-model:value="paymentForm.payerBirthday"
                    type="date"
                    fkey="payerBirthday"
                    :label="t('eur-remit.item61')"
                    :required="true"
                    :rules="rules['payerBirthday']"
                    @change="handleBankChange"
                />
                <remit-input
                    v-model:value="paymentForm.payerNationalityCountry"
                    type="select"
                    fkey="payerNationalityCountry"
                    :show-search="true"
                    :label="t('eur-remit.item62')"
                    :columns="countryOptions"
                    :required="true"
                    :rules="rules['payerNationalityCountry']"
                    :loading="loadingStates.validateStep2"
                    @change="handleBankChange"
                />
                <remit-input
                    v-model:value="paymentForm.payerMobile"
                    type="text"
                    fkey="payerMobile"
                    :label="t('eur-remit.item64')"
                    :required="true"
                    :rules="rules['payerMobile']"
                    @change="handleBankChange"
                />
                <remit-input
                    v-model:value="paymentForm.payerCountryCode"
                    type="select"
                    fkey="payerCountryCode"
                    :label="t('eur-remit.item65')"
                    :show-search="true"
                    :columns="countryOptions"
                    :required="true"
                    :rules="rules['payerCountryCode']"
                    :loading="loadingStates.validateStep2"
                    @change="handleBankChange"
                />
                <remit-input
                    v-model:value="paymentForm.payerCityCode"
                    type="select"
                    fkey="payerCityCode"
                    :label="t('eur-remit.item67')"
                    :show-search="true"
                    :columns="payerCityList"
                    :required="true"
                    :rules="rules['payerCityCode']"
                    :loading="loadingStates.validateStep2"
                    :disabled="!paymentForm.payerCountryCode"
                    @change="handleBankChange"
                />
                <remit-input
                    v-model:value="paymentForm.payerAddress"
                    type="text"
                    fkey="payerAddress"
                    :label="t('eur-remit.item69')"
                    :required="true"
                    :rules="rules['payerAddress']"
                    @change="handleBankChange"
                />
                <remit-input
                    v-model:value="paymentForm.payerPostCode"
                    type="text"
                    fkey="payerPostCode"
                    :label="t('eur-remit.item70')"
                    :required="true"
                    :rules="rules['payerPostCode']"
                    @change="handleBankChange"
                />
                <remit-input
                    v-model:value="paymentForm.payerOccupation"
                    type="text"
                    fkey="payerOccupation"
                    :label="t('eur-remit.item71')"
                    :required="true"
                    :rules="rules['payerOccupation']"
                    @change="handleBankChange"
                />
            </div>
            <!-- 第三步：收款人信息 -->
            <div v-show="currentStep === 1" class="form-section">
                <h3 class="section-title">{{ t('eur-remit.item73') }}</h3>
                <div class="bank-summary">
                    <icon name="icon_bank" :size="48" color="#1a1a1a" />
                    <div class="bank-r">
                        <div class="bank-title">{{ t('eur.p5') }} {{ bankSummary?.number }}{{ t('eur.p6') }}</div>
                        <div class="bank-value">{{ bankSummary?.value }}{{ bankSummary?.number > 5 ? t('eur.p7') : '' }}{{ t('eur.p8') }}</div>
                    </div>
                </div>
                <remit-input
                    v-model:value="paymentForm.bankId"
                    type="select"
                    fkey="bankId"
                    :label="t('eur-remit.item7')"
                    :required="true"
                    :rules="rules['bankId']"
                    :columns="targetBankOptions"
                    :show-search="true"
                    @change="handleBankChange"
                    :loading="loadingStates.validateStep1"
                />
                <remit-input
                    v-if="showField('benBankAccountType').value"
                    v-model:value="paymentForm.benBankAccountType"
                    type="select"
                    :required="true"
                    :rules="rules['bankId']"
                    fkey="benBankAccountType"
                    :label="t('eur-remit.item97')"
                    :columns="bankAccountTypeOptions"
                    :loading="loadingStates.validateStep3"
                    @change="handleBankChange"
                />
                <remit-input
                    v-model:value="paymentForm.benAccountNum"
                    type="text"
                    fkey="benAccountNum"
                    :label="t('eur-remit.item75')"
                    :required="true"
                    :rules="rules['benAccountNum']"
                    @change="handleBankChange"
                />
                <remit-input
                    v-if="showField('benCountryCode').value"
                    v-model:value="paymentForm.benCountryCode"
                    type="select"
                    fkey="benCountryCode"
                    :label="t('eur-remit.item77')"
                    :show-search="true"
                    :required="true"
                    :rules="rules['benCountryCode']"
                    :columns="countryOptions"
                    :loading="loadingStates.validateStep3"
                    @change="handleBankChange"
                />
                <remit-input
                    v-model:value="paymentForm.benAccountName"
                    type="text"
                    fkey="benAccountName"
                    :label="t('eur-remit.item76')"
                    :required="true"
                    :rules="rules['benAccountName']"
                    @change="handleBankChange"
                />
                <remit-input
                    v-if="showField('benBankCode').value"
                    v-model:value="paymentForm.benBankCode"
                    type="text"
                    :required="true"
                    :rules="rules['benBankCode']"
                    fkey="benBankCode"
                    :label="t('eur-remit.item85')"
                    @change="handleBankChange"
                />

                <remit-input
                    v-if="showField('benCityCode').value"
                    v-model:value="paymentForm.benCityCode"
                    type="select"
                    fkey="benCityCode"
                    :label="t('eur-remit.item79')"
                    :show-search="true"
                    :required="true"
                    :rules="rules['benCityCode']"
                    :columns="payeeCityList"
                    :loading="loadingStates.validateStep3"
                    :disabled="!paymentForm.benCountryCode"
                    @change="handleBankChange"
                />
                <remit-input
                    v-if="showField('benAddress').value"
                    v-model:value="paymentForm.benAddress"
                    type="text"
                    :required="true"
                    :rules="rules['benAddress']"
                    fkey="benAddress"
                    :label="t('eur-remit.item81')"
                    @change="handleBankChange"
                />
                <remit-input
                    v-if="showField('benPostCode').value"
                    v-model:value="paymentForm.benPostCode"
                    type="text"
                    fkey="benPostCode"
                    :required="true"
                    :rules="rules['benPostCode']"
                    :label="t('eur-remit.item82')"
                    @change="handleBankChange"
                />
                <remit-input
                    v-if="showField('benLastName').value"
                    v-model:value="paymentForm.benLastName"
                    type="text"
                    :required="true"
                    :rules="rules['benLastName']"
                    fkey="benLastName"
                    :label="t('eur-remit.item83')"
                    @change="handleBankChange"
                />
                <remit-input
                    v-if="showField('benFirstName').value"
                    v-model:value="paymentForm.benFirstName"
                    type="text"
                    fkey="benFirstName"
                    :required="true"
                    :rules="rules['benFirstName']"
                    :label="t('eur-remit.item84')"
                    @change="handleBankChange"
                />
                <remit-input
                    v-if="showField('benNationalityCountry').value"
                    v-model:value="paymentForm.benNationalityCountry"
                    type="select"
                    :required="true"
                    :rules="rules['benNationalityCountry']"
                    fkey="benNationalityCountry"
                    :label="t('eur-remit.item86')"
                    :show-search="true"
                    :columns="countryOptions"
                    :loading="loadingStates.validateStep3"
                    @change="handleBankChange"
                />
                <remit-input
                    v-if="showField('benIdNoType').value"
                    v-model:value="paymentForm.benIdNoType"
                    type="select"
                    :required="true"
                    :rules="rules['benIdNoType']"
                    fkey="benIdNoType"
                    :label="t('eur-remit.item88')"
                    :columns="idNoTypeOptions"
                    :loading="loadingStates.validateStep3"
                    @change="handleBankChange"
                />
                <remit-input
                    v-if="showField('benIdNo').value"
                    v-model:value="paymentForm.benIdNo"
                    type="text"
                    :required="true"
                    :rules="rules['benIdNo']"
                    fkey="benIdNo"
                    :label="t('eur-remit.item91')"
                    @change="handleBankChange"
                />
                <remit-input
                    v-if="showField('benIdExpirationDate').value"
                    v-model:value="paymentForm.benIdExpirationDate"
                    type="date"
                    :required="true"
                    :rules="rules['benIdExpirationDate']"
                    fkey="benIdExpirationDate"
                    :label="t('eur-remit.item92')"
                    @change="handleBankChange"
                />
                <remit-input
                    v-if="showField('benBirthday').value"
                    v-model:value="paymentForm.benBirthday"
                    type="date"
                    :required="true"
                    :rules="rules['benBirthday']"
                    fkey="benBirthday"
                    :label="t('eur-remit.item93')"
                    @change="handleBankChange"
                />
                <remit-input
                    v-if="showField('benMobileCode').value"
                    v-model:value="paymentForm.benMobileCode"
                    type="select"
                    :required="true"
                    :rules="rules['benMobileCode']"
                    fkey="benMobileCode"
                    :label="t('eur-remit.item94')"
                    :show-search="true"
                    :columns="mobileCodeOptions"
                    :loading="loadingStates.validateStep3"
                    @change="handleBankChange"
                />
                <remit-input
                    v-if="showField('benMobile').value"
                    v-model:value="paymentForm.benMobile"
                    type="text"
                    :required="true"
                    :rules="rules['benMobile']"
                    fkey="benMobile"
                    :label="t('eur-remit.item96')"
                    @change="handleBankChange"
                />
            </div>
            <!-- 第四步：确认信息 -->
            <div v-if="currentStep === 4" class="form-section">
                <h3 class="section-title">{{ t('eur-remit.item104') }}</h3>
                <h3 class="section-title1">{{ t('eur-remit.item100_1') }}</h3>
                <div class="confirm-info">
                    <div class="info-group">
                        <h4>{{ t('eur-remit.item6') }}</h4>
                        <div class="info-item">
                            <span class="label">{{ t('eur-remit.item9_10') }}</span>
                            <p class="value">{{ formData.amount }}</p>
                        </div>
                        <div class="info-item">
                            <span class="label">{{ t('eur-remit.item9_11') }}</span>
                            <p class="value">{{ feeRate1 }}%</p>
                        </div>
                        <div class="info-item">
                            <span class="label">{{ t('eur-remit.item9_12') }}</span>
                            <p class="value">{{ t('eur-remit.item9_13', { allFee, feeRate2, feeAmount1 }) }}</p>
                        </div>
                        <div class="info-item">
                            <span class="label">{{ t('eur-remit.item10') }}</span>
                            <p class="value">{{ formData.postscript }}</p>
                        </div>
                    </div>
                    <div class="info-group">
                        <h4>{{ t('eur-remit.item50') }}</h4>
                        <div class="info-item">
                            <span class="label">{{ t('eur-remit.item53') }}</span>
                            <p class="value">{{ formData.payer.payerLastName }} {{ formData.payer.payerFirstName }}</p>
                        </div>
                        <div class="info-item">
                            <span class="label">{{ t('eur-remit.item55') }}</span>
                            <p class="value">{{ formData.payer.payerIdNo }}</p>
                        </div>
                    </div>
                    <div class="info-group">
                        <h4>{{ t('eur-remit.item73') }}</h4>
                        <div class="info-item">
                            <span class="label">{{ t('eur-remit.item7') }}</span>
                            <p class="value">{{ getBankName(formData.bankId) }}</p>
                        </div>
                        <div class="info-item">
                            <span class="label">{{ t('eur-remit.item75') }}</span>
                            <p class="value">{{ formData.payee.benAccountNum }}</p>
                        </div>
                        <div class="info-item">
                            <span class="label">{{ t('eur-remit.item76') }}</span>
                            <p class="value">{{ formData.payee.benAccountName }}</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 步骤控制按钮 -->
            <div class="form-actions">
                <template v-if="currentStep === 3">
                    <div class="fixed-btn">
                        <div class="cwg-button two-btn">
                            <van-button plain block @click="goStep(2)" class="prev-btn">
                                {{ t('eur-remit.prev') }}
                            </van-button>
                            <van-button type="primary" block @click="validateStep1" :loading="loadingStates.validateStep1">
                                {{ t('eur-remit.next') }}</van-button
                            >
                        </div>
                    </div>
                </template>
                <template v-else-if="currentStep === 2">
                    <div class="fixed-btn">
                        <div class="cwg-button two-btn">
                            <van-button plain block @click="goStep(1)" class="prev-btn">
                                {{ t('eur-remit.prev') }}
                            </van-button>
                            <van-button type="warning" block @click="validateStep2" :loading="loadingStates.validateStep2">
                                {{ t('eur-remit.next') }}
                            </van-button>
                        </div>
                    </div>
                </template>
                <template v-else-if="currentStep === 1">
                    <div class="fixed-btn">
                        <div class="cwg-button two-btn">
                            <van-button type="warning" block @click="validateStep3" :loading="loadingStates.validateStep3">
                                {{ t('eur-remit.next') }}
                            </van-button>
                        </div>
                    </div>
                </template>
                <template v-else-if="currentStep === 4">
                    <div class="fixed-btn">
                        <div class="cwg-button two-btn">
                            <van-button plain block @click="goStep(3)" class="prev-btn">
                                {{ t('eur-remit.prev') }}
                            </van-button>
                            <van-button type="warning" block @click="validateStep4" :loading="loadingStates.validateStep4">
                                {{ t('eur-remit.item105') }}
                            </van-button>
                        </div>
                    </div>
                </template>
            </div>
        </van-form>
    </div>
</template>

<script setup lang="ts">
import crypt from '@/composables/crypt'
import { useI18n } from 'vue-i18n'
import { showToast } from 'vant'
import { useRouter, useRoute, onBeforeRouteLeave } from 'vue-router'
import { ucardApi } from '@/api/ucard'
import RemitInput from '@/components/RemitInput.vue'
import { lang } from '@/composables/config'
const route = useRoute()
const { currency, allAmount } = route.query as { currency: string; allAmount: string }
const { t } = useI18n()
import useUserStore from '@/stores/use-user-store'
import { ucardValidateParams } from '@/api/ucard'
const userStore = useUserStore()
const userInfo = userStore.userInfo?.customInfo
const router = useRouter()
const stepOptions = ref([t('eur.p1'), t('eur.p2'), t('eur.p3'), t('eur.p4')])
const formRef = ref()
// 当前步骤
const currentStep = ref(Number(route.query.currentStep) || 1)

watch(
    () => route.query.currentStep,
    (val) => {
        currentStep.value = Number(val) || 1
    },
)

function goStep(step: number) {
    router.replace({
        query: {
            ...route.query,
            currentStep: step,
        },
    })
}

// 加载状态
const loadingStates = ref({
    validateStep1: false,
    validateStep2: false,
    validateStep3: false,
    validateStep4: false,
})
const isAllValidated = ref(false)

const formData = ref<ucardValidateParams>({ uniqueId: userInfo?.uniqueId } as ucardValidateParams)
// 表单数据
const paymentForm = ref({
    bankId: 10000,
    uniqueId: userInfo?.uniqueId,
    originOrderNo: '',
    amount: 200,
    postscript: 'testorder',
    relationship: 'OTHER',
    sourceFunds: 'SAVINGS',
    payPurpose: 'INTERNATIONAL_TRADE',
    payerType: 'INDIVIDUAL',
    payerLastName: 'zhang',
    payerFirstName: 'tom',
    payerIdNo: 'ES125664',
    payerIdNoType: 'PASSPORT',
    payerIdCountry: 'SG',
    payerBirthday: '1990-10-10',
    payerNationalityCountry: 'SG',
    payerMobile: '+65012345678',
    payerCountryCode: 'SG',
    payerCityCode: 'SG_1',
    payerAddress: '21 Tampines Ave 1, Singapore 529757',
    payerPostCode: '999002',
    payerOccupation: 'worker',
    benAccountNum: '235486845630',
    benAccountName: 'wangfei',
    benCountryCode: 'SG',
    benCityCode: 'SG_1',
    benAddress: '21 Tampines Ave 1, Singapore 529757',
    benPostCode: '999002',
    benTransBankSwift: '',
    benLastName: 'zhang',
    benFirstName: 'alex',
    benNationalityCountry: 'SG',
    benIdNoType: 'PASSPORT',
    benIdNo: '1334924322424',
    benIdExpirationDate: '2030-01-01',
    benBirthday: '2001-01-01',
    benMobileCode: '+67',
    benMobile: '18326559132',
    benBankAccountType: 'SAVINGS',
    benBankCode: '',
})

// 表单验证规则
const rules = {
    bankId: [{ required: true, message: t('eur-remit.ms3') }],
    amount: [
        { required: true, message: t('eur-remit.ms6') },
        {
            validator: (val: string) => {
                const num = Number(val)
                if (isNaN(num)) return t('eur-remit.ms')
                if (!/^\d+(\.\d{1,2})?$/.test(val)) return t('eur-remit.ms')
                if (num < 100) return t('eur-remit.ms', { min: 100 })
                if (maxAmount.value > limitAmount.value) {
                    if (num > limitAmount.value) return t('eur-remit.maxAmountTip', { max: limitAmount.value })
                } else {
                    if (num > maxAmount.value) return t('eur-remit.maxAmountTip', { max: maxAmount.value })
                }
                return true
            },
            trigger: 'blur',
        },
    ],
    postscript: [
        { required: true, message: t('eur-remit.ms7') },
        { pattern: /^[A-Za-z]{5,64}$/, message: t('eur-remit.ms8') },
    ],
    uniqueId: [{ required: true, message: t('eur-remit.ms4') }],
    // 付款人信息验证规则
    payerLastName: [
        { required: true, message: t('eur-remit.ms9') },
        {
            validator: (val: string) => {
                const trimmed = val.trim()
                const lengthValid = trimmed.length >= 2 && trimmed.length <= 50
                const noChinese = !/[\u4e00-\u9fa5]/.test(trimmed)
                return lengthValid && noChinese
            },
            message: t('eur-remit.ms10'),
        },
    ],
    payerFirstName: [
        { required: true, message: t('eur-remit.ms10_1') },
        {
            validator: (val: string) => {
                const trimmed = val.trim()
                const lengthValid = trimmed.length >= 2 && trimmed.length <= 50
                const noChinese = !/[\u4e00-\u9fa5]/.test(trimmed)
                return lengthValid && noChinese
            },
            message: t('eur-remit.ms10'),
        },
    ],
    payerIdNo: [
        { required: true, message: t('eur-remit.ms11') },
        {
            validator: (val: string) => {
                const trimmed = val.trim()
                const lengthValid = trimmed.length >= 6 && trimmed.length <= 18
                const noChinese = !/[\u4e00-\u9fa5]/.test(trimmed)
                return lengthValid && noChinese
            },
            message: t('eur-remit.ms12'),
        },
    ],
    payerIdNoType: [{ required: true, message: t('eur-remit.ms13') }],
    payerIdCountry: [{ required: true, message: t('eur-remit.ms14') }],
    payerBirthday: [{ required: true, message: t('eur-remit.ms16') }],
    payerNationalityCountry: [{ required: true, message: t('eur-remit.ms17') }],
    payerMobile: [
        { required: true, message: t('eur-remit.ms18') },
        { pattern: /^\+?\d{8,15}$/, message: t('eur-remit.ms19') },
    ],
    payerCountryCode: [{ required: true, message: t('eur-remit.ms20') }],
    payerCityCode: [{ required: true, message: t('eur-remit.ms22') }],
    payerAddress: [
        { required: true, message: t('eur-remit.ms23') },
        {
            validator: (val: string) => {
                const trimmed = val.trim()
                const lengthValid = trimmed.length >= 10 && trimmed.length <= 100
                const noChinese = !/[\u4e00-\u9fa5]/.test(trimmed)
                return lengthValid && noChinese
            },
            message: t('eur-remit.ms24'),
        },
    ],
    payerPostCode: [
        { required: true, message: t('eur-remit.ms25') },
        { pattern: /^.{3,9}$/, message: t('eur-remit.ms26') },
    ],
    payerOccupation: [
        { required: true, message: t('eur-remit.ms27') },
        { pattern: /^[A-Za-z]{3,10}$/, message: t('eur-remit.ms28') },
    ],

    // 收款人信息验证规则
    benAccountNum: [
        { required: true, message: t('eur-remit.ms29') },
        {
            validator: (val: string) => {
                const trimmed = val.trim()
                const lengthValid = trimmed.length >= 2 && trimmed.length <= 48
                const noChinese = !/[\u4e00-\u9fa5]/.test(trimmed)
                return lengthValid && noChinese
            },
            message: t('eur-remit.ms30'),
        },
    ],
    benAccountName: [
        { required: true, message: t('eur-remit.ms31') },
        { pattern: /^.{1,100}$/, message: t('eur-remit.ms32') },
    ],

    benCountryCode: [{ required: true, message: t('eur-remit.ms20') }],
    benCityCode: [{ required: true, message: t('eur-remit.ms22') }],
    benAddress: [
        { required: true, message: t('eur-remit.ms23') },
        {
            validator: (val: string) => {
                const trimmed = val.trim()
                const lengthValid = trimmed.length >= 10 && trimmed.length <= 100
                const noChinese = !/[\u4e00-\u9fa5]/.test(trimmed)
                return lengthValid && noChinese
            },
            message: t('eur-remit.ms24'),
        },
    ],
    benPostCode: [
        { required: true, message: t('eur-remit.ms33') },
        { pattern: /^.{3,9}$/, message: t('eur-remit.ms34') },
    ],
    benLastName: [
        { required: true, message: t('eur-remit.ms35') },
        {
            validator: (val: string) => {
                const trimmed = val.trim()
                const lengthValid = trimmed.length >= 2 && trimmed.length <= 50
                const noChinese = !/[\u4e00-\u9fa5]/.test(trimmed)
                return lengthValid && noChinese
            },
            message: t('eur-remit.ms10'),
        },
    ],
    benFirstName: [
        { required: true, message: t('eur-remit.ms36') },
        {
            validator: (val: string) => {
                const trimmed = val.trim()
                const lengthValid = trimmed.length >= 2 && trimmed.length <= 50
                const noChinese = !/[\u4e00-\u9fa5]/.test(trimmed)
                return lengthValid && noChinese
            },
            message: t('eur-remit.ms10'),
        },
    ],
    benNationalityCountry: [{ required: true, message: t('eur-remit.ms17') }],
    benIdNoType: [{ required: true, message: t('eur-remit.ms39') }],
    benIdNo: [
        { required: true, message: t('eur-remit.ms40') },
        { pattern: /^.{6,18}$/, message: t('eur-remit.ms32') },
    ],
    benIdExpirationDate: [{ required: true, message: t('eur-remit.ms42') }],
    benBirthday: [{ required: true, message: t('eur-remit.ms43') }],
    benMobileCode: [{ required: true, message: t('eur-remit.ms44') }],
    benMobile: [
        { required: true, message: t('eur-remit.ms45') },
        { pattern: /^.{5,15}$/, message: t('eur-remit.ms46') },
    ],
    benBankAccountType: [{ required: true, message: t('eur-remit.ms47') }],
    benBankCode: [
        { required: true, message: t('eur-remit.ms48') },
        { pattern: /^.{6,12}$/, message: t('eur-remit.ms49') },
    ],
}
// 关系
const relationshipOptions = ref([
    { text: t('eur-remit.item26'), value: 'SELF' },
    { text: t('eur-remit.item21'), value: 'HUSBAND' },
    { text: t('eur-remit.item31'), value: 'WIFE' },
    { text: t('eur-remit.item16'), value: 'FATHER' },
    { text: t('eur-remit.item22'), value: 'MOTHER' },
    { text: t('eur-remit.item29'), value: 'SON' },
    { text: t('eur-remit.item15'), value: 'DAUGHTER' },
    { text: t('eur-remit.item27'), value: 'SISTER' },
    { text: t('eur-remit.item12'), value: 'BROTHER' },
    { text: t('eur-remit.item17'), value: 'FATHER_IN_LAW' },
    { text: t('eur-remit.item23'), value: 'MOTHER_IN_LAW' },
    { text: t('eur-remit.item28'), value: 'SISTER_IN_LAW' },
    { text: t('eur-remit.item13'), value: 'BROTHER_IN_LAW' },
    { text: t('eur-remit.item19'), value: 'GRAND_FATHER' },
    { text: t('eur-remit.item20'), value: 'GRAND_MOTHER' },
    { text: t('eur-remit.item24'), value: 'NEPHEW' },
    { text: t('eur-remit.item25'), value: 'NIECE' },
    { text: t('eur-remit.item30'), value: 'UNCLE' },
    { text: t('eur-remit.item14'), value: 'COUSIN' },
    { text: t('eur-remit.item18'), value: 'FRIEND' },
    { text: t('eur-remit.item32'), value: 'OTHER' },
])

// 资金来源
const sourceFundsOptions = ref([
    { text: t('eur-remit.item34'), value: 'SAVINGS' },
    { text: t('eur-remit.item35'), value: 'SALARY' },
    { text: t('eur-remit.item36'), value: 'INVESTMENT' },
    { text: t('eur-remit.item37'), value: 'OTHER' },
])
// 付款目的
const payPurposeOptions = ref([
    { text: t('eur-remit.item42'), value: 'PURCHASE_OF_GOODS_OR_SERVICES' },
    { text: t('eur-remit.item43'), value: 'FREIGHT_AND_TRANSPORTATION_COSTS' },
    { text: t('eur-remit.item44'), value: 'EDUCATION_EXPENSES' },
    { text: t('eur-remit.item45'), value: 'IMMIGRATION_INVESTMENT' },
    { text: t('eur-remit.item46'), value: 'CHARITABLE_DONATIONS' },
    { text: t('eur-remit.item47'), value: 'FAMILY_SUPPORT' },
    { text: t('eur-remit.item48'), value: 'DIVIDEND_OR_INTEREST_PAYMENTS' },
    { text: t('eur-remit.item49'), value: 'INTERNATIONAL_TRADE' },
])

// 付款人类型
const payerTypeOptions = ref([{ text: t('eur-remit.item52'), value: 'INDIVIDUAL' }])

// 证件类型
const idNoTypeOptions = ref([
    { text: t('eur-remit.item57'), value: 'PASSPORT' },
    { text: t('eur-remit.item58'), value: 'EUROPEAN_ID' },
])

// 手机区号
const mobileCodeOptions = ref([])

const getMobileCode = async () => {
    try {
        const res = await ucardApi.countryGet()
        mobileCodeOptions.value = res.data.map((item: { callingCode: string; name: string; enName: string }) => ({
            text: '+' + item.callingCode + ' ' + (lang.value === 'cn' ? item.name : item.enName),
            value: item.callingCode,
        }))
    } catch (error) {
        showToast(t('common.error'))
    }
}
// 银行账户类型
const bankAccountTypeOptions = ref([
    { text: t('eur-remit.item98'), value: 'SAVINGS' },
    { text: t('eur-remit.item99'), value: 'CHECKING' },
])

const bankConfigList = ref<any[]>([])
const payeeParams1 = ref<string[]>([])
const feeAmount1 = ref<number>(0)
const feeRate1 = ref<number>(0)
const maxAmount = computed(() => {
    const rate = Number(feeRate1.value) / 100
    return Number((balance.value / (1 + rate) - feeAmount1.value).toFixed(2))
})
const limitAmount = computed(() => {
    return currency == 'CNY' ? 29999 : 1000000
})

function useAll() {
    const rate = Number(feeRate1.value) / 100
    paymentForm.value.amount = (balance.value / (1 + rate) - feeAmount1.value).toFixed(2)
}
// 手续费
const feeRate2 = computed(() => {
    const amount = formData.value.amount
    return Number(amount) === 0 ? 0 : ((Number(amount) * feeRate1.value) / 100).toFixed(2)
})
const allFee = computed(() => {
    return Number(feeRate2.value) + feeAmount1.value
})
const balance = computed(() => {
    return Number(allAmount)
})
const paymentType1 = ref(15)
const showField = (key: string) =>
    computed(() => {
        return payeeParams1.value.includes(key)
    })

const targetBankOptions = ref<Array<{ text: string; value: number }>>([])
const bankSummary = ref({ value: '', number: 0 })
const loadBankConfigList = async () => {
    try {
        const res = await ucardApi.ucardBanks({})
        if (res && (res.code === 0 || res.code === 200) && Array.isArray(res.data)) {
            let allBanks = []
            // 根据 currency 字段过滤
            if (currency) {
                const a = res.data.filter((bank: any) => bank.currency === currency)
                if (a.length === 1) {
                    allBanks = a[0].bankList
                } else if (a.length > 1) {
                    allBanks = a.reduce((arr: any[], item: any) => arr.concat(item.bankList || []), [])
                }
            }
            bankConfigList.value = allBanks
            const options = allBanks.map((bank) => ({
                text: bank.bankName + '(' + bank.bankId + ')',
                value: bank.bankId,
            }))
            targetBankOptions.value = options
            const names = allBanks.map((b) => String(b.bankName || '')).filter(Boolean)
            bankSummary.value = { value: names.slice(0, 5).join('、'), number: names.length }
        }
    } catch (error) {
        bankConfigList.value = []
        targetBankOptions.value = []
        bankSummary.value = {}
    }
}

// 国家选项
const countryOptions = ref<Array<{ text: string; value: string }>>([])
const payerCityList = ref<Array<{ text: string; value: string }>>([])
const payeeCityList = ref<Array<{ text: string; value: string }>>([])
// 获取国家列表
const getCountryListForSelect = async () => {
    try {
        const res = await ucardApi.ucardCountryCity({})
        if (res.code === 200 || res.code === 0) {
            countryOptions.value = res.data.map((item: any) => ({
                text: lang.value === 'cn' ? item.cnName : item.enName,
                value: item.code,
            }))
        }
    } catch (error) {
        countryOptions.value = []
    }
}
// 获取城市列表
const getCityListForSelect = async (countryCode: string, type: 'payer' | 'payee' = 'payer') => {
    try {
        const res = await ucardApi.ucardCountryCity({ code: countryCode })
        if (res.code === 200 || res.code === 0) {
            const cityList = res.data.map((item: any) => ({
                text: lang.value === 'cn' ? item.cnName : item.enName,
                value: item.code,
            }))

            if (type === 'payer') {
                payerCityList.value = cityList
            } else {
                payeeCityList.value = cityList
            }
        }
    } catch (error) {
        if (type === 'payer') {
            payerCityList.value = []
        } else {
            payeeCityList.value = []
        }
    }
}
// 汇率
const getUcardRate = async () => {
    try {
        const res = await ucardApi.ucardRate({
            currency: 'USD',
            targetCurrency: 'CNY',
            targetCountry: 'CN',
        })
        if (res.code === 200 || res.code === 0) {
            console.log(1122,res);
            
        }
    } catch (error) {
       
    }
}

// API 调用函数
interface ApiResponse {
    success: boolean
    message?: string
    data?: any
}
const validateBasicInfo = async (data: ucardValidateParams): Promise<ApiResponse> => {
    try {
        const res = await ucardApi.ucardValidate({ ...data })
        if (res.code === 200 || res.code === 0) {
            return {
                ...res.data,
                success: true,
            }
        }
        return {
            success: false,
            message: res.msg || t('eur-remit.validateError'),
        }
    } catch (error: any) {
        return {
            success: false,
            message: error.response?.data?.message || t('eur-remit.validateError'),
        }
    }
}
const validatePayerInfo = async (data: ucardValidateParams): Promise<ApiResponse> => {
    try {
        const res = await ucardApi.ucardValidatePayer({ ...data })
        if (res.code === 200 || res.code === 0) {
            return {
                ...res.data,
                success: true,
            }
        }
        return {
            success: false,
            message: res.msg || t('eur-remit.validateError'),
        }
    } catch (error: any) {
        return {
            success: false,
            message: error.response?.data?.message || t('eur-remit.validateError'),
        }
    }
}
const validatePayeeInfo = async (data: ucardValidateParams): Promise<ApiResponse> => {
    try {
        const res = await ucardApi.ucardValidatePayee({ ...data })
        if (res.code === 200 || res.code === 0) {
            return {
                ...res.data,
                success: true,
            }
        }
        return {
            success: false,
            message: res.msg || t('eur-remit.validateError'),
        }
    } catch (error: any) {
        return {
            success: false,
            message: error.response?.data?.message || t('eur-remit.validateError'),
        }
    }
}
const executePayment = async (data: ucardValidateParams): Promise<ApiResponse> => {
    try {
        const res = await ucardApi.ucardTransfer({ ...data })
        if (res.code === 200 || res.code === 0) {
            return {
                ...res,
                success: true,
            }
        }
        return {
            success: false,
            message: res.msg || t('eur-remit.paymentError'),
        }
    } catch (error: any) {
        return {
            success: false,
            message: error.response?.data?.message || t('eur-remit.paymentError'),
        }
    }
}

// 获取银行名称
const getBankName = (bankId: number) => {
    const bank = bankConfigList.value.find((b) => b.bankId === bankId)
    return bank ? bank.bankName : ''
}

// 第一步校验 - 基本信息完整性
const validateStep1 = async () => {
    loadingStates.value.validateStep1 = true
    try {
        await formRef.value?.validate(['amount', 'postscript'])
        goStep(4)
    } catch (error) {
        if (Array.isArray(error) && error.length > 0) {
            showToast(error[0].message)
        } else {
            showToast(t('eur-remit.validateError'))
        }
        return
    } finally {
        loadingStates.value.validateStep1 = false
    }
}

// 第二步校验 - 付款人信息
const validateStep2 = async () => {
    loadingStates.value.validateStep2 = true
    try {
        const requiredFields = [
            'payerLastName',
            'payerFirstName',
            'payerIdNo',
            'payerIdNoType',
            'payerIdCountry',
            'payerBirthday',
            'payerNationalityCountry',
            'payerMobile',
            'payerCountryCode',
            'payerCityCode',
            'payerAddress',
            'payerPostCode',
            'payerOccupation',
        ] as const
        await formRef.value?.validate(requiredFields)
        const response = await validatePayerInfo(formData.value.payer)
        if (response.success) {
            goStep(3)
        } else {
            showToast(response.message || t('eur-remit.validateFailed'))
            return
        }
    } catch (error) {
        if (Array.isArray(error) && error.length > 0) {
            showToast(error[0].message)
        } else {
            showToast(t('eur-remit.validateError'))
        }
        return
    } finally {
        loadingStates.value.validateStep2 = false
    }
}

// 第三步校验 - 收款人信息
const validateStep3 = async () => {
    loadingStates.value.validateStep3 = true
    try {
        const requiredFields = ['benAccountNum', 'benAccountName', 'bankId'] as const

        await formRef.value?.validate([...requiredFields, ...payeeParams1.value])
        const response = await validatePayeeInfo(formData.value.payee)
        if (response.success) {
            goStep(2)
            isAllValidated.value = false
        } else {
            showToast(response.message || t('eur-remit.validateFailed'))
            return
        }
    } catch (error) {
        if (Array.isArray(error) && error.length > 0) {
            showToast(error[0].message)
        } else {
            showToast(t('eur-remit.validateError'))
        }
        return
    } finally {
        loadingStates.value.validateStep3 = false
    }
}

// 第四步校验 校验所有信息
const validateStep4 = async () => {
    loadingStates.value.validateStep4 = true
    try {
        // 最终校验所有信息
        const finalValidation = await validateBasicInfo(formData.value)
        if (!finalValidation.success) {
            showToast(finalValidation.message || t('eur-remit.validateFailed'))
            return
        }
        validateStep5()
    } catch (error) {
        showToast(t('eur-remit.validateError'))
        return
    } finally {
        loadingStates.value.validateStep4 = false
    }
}

// 第五步校验 - 最终确认并提交
const validateStep5 = async () => {
    try {
        const payResponse = await executePayment(formData.value)
        if (payResponse.success) {
            showToast(t('eur-remit.paymentSuccess'))
            clearCache()
            // 跳转到成功页面
            router.push({
                path: '/remit/success',
                query: {
                    orderNo: payResponse.data?.orderNo,
                },
            })
        } else {
            showToast(payResponse.message || t('eur-remit.paymentFailed'))
        }
    } catch (error) {
        showToast(t('eur-remit.validateError'))
    }
}

const handleBankChange = (value: any) => {
    const payerKeys = [
        'payerType',
        'payerLastName',
        'payerFirstName',
        'payerIdNo',
        'payerIdNoType',
        'payerIdCountry',
        'payerBirthday',
        'payerNationalityCountry',
        'payerMobile',
        'payerCountryCode',
        'payerCityCode',
        'payerAddress',
        'payerPostCode',
        'payerOccupation',
    ]

    const payeeKeys = [
        'bankId',
        'benAccountNum',
        'benAccountName',
        'benCountryCode',
        'benCityCode',
        'benAddress',
        'benPostCode',
        'benTransBankSwift',
        'benLastName',
        'benFirstName',
        'benNationalityCountry',
        'benIdNoType',
        'benIdNo',
        'benIdExpirationDate',
        'benBirthday',
        'benMobileCode',
        'benMobile',
        'benBankAccountType',
        'benBankCode',
    ]
    if (value.key === 'amount') {
        const num = Number(value.value)
        const max = Number(maxAmount.value)
        if (maxAmount.value > limitAmount.value) {
            if (num > limitAmount.value) return t('eur-remit.maxAmountTip', { max: limitAmount.value })
        } else {
            if (num > max) {
                if (value.value !== maxAmount.value) {
                    showToast(t('eur-remit.maxAmountTip', { max: maxAmount.value }))
                }
            }
        }
    }
    if (value.key === 'bankId') {
        formData.value.bankId = value.value
        const { payeeParams, feeAmount, feeRate, paymentType } = bankConfigList.value.find((b) => b.bankId === value.value)

        console.log(paymentType, feeAmount, feeRate, 1999)
        payeeParams1.value = payeeParams
        feeAmount1.value = feeAmount
        feeRate1.value = feeRate
        paymentType1.value = paymentType
        // payeeParams1.value = [
        //     'benLastName',
        //     'benFirstName',
        //     'benAccountNum',
        //     'benAccountName',
        //     'benBankCode',
        //     'benNationalityCountry',
        //     'benMobile',
        //     'benMobileCode',
        //     'benIdNo',
        //     'benBankAccountType',
        //     'benCountryCode',
        //     'benIdNoType',
        //     'benBirthday',
        //     'benAddress',
        //     'benCityCode',
        //     'benPostCode',
        // ]
    }
    if (payerKeys.includes(value.key)) {
        formData.value.payer = { ...formData.value.payer, [value.key]: value.value }
    } else if (payeeKeys.includes(value.key)) {
        formData.value.payee = { ...formData.value.payee, [value.key]: value.value }
    } else {
        formData.value = { ...formData.value, [value.key]: value.value }
    }
    if (value.key === 'payerCountryCode') {
        getCityListForSelect(value.value, 'payer')
        formData.value.payer.payerCityCode = ''
    } else if (value.key === 'benCountryCode') {
        formData.value.payee.benCityCode = ''
        getCityListForSelect(value.value, 'payee')
    }
}

const cacheKey = computed(() => `eur-remit-${currency}`)

function saveCache() {
    const encryptedInfo = crypt.encrypt(JSON.stringify(formData.value))
    localStorage.setItem(cacheKey.value, encryptedInfo)
}

function loadCache() {
    const cache = localStorage.getItem(cacheKey.value)
    const info = crypt.decrypt(cache)
    if (cache) {
        try {
            Object.assign(formData.value, JSON.parse(info))
        } catch (e) {}
    }
}

function clearCache() {
    localStorage.removeItem(cacheKey.value)
}

watch(formData, saveCache, { deep: true })

onMounted(() => {
    loadCache()
    getUcardRate()
    loadBankConfigList()
    getCountryListForSelect()
    getMobileCode()
    if (paymentForm.value.payerCountryCode) {
        getCityListForSelect(paymentForm.value.payerCountryCode, 'payer')
    }
    if (paymentForm.value.benCountryCode) {
        getCityListForSelect(paymentForm.value.benCountryCode, 'payee')
    }
    if (currency == 'CNY') {
        rules.benAccountName = [
            { required: true, message: t('eur-remit.ms31') },
            {
                validator: (val: string) => {
                    const trimmed = val.trim()
                    const noChinese = /[\u4e00-\u9fa5]/.test(trimmed)
                    return noChinese
                },
                message: t('eur-remit.ms50'),
            },
        ]
        rules.benLastName = [
            { required: true, message: t('eur-remit.ms35') },
            {
                validator: (val: string) => {
                    const trimmed = val.trim()
                    const noChinese = /[\u4e00-\u9fa5]/.test(trimmed)
                    return noChinese
                },
                message: t('eur-remit.ms50'),
            },
        ]
        rules.benFirstName = [
            { required: true, message: t('eur-remit.ms36') },
            {
                validator: (val: string) => {
                    const trimmed = val.trim()
                    const noChinese = /[\u4e00-\u9fa5]/.test(trimmed)
                    return noChinese
                },
                message: t('eur-remit.ms50'),
            },
        ]
    }
})

onBeforeRouteLeave(() => {
    clearCache()
})
</script>

<style scoped lang="scss">
.bank-summary {
    display: flex;
    padding: 16px;
    margin-bottom: 24px;
    align-items: flex-start;
    gap: 16px;
    border-radius: 12px;
    box-shadow: 0px 5px 30px 0px rgba(5, 0, 1, 0.05);
    .bank-r {
        .bank-title {
            color: #1a1a1a;
            font-family: Roboto;
            font-size: 16px;
            font-style: normal;
            font-weight: 600;
            line-height: 24px;
        }
        .bank-value {
            color: #474747;
            font-family: Roboto;
            font-size: 12px;
            font-style: normal;
            font-weight: 400;
            line-height: 16px;
            letter-spacing: 0.048px;
        }
    }
}

.form-section {
    margin: 8px 0;
    .amount-fee {
        .form-group {
            margin-bottom: 0;
        }
        .fee {
            color: #8e8a8a;
            font-family: Roboto;
            font-size: 14px;
            font-style: normal;
            font-weight: 400;
            line-height: 20px;
            letter-spacing: 0.07px;
            margin: 16px 0;
        }
        .balance-info {
            width: 100%;
            color: #bdbdbd;
            font-size: 14px;
            margin: 16px 0;
            display: flex;
            align-items: center;
        }
        .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;
        }
    }
}

.section-title {
    color: #1a1a1a;
    font-family: Roboto;
    font-size: 22px;
    font-style: normal;
    font-weight: 600;
    line-height: 22px;
    margin-bottom: 16px;
}
.section-title1 {
    color: #474747;
    font-family: Roboto;
    font-size: 15px;
    font-style: normal;
    font-weight: 400;
    line-height: 24px;
}

.confirm-info {
    padding: 16px 0;
    border-radius: 12px;
    margin-bottom: 24px;

    .info-group {
        display: flex;
        padding: 16px;
        flex-direction: column;
        justify-content: center;
        align-items: flex-start;
        gap: 16px;
        border-radius: 12px;
        box-shadow: 0px 5px 30px 0px rgba(5, 0, 1, 0.05);
        margin-bottom: 20px;

        h4 {
            color: #1a1a1a;
            font-family: Roboto;
            font-size: 22px;
            font-style: normal;
            font-weight: 600;
            line-height: 28px;
        }
    }

    .info-item {
        display: flex;
        width: 100%;

        .label {
            width: 120px;
            color: #8e8a8a;
            font-family: Roboto;
            font-size: 14px;
            font-style: normal;
            font-weight: 600;
            line-height: 20px;
            letter-spacing: 0.07px;
        }

        .value {
            display: inline-block;
            flex: 1;
            color: #1a1a1a;
            text-align: right;
            font-family: Roboto;
            font-size: 14px;
            font-style: normal;
            font-weight: 600;
            line-height: 20px;
            letter-spacing: 0.07px;
        }
    }
}

.two-btn {
    display: flex;
    align-items: center;
    .prev-btn {
        border: 1px solid var(--main-yellow) !important;
        color: var(--main-yellow) !important;
        background: transparent;
    }
}
</style>
