<script setup>
import SearchField from '@/components/SearchField.vue';
import SearchPanel from '@/components/SearchPanel.vue';
import { OrderService } from '@/service/OrderService';
import { useToast } from 'primevue/usetoast';
import { ref } from 'vue';

const toast = useToast();

const orders = ref([]);
const loading = ref(false);

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

const totalRecords = ref(0);
const page = ref(1);
const rows = ref(10);

const orderID = ref(null);
const tenantID = ref(null);
const tenantCode = ref('');
const tenantName = ref('');
const buyerUserID = ref(null);
const buyerUsername = ref('');
const contentID = ref(null);
const contentTitle = ref('');
const status = ref('');
const type = ref('');
const createdAtFrom = ref(null);
const createdAtTo = ref(null);
const paidAtFrom = ref(null);
const paidAtTo = ref(null);
const amountPaidMin = ref(null);
const amountPaidMax = ref(null);
const sortField = ref('id');
const sortOrder = ref(-1);

const statusOptions = [
    { label: '全部', value: '' },
    { label: 'created', value: 'created' },
    { label: 'paid', value: 'paid' },
    { label: 'refunding', value: 'refunding' },
    { label: 'refunded', value: 'refunded' },
    { label: 'canceled', value: 'canceled' },
    { label: 'failed', value: 'failed' }
];

const typeOptions = [
    { label: '全部', value: '' },
    { label: 'content_purchase', value: 'content_purchase' }
];

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';
    }
}

async function loadOrders() {
    loading.value = true;
    try {
        const result = await OrderService.listOrders({
            page: page.value,
            limit: rows.value,
            id: orderID.value || undefined,
            tenant_id: tenantID.value || undefined,
            tenant_code: tenantCode.value,
            tenant_name: tenantName.value,
            user_id: buyerUserID.value || undefined,
            username: buyerUsername.value,
            content_id: contentID.value || undefined,
            content_title: contentTitle.value,
            status: status.value,
            type: type.value,
            created_at_from: createdAtFrom.value || undefined,
            created_at_to: createdAtTo.value || undefined,
            paid_at_from: paidAtFrom.value || undefined,
            paid_at_to: paidAtTo.value || undefined,
            amount_paid_min: amountPaidMin.value || undefined,
            amount_paid_max: amountPaidMax.value || undefined,
            sortField: sortField.value,
            sortOrder: sortOrder.value
        });
        orders.value = result.items;
        totalRecords.value = result.total;
    } catch (error) {
        toast.add({ severity: 'error', summary: '加载失败', detail: error?.message || '无法加载订单列表', life: 4000 });
    } finally {
        loading.value = false;
    }
}

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

async function confirmRefund() {
    const id = refundOrder.value?.id;
    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 loadOrders();
    } catch (error) {
        toast.add({ severity: 'error', summary: '退款失败', detail: error?.message || '无法发起退款', life: 4000 });
    } finally {
        refundLoading.value = false;
    }
}

function onSearch() {
    page.value = 1;
    loadOrders();
}

function onReset() {
    orderID.value = null;
    tenantID.value = null;
    tenantCode.value = '';
    tenantName.value = '';
    buyerUserID.value = null;
    buyerUsername.value = '';
    contentID.value = null;
    contentTitle.value = '';
    status.value = '';
    type.value = '';
    createdAtFrom.value = null;
    createdAtTo.value = null;
    paidAtFrom.value = null;
    paidAtTo.value = null;
    amountPaidMin.value = null;
    amountPaidMax.value = null;
    sortField.value = 'id';
    sortOrder.value = -1;
    page.value = 1;
    rows.value = 10;
    loadOrders();
}

function onPage(event) {
    page.value = (event.page ?? 0) + 1;
    rows.value = event.rows ?? rows.value;
    loadOrders();
}

function onSort(event) {
    sortField.value = event.sortField ?? sortField.value;
    sortOrder.value = event.sortOrder ?? sortOrder.value;
    loadOrders();
}

loadOrders();
</script>

