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

const toast = useToast();

const loading = ref(false);
const contents = ref([]);
const totalRecords = ref(0);
const page = ref(1);
const rows = ref(10);

const contentID = ref(null);
const tenantID = ref(null);
const tenantCode = ref('');
const tenantName = ref('');
const ownerUserID = ref(null);
const ownerUsername = ref('');
const keyword = ref('');
const status = ref('');
const visibility = ref('');
const publishedAtFrom = ref(null);
const publishedAtTo = ref(null);
const createdAtFrom = ref(null);
const createdAtTo = ref(null);
const priceAmountMin = ref(null);
const priceAmountMax = ref(null);
const sortField = ref('id');
const sortOrder = ref(-1);

const statusOptions = [
    { label: '全部', value: '' },
    { label: 'draft', value: 'draft' },
    { label: 'reviewing', value: 'reviewing' },
    { label: 'published', value: 'published' },
    { label: 'unpublished', value: 'unpublished' },
    { label: 'blocked', value: 'blocked' }
];

const visibilityOptions = [
    { label: '全部', value: '' },
    { label: 'public', value: 'public' },
    { label: 'tenant_only', value: 'tenant_only' },
    { label: 'private', value: 'private' }
];

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 getContentStatusSeverity(value) {
    switch (value) {
        case 'published':
            return 'success';
        case 'reviewing':
            return 'warn';
        case 'blocked':
            return 'danger';
        case 'draft':
        case 'unpublished':
        default:
            return 'secondary';
    }
}

function getContentVisibilitySeverity(value) {
    switch (value) {
        case 'public':
            return 'info';
        case 'tenant_only':
            return 'warn';
        case 'private':
            return 'secondary';
        default:
            return 'secondary';
    }
}

