<template>
    <el-dialog
        class="ba-operate-dialog deposit-review-dialog"
        :close-on-click-modal="false"
        :model-value="isOpen"
        width="640px"
        @close="onDialogClose"
    >
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                {{
                    step === 'reject'
                        ? t('order.depositOrder.review_reject_title')
                        : isPendingReview
                          ? t('order.depositOrder.review_title')
                          : t('order.depositOrder.detail_title')
                }}
            </div>
        </template>

        <el-scrollbar v-loading="loading" class="ba-table-form-scrollbar">
            <div
                class="ba-operate-form ba-edit-form"
                :style="config.layout.shrink ? '' : 'width: calc(100% - ' + (baTable.form.labelWidth ?? 120) / 2 + 'px)'"
            >
                <el-form
                    v-if="!loading && step === 'review'"
                    :label-position="config.layout.shrink ? 'top' : 'right'"
                    :label-width="(baTable.form.labelWidth ?? 120) + 'px'"
                    @submit.prevent=""
                >
                    <el-form-item :label="t('order.depositOrder.order_no')">
                        <el-input :model-value="form.order_no" readonly />
                    </el-form-item>
                    <el-form-item :label="t('order.depositOrder.idempotency_key')">
                        <el-input :model-value="form.idempotency_key || '-'" readonly />
                    </el-form-item>
                    <el-form-item :label="t('order.depositOrder.user_username')">
                        <el-input :model-value="form.user_text" readonly />
                    </el-form-item>
                    <el-form-item :label="t('order.depositOrder.channel_name')">
                        <el-input :model-value="form.channel_text" readonly />
                    </el-form-item>
                    <el-form-item :label="t('order.depositOrder.status')">
                        <el-tag :type="statusTagType" effect="dark" size="small">{{ statusLabel }}</el-tag>
                    </el-form-item>
                    <el-form-item :label="t('order.depositOrder.amount')">
                        <el-input :model-value="amountText" readonly />
                    </el-form-item>
                    <el-form-item :label="t('order.depositOrder.bonus_amount')">
                        <el-input :model-value="bonusText" readonly />
                    </el-form-item>
                    <el-form-item :label="t('order.depositOrder.total_credit')">
                        <el-input :model-value="totalCreditText" readonly />
                    </el-form-item>
                    <el-form-item :label="t('order.depositOrder.pay_channel')">
                        <el-input :model-value="form.pay_channel || '-'" readonly />
                    </el-form-item>
                    <el-form-item :label="t('order.depositOrder.pay_time')">
                        <el-input :model-value="form.pay_time_text" readonly />
                    </el-form-item>
                    <el-form-item :label="t('order.depositOrder.deposit_tier_id')">
                        <el-input :model-value="form.deposit_tier_id || '-'" readonly />
                    </el-form-item>
                    <el-form-item v-if="form.reject_reason" :label="t('order.depositOrder.reject_reason')">
                        <el-input :model-value="form.reject_reason" type="textarea" :rows="2" readonly />
                    </el-form-item>
                    <el-form-item v-if="!isPendingReview" :label="t('order.depositOrder.review_admin_username')">
                        <el-input :model-value="form.review_admin_text" readonly />
                    </el-form-item>
                    <el-form-item v-if="!isPendingReview" :label="t('order.depositOrder.review_time')">
                        <el-input :model-value="form.review_time_text" readonly />
                    </el-form-item>
                    <el-form-item :label="t('order.depositOrder.remark')">
                        <el-input v-model="form.remark" type="textarea" :rows="2" readonly />
                    </el-form-item>
                    <el-form-item :label="t('order.depositOrder.create_time')">
                        <el-input :model-value="form.create_time_text" readonly />
                    </el-form-item>
                </el-form>

                <el-form
                    v-if="!loading && step === 'reject'"
                    ref="rejectFormRef"
                    :model="rejectForm"
                    :rules="rejectRules"
                    :label-position="config.layout.shrink ? 'top' : 'right'"
                    :label-width="(baTable.form.labelWidth ?? 120) + 'px'"
                    @submit.prevent=""
                >
                    <el-alert
                        class="review-reject-hint"
                        type="warning"
                        show-icon
                        :closable="false"
                        :title="t('order.depositOrder.review_reject_tip')"
                    />
                    <el-form-item :label="t('order.depositOrder.order_no')">
                        <el-input :model-value="form.order_no" readonly />
                    </el-form-item>
                    <el-form-item :label="t('order.depositOrder.total_credit')">
                        <el-input :model-value="totalCreditText" readonly />
                    </el-form-item>
                    <el-form-item :label="t('order.depositOrder.reject_reason')" prop="remark">
                        <el-input
                            v-model="rejectForm.remark"
                            type="textarea"
                            :rows="4"
                            maxlength="255"
                            show-word-limit
                            :placeholder="t('order.depositOrder.review_reject_placeholder')"
                        />
                    </el-form-item>
                </el-form>
            </div>
        </el-scrollbar>

        <template #footer>
            <div class="review-footer">
                <template v-if="step === 'review'">
                    <el-button @click="onDialogClose">{{ isPendingReview ? t('Cancel') : t('order.depositOrder.close_btn') }}</el-button>
                    <template v-if="isPendingReview">
                        <el-button type="danger" :loading="submitting" @click="gotoReject">{{ t('order.depositOrder.review_btn_reject') }}</el-button>
                        <el-button type="primary" v-blur :loading="submitting" @click="submitApprove">{{ t('order.depositOrder.review_btn_approve') }}</el-button>
                    </template>
                </template>
                <template v-else>
                    <el-button @click="backToReview">{{ t('order.depositOrder.review_btn_back') }}</el-button>
                    <el-button type="danger" v-blur :loading="submitting" @click="submitReject">{{ t('order.depositOrder.review_btn_confirm_reject') }}</el-button>
                </template>
            </div>
        </template>
    </el-dialog>
