<template>
    <div class="default-main finance-cashier-page">
        <el-alert type="info" :closable="false" show-icon class="mb-3">
            {{ t('config.financeCashierConfig.desc') }}
        </el-alert>

        <div class="toolbar">
            <el-button v-if="canSave" type="primary" :loading="saving" :disabled="loading" @click="onSave">
                {{ t('config.financeCashierConfig.btn_save') }}
            </el-button>
        </div>

        <el-tabs v-model="activeMainTab" class="main-tabs">
            <el-tab-pane :label="t('config.financeCashierConfig.tab_cashier')" name="cashier"></el-tab-pane>
            <el-tab-pane :label="t('config.financeCashierConfig.tab_tiers')" name="tiers"></el-tab-pane>
            <el-tab-pane :label="t('config.financeCashierConfig.tab_deposit_banks')" name="depositBanks"></el-tab-pane>
            <el-tab-pane :label="t('config.financeCashierConfig.tab_withdraw_banks')" name="withdrawBanks"></el-tab-pane>
        </el-tabs>

        <el-scrollbar max-height="calc(100vh - 220px)">
            <el-form v-loading="loading" label-width="160px" class="finance-cashier-form">
                <el-card v-if="activeMainTab === 'cashier'" shadow="never" class="section-card">
                    <template #header>{{ t('config.financeCashierConfig.sec_platform') }}</template>
                    <el-form-item :label="t('config.financeCashierConfig.platform_label_zh')">
                        <el-input v-model="form.platform_coin.label_zh" maxlength="32" class="w400" />
                    </el-form-item>
                    <el-form-item :label="t('config.financeCashierConfig.platform_label_en')">
                        <el-input v-model="form.platform_coin.label_en" maxlength="32" class="w400" />
                    </el-form-item>
                </el-card>

                <el-card v-if="activeMainTab === 'cashier'" shadow="never" class="section-card">
                    <template #header>
                        <span>{{ t('config.financeCashierConfig.sec_currencies') }}</span>
                        <el-button v-if="canSave" type="primary" link class="ml-2" @click="addCurrency">{{ t('config.financeCashierConfig.btn_add_row') }}</el-button>
                    </template>
                    <p class="hint">{{ t('config.financeCashierConfig.currency_rates_hint') }}</p>
                    <el-table :data="form.currencies" border stripe size="small">
                        <el-table-column :label="t('config.financeCashierConfig.col_code')" prop="code" width="110">
                            <template #default="{ row }">
                                <el-input
                                    v-model="row.code"
                                    maxlength="12"
                                    :placeholder="t('config.financeCashierConfig.ph_currency_code')"
                                    @blur="normalizeCurrencyCode(row)"
                                />
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('config.financeCashierConfig.col_label_zh')" min-width="130">
                            <template #default="{ row }">
                                <el-input v-model="row.label_zh" maxlength="64" />
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('config.financeCashierConfig.col_label_en')" min-width="130">
                            <template #default="{ row }">
                                <el-input v-model="row.label_en" maxlength="64" />
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('config.financeCashierConfig.col_deposit_rate')" min-width="120">
                            <template #default="{ row }">
                                <el-input v-model="row.deposit_coins_per_fiat" :placeholder="t('config.financeCashierConfig.ph_ratio')" />
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('config.financeCashierConfig.col_withdraw_rate')" min-width="120">
                            <template #default="{ row }">
                                <el-input v-model="row.withdraw_coins_per_fiat" :placeholder="t('config.financeCashierConfig.ph_ratio')" />
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('config.financeCashierConfig.col_sort')" width="108">
                            <template #default="{ row }">
                                <el-input-number v-model="row.sort" :min="0" :max="99999" :controls="true" class="w100p" @change="resortCurrenciesInPlace" />
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('Operate')" width="90" align="center">
                            <template #default="{ $index }">
                                <el-button v-if="canSave" type="danger" link @click="removeCurrencyRow($index)">{{ t('Delete') }}</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>

                <el-card v-if="activeMainTab === 'cashier'" shadow="never" class="section-card">
                    <template #header>{{ t('config.financeCashierConfig.sec_deposit_channels') }}</template>
                    <p class="hint">{{ t('config.financeCashierConfig.deposit_channels_hint') }}</p>
                    <el-table :data="form.channels" border stripe size="small">
                        <el-table-column :label="t('config.financeCashierConfig.ch_code')" prop="code" width="140">
                            <template #default="{ row }">
                                <el-input :model-value="String(row.code ?? '')" readonly />
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('config.financeCashierConfig.ch_display_name')" min-width="140">
                            <template #default="{ row }">
                                <el-input :model-value="channelDisplayName(String(row.code ?? ''))" readonly />
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('config.financeCashierConfig.ch_sort')" width="108">
                            <template #default="{ row }">
                                <el-input-number
                                    v-model="row.sort"
                                    :min="0"
                                    :max="9999"
                                    :controls="true"
                                    class="w100p"
                                    @change="resortChannelsInPlace"
                                />
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('config.financeCashierConfig.ch_status')" width="100" align="center">
                            <template #default="{ row }">
                                <el-switch v-model="row.status" :active-value="1" :inactive-value="0" />
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('config.financeCashierConfig.ch_currency_codes')" min-width="260">
                            <template #default="{ row }">
                                <div class="currency-codes-cell">
                                    <el-checkbox-group v-model="row.currency_codes" size="small">
                                        <el-checkbox
                                            v-for="c in form.currencies"
                                            :key="c.code"
                                            :label="c.code"
                                        >
                                            {{ currencyLabel(c.code) }}
                                        </el-checkbox>
                                    </el-checkbox-group>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>

                <el-card v-if="activeMainTab === 'tiers'" shadow="never" class="section-card">
                    <template #header>
                        <span>{{ t('config.financeCashierConfig.sec_deposit_tiers') }}</span>
                        <el-button v-if="canSave" type="primary" link class="ml-2" @click="addTier">{{ t('config.financeCashierConfig.btn_add_row') }}</el-button>
                        <el-button v-if="canSave" type="success" link class="ml-2" :loading="tiersSaving" @click="saveTiers">{{ t('config.financeCashierConfig.btn_save_tiers') }}</el-button>
                    </template>
                    <p class="hint">{{ t('config.financeCashierConfig.deposit_tiers_hint') }}</p>
                    <el-table :data="tiers" border stripe size="small">
                        <el-table-column :label="t('config.financeCashierConfig.col_tier_id')" min-width="130">
                            <template #default="{ row }">
                                <el-input v-model="row.id" maxlength="32" />
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('config.financeCashierConfig.col_title_zh')" min-width="140">
                            <template #default="{ row }">
                                <el-input v-model="row.title" maxlength="64" />
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('config.financeCashierConfig.col_title_en')" min-width="140">
                            <template #default="{ row }">
                                <el-input v-model="row.title_en" maxlength="64" />
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('config.financeCashierConfig.col_currency_code')" width="120">
                            <template #default="{ row }">
                                <el-select v-model="row.currency" class="w100p" filterable>
                                    <el-option v-for="c in form.currencies" :key="c.code" :label="currencyLabel(c.code)" :value="c.code" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('config.financeCashierConfig.col_pay_amount')" width="120">
                            <template #default="{ row }">
                                <el-input v-model="row.pay_amount" />
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('config.financeCashierConfig.col_amount')" width="120">
                            <template #default="{ row }">
                                <el-input v-model="row.amount" />
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('config.financeCashierConfig.col_bonus_amount')" width="120">
                            <template #default="{ row }">
                                <el-input v-model="row.bonus_amount" />
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('config.financeCashierConfig.col_tier_sort')" width="120">
                            <template #default="{ row }">
                                <el-input-number v-model="row.sort" :min="0" :max="99999" :controls="false" class="w100p" />
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('config.financeCashierConfig.col_tier_status')" width="90" align="center">
                            <template #default="{ row }">
                                <el-switch v-model="row.status" :active-value="1" :inactive-value="0" />
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('Operate')" width="90" align="center">
                            <template #default="{ $index }">
                                <el-button v-if="canSave" type="danger" link @click="removeRow(tiers, $index)">{{ t('Delete') }}</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>

                <el-card v-if="activeMainTab === 'depositBanks'" shadow="never" class="section-card">
                    <template #header>
                        <span>{{ t('config.financeCashierConfig.sec_deposit_banks') }}</span>
                        <el-button v-if="canSave" type="primary" link class="ml-2" @click="addDepositBank">{{ t('config.financeCashierConfig.btn_add_row') }}</el-button>
                    </template>
                    <p class="hint">{{ t('config.financeCashierConfig.deposit_banks_hint') }}</p>
                    <el-table :data="form.deposit_banks" border stripe size="small">
                        <el-table-column :label="t('config.financeCashierConfig.col_currency_code')" width="140">
                            <template #default="{ row }">
                                <el-select v-model="row.currency_code" class="w100p" filterable>
                                    <el-option v-for="c in form.currencies" :key="c.code" :label="currencyLabel(c.code)" :value="c.code" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('config.financeCashierConfig.col_bank_code')" width="140">
                            <template #default="{ row }">
                                <el-input v-model="row.code" maxlength="32" :placeholder="t('config.financeCashierConfig.ph_bank_code')" />
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('config.financeCashierConfig.col_name_zh')" min-width="140">
                            <template #default="{ row }">
                                <el-input v-model="row.name_zh" maxlength="64" />
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('config.financeCashierConfig.col_name_en')" min-width="140">
                            <template #default="{ row }">
                                <el-input v-model="row.name_en" maxlength="64" />
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('config.financeCashierConfig.col_sort')" width="108">
                            <template #default="{ row }">
                                <el-input-number v-model="row.sort" :min="0" :max="99999" :controls="true" class="w100p" @change="resortDepositBanksInPlace" />
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('Operate')" width="90" align="center">
                            <template #default="{ $index }">
                                <el-button v-if="canSave" type="danger" link @click="removeRow(form.deposit_banks, $index)">{{ t('Delete') }}</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>

                <el-card v-if="activeMainTab === 'withdrawBanks'" shadow="never" class="section-card">
                    <template #header>
                        <span>{{ t('config.financeCashierConfig.sec_withdraw_banks') }}</span>
                        <el-button v-if="canSave" type="primary" link class="ml-2" @click="addWithdrawBank">{{ t('config.financeCashierConfig.btn_add_row') }}</el-button>
                    </template>
                    <p class="hint">{{ t('config.financeCashierConfig.withdraw_banks_hint') }}</p>
                    <el-table :data="form.withdraw_banks" border stripe size="small">
                        <el-table-column :label="t('config.financeCashierConfig.col_currency_code')" width="140">
                            <template #default="{ row }">
                                <el-select v-model="row.currency_code" class="w100p" filterable>
                                    <el-option v-for="c in form.currencies" :key="c.code" :label="currencyLabel(c.code)" :value="c.code" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('config.financeCashierConfig.col_bank_code')" width="140">
                            <template #default="{ row }">
                                <el-input v-model="row.code" maxlength="32" :placeholder="t('config.financeCashierConfig.ph_bank_code')" />
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('config.financeCashierConfig.col_name_zh')" min-width="140">
                            <template #default="{ row }">
                                <el-input v-model="row.name_zh" maxlength="64" />
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('config.financeCashierConfig.col_name_en')" min-width="140">
                            <template #default="{ row }">
                                <el-input v-model="row.name_en" maxlength="64" />
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('config.financeCashierConfig.col_sort')" width="108">
                            <template #default="{ row }">
                                <el-input-number v-model="row.sort" :min="0" :max="99999" :controls="true" class="w100p" @change="resortWithdrawBanksInPlace" />
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('Operate')" width="90" align="center">
                            <template #default="{ $index }">
                                <el-button v-if="canSave" type="danger" link @click="removeRow(form.withdraw_banks, $index)">{{ t('Delete') }}</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>

                <el-card v-if="activeMainTab === 'cashier'" shadow="never" class="section-card">
                    <template #header>{{ t('config.financeCashierConfig.sec_limits') }}</template>
                    <el-form-item :label="t('config.financeCashierConfig.min_ewallet')">
                        <el-input v-model="form.withdraw_limits.min_ewallet" class="w240" />
                    </el-form-item>
                    <el-form-item :label="t('config.financeCashierConfig.min_bank')">
                        <el-input v-model="form.withdraw_limits.min_bank" class="w240" />
                    </el-form-item>
                </el-card>

                <el-card v-if="activeMainTab === 'cashier'" shadow="never" class="section-card">
                    <template #header>{{ t('config.financeCashierConfig.sec_copy') }}</template>
                    <el-form-item :label="t('config.financeCashierConfig.rate_mode')">
                        <el-select v-model="form.withdraw_copy.rate_mode" class="w240">
                            <el-option :label="t('config.financeCashierConfig.rate_mode_fixed')" value="fixed" />
                            <el-option :label="t('config.financeCashierConfig.rate_mode_live')" value="live" />
                        </el-select>
                    </el-form-item>
                    <el-form-item :label="t('config.financeCashierConfig.rate_hint_zh')">
                        <el-input v-model="form.withdraw_copy.rate_hint_zh" type="textarea" :rows="2" maxlength="500" />
                    </el-form-item>
                    <el-form-item :label="t('config.financeCashierConfig.rate_hint_en')">
                        <el-input v-model="form.withdraw_copy.rate_hint_en" type="textarea" :rows="2" maxlength="500" />
                    </el-form-item>
                    <el-form-item :label="t('config.financeCashierConfig.processing_zh')">
                        <el-input v-model="form.withdraw_copy.processing_zh" maxlength="255" />
                    </el-form-item>
                    <el-form-item :label="t('config.financeCashierConfig.processing_en')">
                        <el-input v-model="form.withdraw_copy.processing_en" maxlength="255" />
                    </el-form-item>
                    <el-form-item :label="t('config.financeCashierConfig.fee_note_zh')">
                        <el-input v-model="form.withdraw_copy.fee_note_zh" type="textarea" :rows="2" maxlength="500" />
                    </el-form-item>
                    <el-form-item :label="t('config.financeCashierConfig.fee_note_en')">
                        <el-input v-model="form.withdraw_copy.fee_note_en" type="textarea" :rows="2" maxlength="500" />
                    </el-form-item>
                </el-card>

                <el-card v-if="activeMainTab === 'cashier'" shadow="never" class="section-card">
                    <template #header>{{ t('config.financeCashierConfig.sec_ddpay_spec') }}</template>
                    <el-alert type="info" :closable="false" show-icon class="mb-2">
                        {{ t('config.financeCashierConfig.ddpay_spec_intro') }}
                    </el-alert>
                    <ul class="ddpay-spec-list">
                        <li>{{ t('config.financeCashierConfig.ddpay_spec_li_withdraw') }}</li>
                        <li>{{ t('config.financeCashierConfig.ddpay_spec_li_bank_table') }}</li>
                        <li>{{ t('config.financeCashierConfig.ddpay_spec_li_deposit') }}</li>
                        <li>{{ t('config.financeCashierConfig.ddpay_spec_li_doc') }}</li>
                    </ul>
                </el-card>
            </el-form>
        </el-scrollbar>
    </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage, ElMessageBox } from 'element-plus'
