<template>
    <el-dialog
        class="ba-operate-dialog"
        :close-on-click-modal="false"
        :model-value="['Add', 'Edit'].includes(baTable.form.operate!)"
        @close="baTable.toggleForm"
    >
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                {{ baTable.form.operate ? t(baTable.form.operate) : '' }}
            </div>
        </template>
        <el-scrollbar v-loading="baTable.form.loading" class="ba-table-form-scrollbar">
            <div
                class="ba-operate-form"
                :class="'ba-' + baTable.form.operate + '-form'"
                :style="config.layout.shrink ? '' : 'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
            >
                <el-form
                    v-if="!baTable.form.loading"
                    ref="formRef"
                    @submit.prevent=""
                    @keyup.enter="baTable.onSubmit(formRef)"
                    :model="baTable.form.items"
                    :label-position="config.layout.shrink ? 'top' : 'right'"
                    :label-width="baTable.form.labelWidth + 'px'"
                    :rules="rules"
                >
                    <el-alert class="ba-table-alert" type="info" :closable="false" show-icon>
                        {{ t('config.depositTier.form_tip') }}
                    </el-alert>

                    <el-form-item v-if="baTable.form.operate === 'Edit'" :label="t('config.depositTier.tier_id')" prop="id">
                        <el-input :model-value="String(baTable.form.items!.id ?? '')" readonly />
                    </el-form-item>
                    <el-form-item v-if="baTable.form.operate === 'Add'" :label="t('config.depositTier.tier_id_optional')" prop="id">
                        <el-input v-model="baTable.form.items!.id" clearable :placeholder="t('config.depositTier.tier_id_optional_ph')" />
                    </el-form-item>

                    <el-form-item :label="t('config.depositTier.sort')" prop="sort">
                        <el-input-number v-model="baTable.form.items!.sort" :min="0" :max="9999" :controls="true" class="w100" />
                    </el-form-item>
                    <el-form-item :label="t('config.depositTier.status')" prop="status">
                        <el-switch v-model="baTable.form.items!.status" :active-value="1" :inactive-value="0" />
                    </el-form-item>

                    <el-form-item :label="t('config.depositTier.title_col')" prop="title">
                        <el-input v-model="baTable.form.items!.title" maxlength="64" :placeholder="t('config.depositTier.title_ph')" />
                    </el-form-item>
                    <el-form-item :label="t('config.depositTier.title_en_col')" prop="title_en">
                        <el-input v-model="baTable.form.items!.title_en" maxlength="64" :placeholder="t('config.depositTier.title_en_ph')" />
                    </el-form-item>

                    <el-form-item :label="t('config.depositTier.pay_currency')" prop="currency">
                        <el-select v-model="baTable.form.items!.currency" filterable allow-create default-first-option class="w100" :placeholder="t('config.depositTier.pay_currency_ph')">
                            <el-option v-for="c in payCurrencies" :key="c" :label="c" :value="c" />
                        </el-select>
                    </el-form-item>
                    <el-form-item :label="t('config.depositTier.pay_amount')" prop="pay_amount">
                        <el-input v-model="baTable.form.items!.pay_amount" :placeholder="t('config.depositTier.pay_amount_ph')" />
                    </el-form-item>
                    <el-form-item :label="t('config.depositTier.platform_base')" prop="amount">
                        <el-input v-model="baTable.form.items!.amount" :placeholder="t('config.depositTier.platform_base_ph')" />
                    </el-form-item>
                    <el-form-item :label="t('config.depositTier.bonus_amount')" prop="bonus_amount">
                        <el-input v-model="baTable.form.items!.bonus_amount" :placeholder="t('config.depositTier.bonus_ph')" />
                    </el-form-item>
                    <el-form-item :label="t('config.depositTier.desc_col')" prop="desc">
                        <el-input v-model="baTable.form.items!.desc" type="textarea" :rows="2" maxlength="255" :placeholder="t('config.depositTier.desc_ph')" />
                    </el-form-item>
                    <el-form-item :label="t('config.depositTier.desc_en_col')" prop="desc_en">
                        <el-input v-model="baTable.form.items!.desc_en" type="textarea" :rows="2" maxlength="255" :placeholder="t('config.depositTier.desc_en_ph')" />
                    </el-form-item>
                </el-form>
            </div>
        </el-scrollbar>
        <template #footer>
            <div :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'">
                <el-button @click="baTable.toggleForm()">{{ t('Cancel') }}</el-button>
                <el-button v-blur :loading="baTable.form.submitLoading" @click="baTable.onSubmit(formRef)" type="primary">
                    {{ t('Save') }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormItemRule } from 'element-plus'
import { inject, onMounted, reactive, ref, useTemplateRef } from 'vue'
import { useI18n } from 'vue-i18n'
import { useConfig } from '/@/stores/config'
import createAxios from '/@/utils/axios'

const config = useConfig()
const formRef = useTemplateRef<FormInstance>('formRef')
const baTable = inject('baTable') as baTable
const { t } = useI18n()

const payCurrencies = ref<string[]>(['MYR', 'CNY', 'USD', 'USDT', 'VND', 'THB', 'SGD', 'IDR'])

async function loadPayCurrencies() {
    try {
        const res = await createAxios({
            url: '/admin/config.DepositTier/currencyOptions',
            method: 'GET',
        })
        const listRaw = (res as anyObj)?.data?.list
        if (Array.isArray(listRaw)) {
            const list = listRaw
                .map((x: unknown) => (typeof x === 'string' ? x.trim().toUpperCase() : ''))
                .filter((x: string) => x !== '')
            if (list.length > 0) {
                payCurrencies.value = Array.from(new Set(list))
            }
        }
    } catch (_e) {
        // 下拉拉取失败时保持内置兜底列表，避免阻断表单编辑
    }
}

function positiveAmountRule(msg: string): FormItemRule {
    return {
        validator: (_rule, val, callback) => {
            const s = val === null || val === undefined ? '' : String(val).trim().replace(',', '.')
            if (s === '' || !/^-?\d+(\.\d+)?$/.test(s)) {
                callback(new Error(msg))
                return
            }
            const n = parseFloat(s)
            if (!Number.isFinite(n) || n <= 0) {
                callback(new Error(msg))
                return
            }
            callback()
        },
        trigger: 'blur',
    }
}

function nonNegAmountRule(msg: string): FormItemRule {
    return {
        validator: (_rule, val, callback) => {
            const s = val === null || val === undefined || val === '' ? '0' : String(val).trim().replace(',', '.')
            if (!/^-?\d+(\.\d+)?$/.test(s)) {
                callback(new Error(msg))
                return
            }
            const n = parseFloat(s)
            if (!Number.isFinite(n) || n < 0) {
                callback(new Error(msg))
                return
            }
            callback()
        },
        trigger: 'blur',
    }
}

const rules = reactive({
    title: [{ required: true, message: t('config.depositTier.rule_title'), trigger: 'blur' }],
    currency: [{ required: true, message: t('config.depositTier.rule_currency'), trigger: 'change' }],
    pay_amount: [positiveAmountRule(t('config.depositTier.rule_pay_amount'))],
    amount: [positiveAmountRule(t('config.depositTier.rule_platform_base'))],
    bonus_amount: [nonNegAmountRule(t('config.depositTier.rule_bonus'))],
})

onMounted(() => {
    loadPayCurrencies()
})
</script>

<style scoped lang="scss">
.w100 {
    width: 100%;
}
</style>