</template>

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

const config = useConfig()
const baTable = inject('baTable') as baTableClass
const { t } = useI18n()

const rejectFormRef = useTemplateRef<FormInstance>('rejectFormRef')

type Step = 'review' | 'reject'
const step = ref<Step>('review')
const loading = ref(false)
const submitting = ref(false)

const form = reactive({
    id: 0,
    order_no: '',
    idempotency_key: '',
    user_text: '-',
    channel_text: '-',
    pay_channel: '',
    pay_time_text: '-',
    deposit_tier_id: '',
    remark: '',
    reject_reason: '',
    create_time_text: '-',
    review_time_text: '-',
    review_admin_text: '-',
    amount: 0,
    bonus_amount: 0,
    status: 0,
})

const rejectForm = reactive({
    remark: '',
})

const isOpen = computed(() => ['Edit'].includes(baTable.form.operate ?? ''))
const isPendingReview = computed(() => form.status === 3)

watch(isOpen, (visible) => {
    if (!visible) {
        return
    }
    step.value = 'review'
    rejectForm.remark = ''
})

watch(
    () => ({ visible: isOpen.value, loadingState: baTable.form.loading, items: baTable.form.items }),
    ({ visible, loadingState }) => {
        if (!visible) return
        loading.value = loadingState === true
        if (loadingState) return
        hydrate()
    },
    { deep: true, immediate: true }
)

const hydrate = () => {
    const row = baTable.form.items as Record<string, unknown> | undefined
    if (!row || !row['id']) {
        return
    }
    form.id = Number(row['id'] ?? 0)
    form.order_no = String(row['order_no'] ?? '')
    form.idempotency_key = String(row['idempotency_key'] ?? '')
    form.pay_channel = String(row['pay_channel'] ?? '')
    form.deposit_tier_id = String(row['deposit_tier_id'] ?? '')
    form.remark = String(row['remark'] ?? '')
    form.reject_reason = String(row['reject_reason'] ?? '')
    form.amount = parseNumber(row['amount'])
    form.bonus_amount = parseNumber(row['bonus_amount'])
    form.status = Number(row['status'] ?? 0)
    form.create_time_text = formatTime(row['create_time'])
    form.pay_time_text = formatTime(row['pay_time'])
    form.review_time_text = formatTime(row['review_time'])
    form.user_text = resolveRelationText(row, 'user', row['user_id'])
    form.channel_text = resolveRelationText(row, 'channel', row['channel_id'])
    form.review_admin_text = resolveRelationText(row, 'reviewAdmin', row['review_admin_id'])
}