import createAxios from '/@/utils/axios'
import { auth } from '/@/utils/common'

defineOptions({
    name: 'config/financeCashierConfig',
})

const { t, locale } = useI18n()
const canSave = auth('save')

type CurrencyRow = {
    code: string
    label_zh: string
    label_en: string
    sort: number
    deposit_coins_per_fiat: string
    withdraw_coins_per_fiat: string
}
type BankRow = { currency_code: string; code: string; name_zh: string; name_en: string; sort: number }
type ChannelRow = { code: string; sort: number; status: number; tier_ids: string[]; currency_codes: string[] }
type TierRow = {
    id: string
    title: string
    title_en: string
    currency: string
    pay_amount: string
    amount: string
    bonus_amount: string
    desc: string
    desc_en: string
    sort: number
    status: number
}
type RegistryMeta = { name?: string; name_en?: string; sort?: number }

const loading = ref(false)
const saving = ref(false)
const registry = ref<Record<string, RegistryMeta>>({})
const activeMainTab = ref('cashier')
const originalCurrencyCodes = ref<string[]>([])
const tiers = ref<TierRow[]>([])
const tiersSaving = ref(false)

const form = reactive({
    platform_coin: { label_zh: '', label_en: '' },
    currencies: [] as CurrencyRow[],
    deposit_banks: [] as BankRow[],
    withdraw_banks: [] as BankRow[],
    withdraw_limits: { min_ewallet: '0', min_bank: '0' },
    withdraw_copy: {
        rate_hint_zh: '',
        rate_hint_en: '',
        processing_zh: '',
        processing_en: '',
        fee_note_zh: '',
        fee_note_en: '',
        rate_mode: 'fixed',
    },
    channels: [] as ChannelRow[],
})

