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

const toast = useToast();

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

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

const couponID = ref(null);
const tenantID = ref(null);
const tenantCode = ref('');
const tenantName = ref('');
const keyword = ref('');
const type = ref('');
const status = ref('');
const createdAtFrom = ref(null);
const createdAtTo = ref(null);
const sortField = ref('created_at');
const sortOrder = ref(-1);

const typeOptions = [
    { label: '全部', value: '' },
    { label: '固定金额', value: 'fix_amount' },
    { label: '折扣', value: 'discount' }
];

const statusOptions = [
    { label: '全部', value: '' },
    { label: '生效中', value: 'active' },
    { label: '未开始', value: 'upcoming' },
    { label: '已过期', value: 'expired' }
];

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 getStatusSeverity(value) {
    switch (value) {
        case 'active':
            return 'success';
        case 'upcoming':
            return 'warn';
        case 'expired':
            return 'danger';
        default:
            return 'secondary';
    }
}

async function loadCoupons() {
    loading.value = true;
    try {
        const result = await CouponService.listCoupons({
            page: page.value,
            limit: rows.value,
            id: couponID.value || undefined,
            tenant_id: tenantID.value || undefined,
            tenant_code: tenantCode.value,
            tenant_name: tenantName.value,
            keyword: keyword.value,
            type: type.value,
            status: status.value,
            created_at_from: createdAtFrom.value || undefined,
            created_at_to: createdAtTo.value || undefined,
            sortField: sortField.value,
            sortOrder: sortOrder.value
        });
        coupons.value = result.items;
        totalRecords.value = result.total;
    } catch (error) {
        toast.add({ severity: 'error', summary: '加载失败', detail: error?.message || '无法加载优惠券列表', life: 4000 });
    } finally {
        loading.value = false;
    }
}

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

function onReset() {
    couponID.value = null;
    tenantID.value = null;
    tenantCode.value = '';
    tenantName.value = '';
    keyword.value = '';
    type.value = '';
    status.value = '';
    createdAtFrom.value = null;
    createdAtTo.value = null;
    sortField.value = 'created_at';
    sortOrder.value = -1;
    page.value = 1;
    rows.value = 10;
    loadCoupons();
}

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

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

onMounted(() => {
    loadCoupons();
});
</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="CouponID">
                <InputNumber v-model="couponID" :min="1" placeholder="精确匹配" class="w-full" />
            </SearchField>
            <SearchField label="TenantID">
                <InputNumber v-model="tenantID" :min="1" placeholder="精确匹配" class="w-full" />
            </SearchField>
            <SearchField label="Tenant Code">
                <InputText v-model="tenantCode" placeholder="模糊匹配" class="w-full" @keyup.enter="onSearch" />
            </SearchField>
            <SearchField label="Tenant Name">
                <InputText v-model="tenantName" placeholder="模糊匹配" class="w-full" @keyup.enter="onSearch" />
            </SearchField>
            <SearchField label="关键词">
                <IconField>
                    <InputIcon>
                        <i class="pi pi-search" />
                    </InputIcon>
                    <InputText v-model="keyword" placeholder="标题/描述" class="w-full" @keyup.enter="onSearch" />
                </IconField>
            </SearchField>
            <SearchField label="类型">
                <Select v-model="type" :options="typeOptions" optionLabel="label" optionValue="value" placeholder="请选择" class="w-full" />
            </SearchField>
            <SearchField label="状态">
                <Select v-model="status" :options="statusOptions" 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>
        </SearchPanel>

        <DataTable
            :value="coupons"
            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: 6rem" />
            <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-xs text-muted-color">Code: {{ data.tenant_code || '-' }}</span>
                    </div>
                </template>
            </Column>
            <Column field="title" header="标题" sortable style="min-width: 16rem" />
            <Column header="类型" style="min-width: 10rem">
                <template #body="{ data }">
                    {{ data.type_description || data.type || '-' }}
                </template>
            </Column>
            <Column field="value" header="面额/折扣" style="min-width: 10rem">
                <template #body="{ data }">
                    <span v-if="data.type === 'discount'">{{ data.value ?? '-' }}%</span>
                    <span v-else>{{ formatCny(data.value) }}</span>
                </template>
            </Column>
            <Column field="min_order_amount" header="门槛" style="min-width: 10rem">
                <template #body="{ data }">
                    {{ formatCny(data.min_order_amount) }}
                </template>
            </Column>
            <Column header="使用情况" style="min-width: 10rem">
                <template #body="{ data }">
                    <span v-if="data.total_quantity === 0">不限量</span>
                    <span v-else>{{ data.used_quantity ?? 0 }} / {{ data.total_quantity ?? 0 }}</span>
                </template>
            </Column>
            <Column field="status" header="状态" style="min-width: 10rem">
                <template #body="{ data }">
                    <Tag :value="data.status_description || data.status || '-'" :severity="getStatusSeverity(data.status)" />
                </template>
            </Column>
            <Column field="start_at" header="开始时间" sortable style="min-width: 14rem">
                <template #body="{ data }">
                    {{ formatDate(data.start_at) }}
                </template>
            </Column>
            <Column field="end_at" header="结束时间" sortable style="min-width: 14rem">
                <template #body="{ data }">
                    {{ formatDate(data.end_at) }}
                </template>
            </Column>
            <Column field="created_at" header="创建时间" sortable style="min-width: 14rem">
                <template #body="{ data }">
                    {{ formatDate(data.created_at) }}
                </template>
            </Column>
        </DataTable>
    </div>
</template>