const statusLabel = computed(() => t('order.depositOrder.status ' + form.status))
const statusTagType = computed(() => {
    switch (form.status) {
        case 1:
            return 'success'
        case 2:
            return 'danger'
        case 3:
            return 'warning'
        default:
            return 'info'
    }
})

const amountText = computed(() => formatAmount(form.amount))
const bonusText = computed(() => formatAmount(form.bonus_amount))
const totalCreditText = computed(() => formatAmount(Number((form.amount + form.bonus_amount).toFixed(2))))

const rejectRules: Record<string, FormItemRule[]> = {
    remark: [
        {
            required: true,
            validator: (_r, value, cb) => {
                const text = typeof value === 'string' ? value.trim() : ''
                if (text === '') {
                    cb(new Error(t('order.depositOrder.reject_reason_required')))
                    return
                }
                cb()
            },
            trigger: 'blur',
        },
    ],
}

const onDialogClose = () => {
    if (submitting.value) {
        return
    }
    step.value = 'review'
    baTable.toggleForm()
}

const gotoReject = () => {
    step.value = 'reject'
    rejectForm.remark = ''
}

const backToReview = () => {
    step.value = 'review'
}

const submitApprove = async () => {
    if (!isPendingReview.value) {
        ElMessage.warning(t('order.depositOrder.already_reviewed'))
        return
    }
    submitting.value = true
    try {
        await createAxios(
            {
                url: '/admin/order.DepositOrder/approve',
                method: 'POST',
                data: { id: form.id },
            },
            { showSuccessMessage: true }
        )
        baTable.onTableHeaderAction('refresh', {})
        baTable.toggleForm()
    } catch (_e) {
        // axios interceptor
    } finally {
        submitting.value = false
    }
}

const submitReject = async () => {
    const formEl = rejectFormRef.value
    if (!formEl) return
    const valid = await formEl.validate().catch(() => false)
    if (!valid) return
    submitting.value = true
    try {
        await createAxios(
            {
                url: '/admin/order.DepositOrder/reject',
                method: 'POST',
                data: {
                    id: form.id,
                    remark: rejectForm.remark.trim(),
                },
            },
            { showSuccessMessage: true }
        )
        baTable.onTableHeaderAction('refresh', {})
        baTable.toggleForm()
    } catch (_e) {
        // axios interceptor
    } finally {
        submitting.value = false
    }
}

function parseNumber(raw: unknown): number {
    if (raw === null || raw === undefined || raw === '') return 0
    const n = Number(raw)
    if (!Number.isFinite(n)) return 0
    return Number(n.toFixed(2))
}

function formatAmount(value: number): string {
    if (!Number.isFinite(value)) return '0.00'
    return value.toFixed(2)
}

function formatTime(raw: unknown): string {
    if (raw === null || raw === undefined || raw === '' || raw === 0) return '-'
    const sec = Number(raw)
    if (!Number.isFinite(sec) || sec <= 0) return '-'
    const d = new Date(sec * 1000)
    const pad = (n: number) => (n < 10 ? '0' + n : String(n))
    return (
        d.getFullYear() +
        '-' +
        pad(d.getMonth() + 1) +
        '-' +
        pad(d.getDate()) +
        ' ' +
        pad(d.getHours()) +
        ':' +
        pad(d.getMinutes()) +
        ':' +
        pad(d.getSeconds())
    )
}

function resolveRelationText(row: Record<string, unknown>, relationKey: string, fallbackId: unknown): string {
    const rel = row[relationKey]
    if (rel && typeof rel === 'object') {
        const r = rel as Record<string, unknown>
        const name = r['username'] ?? r['name']
        if (typeof name === 'string' && name !== '') {
            const id = fallbackId === null || fallbackId === undefined || fallbackId === '' ? '' : ' (ID: ' + String(fallbackId) + ')'
            return name + id
        }
    }
    if (fallbackId === null || fallbackId === undefined || fallbackId === '') {
        return '-'
    }
    return 'ID: ' + String(fallbackId)
}
</script>

<style scoped lang="scss">
.deposit-review-dialog {
    :deep(.el-dialog__body) {
        padding-top: 8px;
    }
}

.review-footer {
    display: flex;
    justify-content: flex-end;
    gap: 8px;
}

.review-reject-hint {
    margin-bottom: 12px;
}
</style>