function rowSortValue(row: { sort?: unknown }): number {
    const s = row.sort
    if (typeof s === 'number' && Number.isFinite(s)) {
        return Math.round(s)
    }
    if (typeof s === 'string' && s.trim() !== '') {
        const n = Number(s)
        if (!Number.isNaN(n) && Number.isFinite(n)) {
            return Math.round(n)
        }
    }
    return 0
}

function nextSort(rows: { sort?: unknown }[]): number {
    let m = 0
    for (const r of rows) {
        const v = rowSortValue(r)
        if (v > m) {
            m = v
        }
    }
    return m > 0 ? m + 10 : 10
}

function addCurrency() {
    form.currencies.push({
        code: '',
        label_zh: '',
        label_en: '',
        sort: nextSort(form.currencies),
        deposit_coins_per_fiat: '100',
        withdraw_coins_per_fiat: '100',
    })
}

function normalizeCurrencyCode(row: CurrencyRow) {
    row.code = String(row.code || '').trim().toUpperCase()
}

function resortCurrenciesInPlace() {
    form.currencies.sort((a, b) => {
        const ds = rowSortValue(a) - rowSortValue(b)
        if (ds !== 0) {
            return ds
        }
        return String(a.code || '').localeCompare(String(b.code || ''))
    })
}