<template>
    <div class="card">
        <div class="flex items-center justify-between mb-4">
            <h4 class="m-0">订单列表</h4>
        </div>

        <SearchPanel :loading="loading" @search="onSearch" @reset="onReset">
            <SearchField label="OrderID">
                <InputNumber v-model="orderID" :min="1" placeholder="精确匹配" class="w-full" />
            </SearchField>
            <SearchField label="TenantID">
                <InputNumber v-model="tenantID" :min="1" placeholder="精确匹配" class="w-full" />
            </SearchField>
            <SearchField label="TenantCode">
                <InputText v-model="tenantCode" placeholder="请输入" class="w-full" @keyup.enter="onSearch" />
            </SearchField>
            <SearchField label="TenantName">
                <InputText v-model="tenantName" placeholder="请输入" class="w-full" @keyup.enter="onSearch" />
            </SearchField>
            <SearchField label="BuyerUserID">
                <InputNumber v-model="buyerUserID" :min="1" placeholder="精确匹配" class="w-full" />
            </SearchField>
            <SearchField label="BuyerUsername">
                <IconField>
                    <InputIcon>
                        <i class="pi pi-search" />
                    </InputIcon>
                    <InputText v-model="buyerUsername" placeholder="请输入" class="w-full" @keyup.enter="onSearch" />
                </IconField>
            </SearchField>
            <SearchField label="ContentID">
                <InputNumber v-model="contentID" :min="1" placeholder="精确匹配" class="w-full" />
            </SearchField>
            <SearchField label="ContentTitle">
                <InputText v-model="contentTitle" placeholder="请输入" class="w-full" @keyup.enter="onSearch" />
            </SearchField>
            <SearchField label="状态">
                <Select v-model="status" :options="statusOptions" optionLabel="label" optionValue="value" placeholder="请选择" class="w-full" />
            </SearchField>
            <SearchField label="类型">
                <Select v-model="type" :options="typeOptions" optionLabel="label" optionValue="value" placeholder="请选择" class="w-full" />
            </SearchField>
            <SearchField label="创建时间 From">
                <DatePicker v-model="createdAtFrom" showIcon showButtonBar placeholder="开始时间" class="w-full" />
            </SearchField>
            <SearchField label="创建时间 To">
                <DatePicker v-model="createdAtTo" showIcon showButtonBar placeholder="结束时间" class="w-full" />
            </SearchField>
            <SearchField label="支付时间 From">
                <DatePicker v-model="paidAtFrom" showIcon showButtonBar placeholder="开始时间" class="w-full" />
            </SearchField>
            <SearchField label="支付时间 To">
                <DatePicker v-model="paidAtTo" showIcon showButtonBar placeholder="结束时间" class="w-full" />
            </SearchField>
            <SearchField label="实付金额 Min(分)">
                <InputNumber v-model="amountPaidMin" :min="0" placeholder=">= 0" class="w-full" />
            </SearchField>
            <SearchField label="实付金额 Max(分)">
                <InputNumber v-model="amountPaidMax" :min="0" placeholder=">= 0" class="w-full" />
            </SearchField>
        </SearchPanel>

        <DataTable
            :value="orders"
            dataKey="id"
            :loading="loading"
            lazy
            :paginator="true"
            :rows="rows"
            :totalRecords="totalRecords"
            :first="(page - 1) * rows"
            :rowsPerPageOptions="[10, 20, 50, 100]"
            sortMode="single"
            :sortField="sortField"
            :sortOrder="sortOrder"
            @page="onPage"
            @sort="onSort"
            currentPageReportTemplate="显示第 {first} - {last} 条，共 {totalRecords} 条"
            paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
            scrollable
            scrollHeight="flex"
            responsiveLayout="scroll"
        >
            <Column field="id" header="ID" sortable style="min-width: 8rem">
                <template #body="{ data }">
                    <Button label="详情" icon="pi pi-search" text size="small" class="p-0 mr-2" as="router-link" :to="`/superadmin/orders/${data.id}`" />
                    <span class="text-muted-color">{{ data.id }}</span>
                </template>
            </Column>
            <Column header="租户" style="min-width: 16rem">
                <template #body="{ data }">
                    <div class="flex flex-col">
                        <span class="font-medium">{{ data?.tenant?.name ?? '-' }}</span>
                        <span class="text-muted-color">{{ data?.tenant?.code ?? '-' }} / {{ data?.tenant?.id ?? '-' }}</span>
                    </div>
                </template>
            </Column>
            <Column header="买家" style="min-width: 14rem">
                <template #body="{ data }">
                    <div class="flex flex-col">
                        <span class="font-medium">{{ data?.buyer?.username ?? '-' }}</span>
                        <span class="text-muted-color">ID: {{ data?.buyer?.id ?? '-' }}</span>
                    </div>
                </template>
            </Column>
            <Column field="type" header="类型" style="min-width: 12rem" />
            <Column field="status" header="状态" sortable style="min-width: 12rem">
                <template #body="{ data }">
                    <Tag :value="data?.status_description || data?.status || '-'" :severity="getOrderStatusSeverity(data?.status)" />
                </template>
            </Column>
            <Column field="amount_paid" header="实付" sortable style="min-width: 10rem">
                <template #body="{ data }">
                    {{ formatCny(data.amount_paid) }}
                </template>
            </Column>
            <Column field="amount_original" header="原价" style="min-width: 10rem">
                <template #body="{ data }">
                    {{ formatCny(data.amount_original) }}
                </template>
            </Column>
            <Column field="amount_discount" header="优惠" style="min-width: 10rem">
                <template #body="{ data }">
                    {{ formatCny(data.amount_discount) }}
                </template>
            </Column>
            <Column field="created_at" header="创建时间" sortable style="min-width: 14rem">
                <template #body="{ data }">
                    {{ formatDate(data.created_at) }}
                </template>
            </Column>
            <Column field="paid_at" header="支付时间" sortable style="min-width: 14rem">
                <template #body="{ data }">
                    {{ formatDate(data.paid_at) }}
                </template>
            </Column>
            <Column field="refunded_at" header="退款完成" style="min-width: 14rem">
                <template #body="{ data }">
                    {{ formatDate(data.refunded_at) }}
                </template>
            </Column>
            <Column header="操作" style="min-width: 10rem">
                <template #body="{ data }">
                    <Button label="退款" icon="pi pi-replay" text size="small" class="p-0" :disabled="data?.status !== 'paid'" @click="openRefundDialog(data)" />
                </template>
            </Column>
        </DataTable>
    </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]">
                    {{ refundOrder?.id ? `#${refundOrder.id}` : '' }}
                </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="refundOrder?.status !== 'paid'" />
        </template>
    </Dialog>
</template>