async function loadContents() {
    loading.value = true;
    try {
        const result = await ContentService.listContents({
            page: page.value,
            limit: rows.value,
            id: contentID.value || undefined,
            tenant_id: tenantID.value || undefined,
            tenant_code: tenantCode.value,
            tenant_name: tenantName.value,
            user_id: ownerUserID.value || undefined,
            username: ownerUsername.value,
            keyword: keyword.value,
            status: status.value || undefined,
            visibility: visibility.value || undefined,
            published_at_from: publishedAtFrom.value || undefined,
            published_at_to: publishedAtTo.value || undefined,
            created_at_from: createdAtFrom.value || undefined,
            created_at_to: createdAtTo.value || undefined,
            price_amount_min: priceAmountMin.value ?? undefined,
            price_amount_max: priceAmountMax.value ?? undefined,
            sortField: sortField.value,
            sortOrder: sortOrder.value
        });
        contents.value = (result.items || []).map((item) => ({ ...item, __key: item?.content?.id ?? undefined }));
        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;
    loadContents();
}

function onReset() {
    contentID.value = null;
    tenantID.value = null;
    tenantCode.value = '';
    tenantName.value = '';
    ownerUserID.value = null;
    ownerUsername.value = '';
    keyword.value = '';
    status.value = '';
    visibility.value = '';
    publishedAtFrom.value = null;
    publishedAtTo.value = null;
    createdAtFrom.value = null;
    createdAtTo.value = null;
    priceAmountMin.value = null;
    priceAmountMax.value = null;
    sortField.value = 'id';
    sortOrder.value = -1;
    page.value = 1;
    rows.value = 10;
    loadContents();
}

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

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

const unpublishDialogVisible = ref(false);
const unpublishLoading = ref(false);
const unpublishItem = ref(null);

const unpublishTenantID = computed(() => Number(unpublishItem.value?.tenant?.id ?? 0));
const unpublishContentID = computed(() => Number(unpublishItem.value?.content?.id ?? 0));

function openUnpublishDialog(row) {
    unpublishItem.value = row;
    unpublishDialogVisible.value = true;
}

async function confirmUnpublish() {
    const teID = unpublishTenantID.value;
    const cID = unpublishContentID.value;
    if (!teID || !cID) return;

    unpublishLoading.value = true;
    try {
        await ContentService.updateTenantContentStatus(teID, cID, { status: 'unpublished' });
        toast.add({ severity: 'success', summary: '下架成功', detail: `ContentID: ${cID}`, life: 3000 });
        unpublishDialogVisible.value = false;
        await loadContents();
    } catch (error) {
        toast.add({ severity: 'error', summary: '下架失败', detail: error?.message || '无法下架内容', life: 4000 });
    } finally {
        unpublishLoading.value = false;
    }
}

onMounted(() => {
    loadContents();
});
</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">平台侧汇总（跨租户）</span>
            </div>
            <Button label="刷新" icon="pi pi-refresh" severity="secondary" @click="loadContents" :disabled="loading" />
        </div>

        <div class="flex flex-col gap-4">
            <SearchPanel :loading="loading" @search="onSearch" @reset="onReset">
                <SearchField label="ContentID">
                    <InputNumber v-model="contentID" :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="OwnerUserID">
                    <InputNumber v-model="ownerUserID" :min="1" placeholder="精确匹配" class="w-full" />
                </SearchField>
                <SearchField label="OwnerUsername">
                    <InputText v-model="ownerUsername" placeholder="模糊匹配" class="w-full" @keyup.enter="onSearch" />
                </SearchField>
                <SearchField label="Keyword">
                    <InputText v-model="keyword" 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="visibility" :options="visibilityOptions" optionLabel="label" optionValue="value" placeholder="请选择" class="w-full" />
                </SearchField>
                <SearchField label="价格 From(分)">
                    <InputNumber v-model="priceAmountMin" :min="0" placeholder=">= 0" class="w-full" />
                </SearchField>
                <SearchField label="价格 To(分)">
                    <InputNumber v-model="priceAmountMax" :min="0" placeholder=">= 0" class="w-full" />
                </SearchField>
                <SearchField label="发布时间 From">
                    <DatePicker v-model="publishedAtFrom" showIcon showButtonBar placeholder="开始时间" class="w-full" />
                </SearchField>
                <SearchField label="发布时间 To">
                    <DatePicker v-model="publishedAtTo" showIcon showButtonBar 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="contents"
                dataKey="__key"
                :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="640px"
                responsiveLayout="scroll"
            >
                <Column header="ID" sortable sortField="id" style="min-width: 8rem">
                    <template #body="{ data }">
                        <span class="text-muted-color">{{ data?.content?.id ?? '-' }}</span>
                    </template>
                </Column>
                <Column header="标题" sortable sortField="title" style="min-width: 22rem">
                    <template #body="{ data }">
                        <div class="flex flex-col">
                            <span class="font-medium truncate max-w-[520px]">{{ data?.content?.title ?? '-' }}</span>
                            <span class="text-muted-color">TenantID: {{ data?.tenant?.id ?? data?.content?.tenant_id ?? '-' }}</span>
                        </div>
                    </template>
                </Column>
                <Column header="租户" sortable sortField="tenant_id" style="min-width: 18rem">
                    <template #body="{ data }">
                        <router-link v-if="data?.tenant?.id" class="inline-flex items-center gap-1 font-medium text-primary hover:underline" :to="`/superadmin/tenants/${data.tenant.id}`">
                            <span class="truncate max-w-[220px]">{{ data?.tenant?.name ?? data?.tenant?.code ?? '-' }}</span>
                            <i class="pi pi-external-link text-xs" />
                        </router-link>
                        <span v-else class="font-medium text-muted-color">{{ data?.tenant?.name ?? data?.tenant?.code ?? '-' }}</span>
                        <div class="flex flex-col">
                            <span class="text-muted-color">ID: {{ data?.tenant?.id ?? data?.content?.tenant_id ?? '-' }}</span>
                            <span class="text-muted-color">Code: {{ data?.tenant?.code ?? '-' }}</span>
                        </div>
                    </template>
                </Column>
                <Column header="Owner" sortable sortField="user_id" style="min-width: 14rem">
                    <template #body="{ data }">
                        <router-link v-if="(data?.owner?.id ?? data?.content?.user_id) > 0" class="inline-flex items-center gap-1 font-medium text-primary hover:underline" :to="`/superadmin/users/${data?.owner?.id ?? data?.content?.user_id}`">
                            <span class="truncate max-w-[200px]">{{ data?.owner?.username ?? `ID:${data?.content?.user_id ?? '-'}` }}</span>
                            <i class="pi pi-external-link text-xs" />
                        </router-link>
                        <span v-else class="font-medium text-muted-color">-</span>
                        <div class="flex flex-col">
                            <span class="text-muted-color">ID: {{ data?.content?.user_id ?? '-' }}</span>
                        </div>
                    </template>
                </Column>
                <Column header="状态" sortable sortField="status" style="min-width: 12rem">
                    <template #body="{ data }">
                        <Tag :value="data?.status_description || data?.content?.status || '-'" :severity="getContentStatusSeverity(data?.content?.status)" />
                    </template>
                </Column>
                <Column header="可见性" sortable sortField="visibility" style="min-width: 12rem">
                    <template #body="{ data }">
                        <Tag :value="data?.visibility_description || data?.content?.visibility || '-'" :severity="getContentVisibilitySeverity(data?.content?.visibility)" />
                    </template>
                </Column>
                <Column header="价格" style="min-width: 10rem">
                    <template #body="{ data }">
                        <span v-if="data?.price && (data.price.price_amount ?? null) !== null">
                            {{ Number(data.price.price_amount) === 0 ? '免费' : formatCny(data.price.price_amount) }}
                        </span>
                        <span v-else class="text-muted-color">-</span>
                    </template>
                </Column>
                <Column header="发布时间" sortable sortField="published_at" style="min-width: 14rem">
                    <template #body="{ data }">
                        {{ formatDate(data?.content?.published_at) }}
                    </template>
                </Column>
                <Column header="创建时间" sortable sortField="created_at" style="min-width: 14rem">
                    <template #body="{ data }">
                        {{ formatDate(data?.content?.created_at) }}
                    </template>
                </Column>
                <Column header="操作" style="min-width: 10rem">
                    <template #body="{ data }">
                        <Button v-if="data?.content?.status === 'published'" label="下架" icon="pi pi-ban" severity="danger" text size="small" class="p-0" @click="openUnpublishDialog(data)" />
                        <span v-else class="text-muted-color">-</span>
                    </template>
                </Column>
            </DataTable>
        </div>
    </div>

    <Dialog v-model:visible="unpublishDialogVisible" :modal="true" :style="{ width: '460px' }">
        <template #header>
            <div class="flex items-center gap-2">
                <span class="font-medium">下架内容</span>
                <span class="text-muted-color truncate max-w-[280px]">{{ unpublishItem?.content?.title ?? '-' }}</span>
            </div>
        </template>
        <div class="flex flex-col gap-2">
            <div class="text-muted-color">确认将该内容下架？下架后租户端将不可见/不可购买。</div>
            <div class="text-sm text-muted-color">ContentID: {{ unpublishItem?.content?.id ?? '-' }}</div>
            <div class="text-sm text-muted-color">TenantID: {{ unpublishItem?.tenant?.id ?? unpublishItem?.content?.tenant_id ?? '-' }}</div>
        </div>
        <template #footer>
            <Button label="取消" icon="pi pi-times" text @click="unpublishDialogVisible = false" :disabled="unpublishLoading" />
            <Button label="确认下架" icon="pi pi-ban" severity="danger" @click="confirmUnpublish" :loading="unpublishLoading" />
        </template>
    </Dialog>
</template>