function resortDepositBanksInPlace() {
    form.deposit_banks.sort((a, b) => {
        const cc = String(a.currency_code || '').localeCompare(String(b.currency_code || ''))
        if (cc !== 0) {
            return cc
        }
        const ds = rowSortValue(a) - rowSortValue(b)
        if (ds !== 0) {
            return ds
        }
        return String(a.code || '').localeCompare(String(b.code || ''))
    })
}

function resortWithdrawBanksInPlace() {
    form.withdraw_banks.sort((a, b) => {
        const cc = String(a.currency_code || '').localeCompare(String(b.currency_code || ''))
        if (cc !== 0) {
            return cc
        }
        const ds = rowSortValue(a) - rowSortValue(b)
        if (ds !== 0) {
            return ds
        }
        return String(a.code || '').localeCompare(String(b.code || ''))
    })
}

function resortChannelsInPlace() {
    form.channels.sort((a, b) => {
        const ds = rowSortValue(a) - rowSortValue(b)
        if (ds !== 0) {
            return ds
        }
        return String(a.code || '').localeCompare(String(b.code || ''))
    })
}

function channelDisplayName(code: string): string {
    const r = registry.value[code]
    if (!r) {
        return code
    }
    const loc = String(locale.value ?? '').toLowerCase().replaceAll('_', '-')
    const preferEn = loc === 'en' || loc.startsWith('en-')
    if (preferEn) {
        const ne = r.name_en
        if (typeof ne === 'string' && ne !== '') {
            return ne
        }
    }
    const n = r.name
    if (typeof n === 'string' && n !== '') {
        return n
    }
    const ne = r.name_en
    if (typeof ne === 'string' && ne !== '') {
        return ne
    }
    return code
}

