<script setup>
import { OrderService } from '@/service/OrderService';
import { useToast } from 'primevue/usetoast';
import { computed, ref, watch } from 'vue';
import { useRoute } from 'vue-router';

const toast = useToast();
const route = useRoute();

const orderID = computed(() => Number(route.params.orderID));

const loading = ref(false);
const detail = ref(null);

const refundDialogVisible = ref(false);
const refundLoading = ref(false);
const refundForce = ref(false);
const refundReason = ref('');

function formatDate(value) {
    if (!value) return '-';
    if (String(value).startsWith('0001-01-01')) return '-';
    const date = new Date(value);
    if (Number.isNaN(date.getTime())) return String(value);
    return date.toLocaleString();
}

function formatCny(amountInCents) {
    const amount = Number(amountInCents) / 100;
    if (!Number.isFinite(amount)) return '-';
    return new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY' }).format(amount);
}

function getOrderStatusSeverity(value) {
    switch (value) {
        case 'paid':
            return 'success';
        case 'created':
        case 'refunding':
            return 'warn';
        case 'failed':
        case 'canceled':
            return 'danger';
        default:
            return 'secondary';
    }
}

function safeJson(value) {
    try {
        return JSON.stringify(value ?? null, null, 2);
    } catch {
        return String(value ?? '');
    }
}

async function loadDetail() {
    const id = orderID.value;
    if (!id || Number.isNaN(id)) return;
    loading.value = true;
    try {
        detail.value = await OrderService.getOrderDetail(id);
    } catch (error) {
        toast.add({ severity: 'error', summary: '加载失败', detail: error?.message || '无法加载订单详情', life: 4000 });
    } finally {
        loading.value = false;
    }
}

function openRefundDialog() {
    refundDialogVisible.value = true;
    refundForce.value = false;
    refundReason.value = '';
}

async function confirmRefund() {
    const id = orderID.value;
    if (!id) return;
    refundLoading.value = true;
    try {
        await OrderService.refundOrder(id, { force: refundForce.value, reason: refundReason.value });
        toast.add({ severity: 'success', summary: '已提交退款', detail: `订单ID: ${id}`, life: 3000 });
        refundDialogVisible.value = false;
        await loadDetail();
    } catch (error) {
        toast.add({ severity: 'error', summary: '退款失败', detail: error?.message || '无法发起退款', life: 4000 });
    } finally {
        refundLoading.value = false;
    }
}

watch(
    () => orderID.value,
    () => loadDetail(),
    { immediate: true }
);
</script>

<template>
    <div class="card">
        <div class="flex items-center justify-between mb-4">
            <div class="flex flex-col">
                <h4 class="m-0">订单详情</h4>
                <span class="text-muted-color">OrderID: {{ orderID || '-' }}</span>
            </div>
            <div class="flex items-center gap-2">
                <Button label="退款" icon="pi pi-replay" severity="danger" @click="openRefundDialog" :disabled="detail?.order?.status !== 'paid' || loading" />
            </div>
        </div>

        <div v-if="loading" class="flex items-center justify-center py-10">
            <ProgressSpinner style="width: 36px; height: 36px" strokeWidth="6" />
        </div>

        <div v-else class="flex flex-col gap-4">
            <div class="grid grid-cols-12 gap-3">
                <div class="col-span-12 md:col-span-6">
                    <div class="text-sm text-muted-color">租户</div>
                    <div class="font-medium">{{ detail?.tenant?.name ?? '-' }}</div>
                    <div class="text-sm text-muted-color">{{ detail?.tenant?.code ?? '-' }} / {{ detail?.tenant?.id ?? '-' }}</div>
                </div>
                <div class="col-span-12 md:col-span-6">
                    <div class="text-sm text-muted-color">买家</div>
                    <div class="font-medium">{{ detail?.buyer?.username ?? '-' }}</div>
                    <div class="text-sm text-muted-color">ID: {{ detail?.buyer?.id ?? '-' }}</div>
                </div>
                <div class="col-span-12 md:col-span-3">
                    <div class="text-sm text-muted-color">状态</div>
                    <Tag :value="detail?.order?.status_description || detail?.order?.status || '-'" :severity="getOrderStatusSeverity(detail?.order?.status)" />
                </div>
                <div class="col-span-12 md:col-span-3">
                    <div class="text-sm text-muted-color">实付</div>
                    <div class="font-medium">{{ formatCny(detail?.order?.amount_paid) }}</div>
                </div>
                <div class="col-span-12 md:col-span-3">
                    <div class="text-sm text-muted-color">创建时间</div>
                    <div class="font-medium">{{ formatDate(detail?.order?.created_at) }}</div>
                </div>
                <div class="col-span-12 md:col-span-3">
                    <div class="text-sm text-muted-color">支付时间</div>
                    <div class="font-medium">{{ formatDate(detail?.order?.paid_at) }}</div>
                </div>
            </div>

            <div class="grid grid-cols-12 gap-3">
                <div class="col-span-12 md:col-span-6">
                    <div class="text-sm text-muted-color mb-2">订单快照（snapshot）</div>
                    <pre class="text-xs whitespace-pre-wrap bg-surface-50 border border-surface-200 rounded-md p-3 max-h-[420px] overflow-auto">{{ safeJson(detail?.order?.snapshot) }}</pre>
                </div>
                <div class="col-span-12 md:col-span-6">
                    <div class="text-sm text-muted-color mb-2">订单明细（items）</div>
                    <DataTable :value="detail?.order?.items || []" dataKey="id" responsiveLayout="scroll" scrollable scrollHeight="420px">
                        <Column field="id" header="ItemID" style="min-width: 7rem" />
                        <Column field="content_id" header="ContentID" style="min-width: 8rem" />
                        <Column field="amount_paid" header="金额" style="min-width: 10rem">
                            <template #body="{ data }">
                                {{ formatCny(data.amount_paid) }}
                            </template>
                        </Column>
                        <Column field="snapshot" header="内容快照" style="min-width: 24rem">
                            <template #body="{ data }">
                                <pre class="text-xs whitespace-pre-wrap bg-surface-50 border border-surface-200 rounded-md p-2 max-h-[220px] overflow-auto">{{ safeJson(data.snapshot) }}</pre>
                            </template>
                        </Column>
                    </DataTable>
                </div>
            </div>
        </div>
    </div>

    <Dialog v-model:visible="refundDialogVisible" :modal="true" :style="{ width: '520px' }">
        <template #header>
            <div class="flex items-center gap-2">
                <span class="font-medium">发起退款</span>
                <span class="text-muted-color truncate max-w-[280px]">{{ orderID ? `#${orderID}` : '' }}</span>
            </div>
        </template>
        <div class="flex flex-col gap-4">
            <div class="text-sm text-muted-color">该操作会将订单从 <span class="font-medium">paid</span> 推进到 <span class="font-medium">refunding</span> 并提交异步退款任务。</div>
            <div class="flex items-center gap-2">
                <Checkbox v-model="refundForce" inputId="refundForce" binary />
                <label for="refundForce" class="cursor-pointer">强制退款（绕过默认时间窗）</label>
            </div>
            <div>
                <label class="block font-medium mb-2">退款原因</label>
                <InputText v-model="refundReason" placeholder="可选，用于审计" class="w-full" />
            </div>
        </div>
        <template #footer>
            <Button label="取消" icon="pi pi-times" text @click="refundDialogVisible = false" :disabled="refundLoading" />
            <Button label="确认退款" icon="pi pi-check" severity="danger" @click="confirmRefund" :loading="refundLoading" :disabled="detail?.order?.status !== 'paid'" />
        </template>
    </Dialog>
</template>