function currencyLabel(code: string): string {
    const cur = form.currencies.find((x) => x.code === code)
    if (!cur) {
        return code
    }
    const loc = String(locale.value ?? '').toLowerCase().replaceAll('_', '-')
    const preferEn = loc === 'en' || loc.startsWith('en-')
    if (preferEn) {
        if (typeof cur.label_en === 'string' && cur.label_en !== '') {
            return cur.label_en
        }
    }
    if (typeof cur.label_zh === 'string' && cur.label_zh !== '') {
        return cur.label_zh
    }
    return cur.label_en
}

function normalizeChannelRow(c: Record<string, unknown>, defaultCurrencyCodes: string[]): ChannelRow {
    const st = c.status
    const statusOn = st === 1 || st === true || st === '1'
    const rawCodes = c.currency_codes
    const isArray = Array.isArray(rawCodes)
    // null/undefined 表示“兼容全部币种”（历史配置默认行为）
    const codesCandidate = isArray ? (rawCodes as unknown[]) : null
    const all = new Set(defaultCurrencyCodes)

    let cc: string[]
    if (codesCandidate === null) {
        cc = defaultCurrencyCodes
    } else {
        cc = codesCandidate
            .map((x) => (typeof x === 'string' ? x.trim().toUpperCase() : ''))
            .filter((x) => x !== '')
            .filter((x) => all.has(x))
    }

    return {
        code: typeof c.code === 'string' ? c.code : '',
        sort: rowSortValue({ sort: c.sort }),
        status: statusOn ? 1 : 0,
        tier_ids: [],
        currency_codes: cc,
    }
}

function addDepositBank() {
    form.deposit_banks.push({ currency_code: '', code: '', name_zh: '', name_en: '', sort: nextSort(form.deposit_banks) })
}

function addWithdrawBank() {
    form.withdraw_banks.push({ currency_code: '', code: '', name_zh: '', name_en: '', sort: nextSort(form.withdraw_banks) })
}

function removeRow<T>(arr: T[], index: number) {
    arr.splice(index, 1)
}

async function removeCurrencyRow(index: number) {
    const row = form.currencies[index]
    if (!row) {
        return
    }
    const code = String(row.code || '').trim().toUpperCase()
    if (code === '') {
        form.currencies.splice(index, 1)
        return
    }
    const affected = tiers.value.filter((x) => String(x.currency || '').trim().toUpperCase() === code)
    if (affected.length === 0) {
        form.currencies.splice(index, 1)
        return
    }
    const sample = affected.slice(0, 10).map((x) => x.id).join(',')
    const confirmed = await ElMessageBox.confirm(
        t('config.financeCashierConfig.msg_delete_currency_prune_tiers', { currency: code, count: affected.length }) +
            (sample !== '' ? `\n${t('config.financeCashierConfig.msg_affected_tier_ids')}: ${sample}` : ''),
        t('Warning'),
        { type: 'warning', confirmButtonText: t('OK'), cancelButtonText: t('Cancel') }
    ).then(() => true).catch(() => false)
    if (!confirmed) {
        return
    }
    form.currencies.splice(index, 1)
}

async function load() {
    loading.value = true
    try {
        const res = await createAxios({
            url: '/admin/config.FinanceCashierConfig/index',
            method: 'get',
        })
        if (res.code === 1 && res.data && res.data.form) {
            const f = res.data.form as typeof form
            const regRaw = res.data.registry
            registry.value =
                regRaw !== null && typeof regRaw === 'object' && !Array.isArray(regRaw)
                    ? (regRaw as Record<string, RegistryMeta>)
                    : {}
            Object.assign(form.platform_coin, f.platform_coin || {})
            const curList = Array.isArray(f.currencies) ? f.currencies : []
            const normalized: CurrencyRow[] = curList.map((c: Record<string, unknown>) => ({
                code: typeof c.code === 'string' ? c.code : '',
                label_zh: typeof c.label_zh === 'string' ? c.label_zh : '',
                label_en: typeof c.label_en === 'string' ? c.label_en : '',
                sort: rowSortValue({ sort: c.sort }),
                deposit_coins_per_fiat:
                    typeof c.deposit_coins_per_fiat === 'string'
                        ? c.deposit_coins_per_fiat
                        : typeof c.deposit_coins_per_fiat === 'number'
                          ? String(c.deposit_coins_per_fiat)
                          : '100',
                withdraw_coins_per_fiat:
                    typeof c.withdraw_coins_per_fiat === 'string'
                        ? c.withdraw_coins_per_fiat
                        : typeof c.withdraw_coins_per_fiat === 'number'
                          ? String(c.withdraw_coins_per_fiat)
                          : '100',
            }))
            form.currencies.splice(0, form.currencies.length, ...normalized)
            originalCurrencyCodes.value = normalized.map((x) => x.code)
            resortCurrenciesInPlace()
            const defaultCurrencyCodes = normalized.map((x) => String(x.code || '')).filter((x) => x !== '')
            const depositBankList = Array.isArray(f.deposit_banks) ? f.deposit_banks : []
            const depositBanksNorm: BankRow[] = depositBankList.map((b: Record<string, unknown>) => ({
                currency_code: typeof b.currency_code === 'string' ? b.currency_code : '',
                code: typeof b.code === 'string' ? b.code : '',
                name_zh: typeof b.name_zh === 'string' ? b.name_zh : '',
                name_en: typeof b.name_en === 'string' ? b.name_en : '',
                sort: rowSortValue({ sort: b.sort }),
            }))
            form.deposit_banks.splice(0, form.deposit_banks.length, ...depositBanksNorm)
            resortDepositBanksInPlace()
            const bankList = Array.isArray(f.withdraw_banks) ? f.withdraw_banks : []
            const banksNorm: BankRow[] = bankList.map((b: Record<string, unknown>) => ({
                currency_code: typeof b.currency_code === 'string' ? b.currency_code : '',
                code: typeof b.code === 'string' ? b.code : '',
                name_zh: typeof b.name_zh === 'string' ? b.name_zh : '',
                name_en: typeof b.name_en === 'string' ? b.name_en : '',
                sort: rowSortValue({ sort: b.sort }),
            }))
            form.withdraw_banks.splice(0, form.withdraw_banks.length, ...banksNorm)
            resortWithdrawBanksInPlace()
            const chList = Array.isArray(f.channels) ? f.channels : []
            const channelsNorm: ChannelRow[] = chList.map((c) => normalizeChannelRow(c as Record<string, unknown>, defaultCurrencyCodes))
            form.channels.splice(0, form.channels.length, ...channelsNorm)
            resortChannelsInPlace()
            Object.assign(form.withdraw_limits, f.withdraw_limits || {})
            Object.assign(form.withdraw_copy, f.withdraw_copy || {})
            await loadTiers()
        }
    } finally {
        loading.value = false
    }
}

async function loadTiers() {
    const res = await createAxios({
        url: '/admin/config.FinanceCashierConfig/tierList',
        method: 'get',
    })
    const listRaw = res.code === 1 && Array.isArray(res.data?.list) ? res.data.list : []
    tiers.value = listRaw.map((row: Record<string, unknown>) => ({
        id: typeof row.id === 'string' ? row.id : '',
        title: typeof row.title === 'string' ? row.title : '',
        title_en: typeof row.title_en === 'string' ? row.title_en : '',
        currency: typeof row.currency === 'string' ? row.currency : '',
        pay_amount: typeof row.pay_amount === 'string' ? row.pay_amount : String(row.pay_amount ?? ''),
        amount: typeof row.amount === 'string' ? row.amount : String(row.amount ?? ''),
        bonus_amount: typeof row.bonus_amount === 'string' ? row.bonus_amount : String(row.bonus_amount ?? '0'),
        desc: typeof row.desc === 'string' ? row.desc : '',
        desc_en: typeof row.desc_en === 'string' ? row.desc_en : '',
        sort: rowSortValue({ sort: row.sort }),
        status: row.status === 1 || row.status === true || row.status === '1' ? 1 : 0,
    }))
}

function addTier() {
    const currency = form.currencies.length > 0 ? form.currencies[0].code : ''
    tiers.value.push({
        id: `t_${Date.now()}_${Math.floor(Math.random() * 1000)}`,
        title: '',
        title_en: '',
        currency,
        pay_amount: '',
        amount: '',
        bonus_amount: '0',
        desc: '',
        desc_en: '',
        sort: 10,
        status: 1,
    })
}

async function saveTiers() {
    if (!canSave) {
        return
    }
    tiersSaving.value = true
    try {
        await createAxios({
            url: '/admin/config.FinanceCashierConfig/tierSave',
            method: 'post',
            data: {
                items: JSON.parse(JSON.stringify(tiers.value)),
            },
            showSuccessMessage: true,
        })
        await loadTiers()
    } finally {
        tiersSaving.value = false
    }
}

async function onSave() {
    if (!auth('save')) {
        return
    }
    for (const row of form.currencies) {
        normalizeCurrencyCode(row)
    }
    const codes = form.currencies.map((c) => String(c.code || '').trim().toUpperCase()).filter((c) => c !== '')
    if (new Set(codes).size !== codes.length) {
        ElMessage.warning(t('config.financeCashierConfig.err_dup_code'))
        return
    }
    resortCurrenciesInPlace()
    const allowed = new Set(form.currencies.map((c) => String(c.code || '').trim().toUpperCase()).filter((x) => x !== ''))
    for (const b of form.deposit_banks) {
        b.currency_code = String(b.currency_code || '').trim().toUpperCase()
        b.code = String(b.code || '').trim().toLowerCase()
        if (!allowed.has(b.currency_code)) {
            b.currency_code = ''
        }
    }
    for (const b of form.withdraw_banks) {
        b.currency_code = String(b.currency_code || '').trim().toUpperCase()
        b.code = String(b.code || '').trim().toLowerCase()
        if (!allowed.has(b.currency_code)) {
            b.currency_code = ''
        }
    }
    resortDepositBanksInPlace()
    resortWithdrawBanksInPlace()
    resortChannelsInPlace()
    const removedCurrencyCodes = originalCurrencyCodes.value.filter((x) => !allowed.has(x))
    let pruneTierCurrencies: string[] = []
    if (removedCurrencyCodes.length > 0) {
        const affected = tiers.value.filter((x) => removedCurrencyCodes.includes(String(x.currency || '').toUpperCase()))
        if (affected.length > 0) {
            const sample = affected.slice(0, 10).map((x) => x.id).join(', ')
            const detail = sample !== '' ? `\n${t('config.financeCashierConfig.msg_affected_tier_ids')}: ${sample}` : ''
            const confirmed = await ElMessageBox.confirm(
                t('config.financeCashierConfig.msg_delete_currency_prune_tiers', {
                    currency: removedCurrencyCodes.join(','),
                    count: affected.length,
                }) + detail,
                t('Warning'),
                {
                    type: 'warning',
                    confirmButtonText: t('OK'),
                    cancelButtonText: t('Cancel'),
                }
            ).then(() => true).catch(() => false)
            if (!confirmed) {
                return
            }
            pruneTierCurrencies = removedCurrencyCodes
        }
    }
    // 仅保留配置了的币种码（后端还会校验）
    for (const ch of form.channels) {
        const raw = Array.isArray(ch.currency_codes) ? ch.currency_codes : []
        const normalized = raw
            .map((x) => (typeof x === 'string' ? x.trim().toUpperCase() : ''))
            .filter((x) => x !== '')
            .filter((x) => allowed.has(x))
        ch.currency_codes = Array.from(new Set(normalized))
    }
    saving.value = true
    try {
        await createAxios({
            url: '/admin/config.FinanceCashierConfig/save',
            method: 'post',
            data: {
                ...JSON.parse(JSON.stringify(form)),
                prune_tier_currency_codes: pruneTierCurrencies,
            },
            showSuccessMessage: true,
        })
        await load()
    } finally {
        saving.value = false
    }
}

onMounted(() => {
    void load()
})
</script>

<style scoped lang="scss">
.finance-cashier-page {
    .toolbar {
        margin-bottom: 12px;
    }
    .section-card {
        margin-bottom: 16px;
    }
    .hint {
        color: var(--el-text-color-secondary);
        font-size: 13px;
        margin: 0 0 10px;
    }
    .w400 {
        max-width: 400px;
    }
    .w240 {
        max-width: 240px;
    }
    .w100p {
        width: 100%;
    }
    .mb-3 {
        margin-bottom: 12px;
    }
    .ml-2 {
        margin-left: 8px;
    }
    .mb-2 {
        margin-bottom: 10px;
    }
    .main-tabs {
        margin-bottom: 8px;
    }
}

.ddpay-spec-list {
    margin: 0;
    padding-left: 1.25rem;
    color: var(--el-text-color-regular);
    font-size: 13px;
    line-height: 1.65;
}
.ddpay-spec-list li {
    margin-bottom: 6px;
}

.currency-codes-cell {
    display: flex;
    flex-wrap: wrap;
    gap: 8px 12px;
    align-items: center;
    padding-right: 6px;
}
</style>
