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

const toast = useToast();

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

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

const tenantID = ref(null);
const ownerUserID = ref(null);
const nameKeyword = ref('');
const codeKeyword = ref('');
const status = ref('');
const createdAtFrom = ref(null);
const createdAtTo = ref(null);
const sortField = ref('id');
const sortOrder = ref(-1);

const statusDialogVisible = ref(false);
const statusOptionsLoading = ref(false);
const statusOptions = ref([]);
const statusUpdating = ref(false);
const statusTenant = ref(null);
const statusValue = ref(null);

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

async function ensureStatusOptionsLoaded() {
    if (statusOptions.value.length > 0) return;
    statusOptionsLoading.value = true;
    try {
        const list = await TenantService.getTenantStatuses();
        statusOptions.value = (list || [])
            .map((kv) => ({
                label: kv?.value ?? kv?.key ?? '-',
                value: kv?.key ?? ''
            }))
            .filter((item) => item.value);
    } finally {
        statusOptionsLoading.value = false;
    }
}

async function loadCreators() {
    loading.value = true;
    try {
        const result = await CreatorService.listCreators({
            page: page.value,
            limit: rows.value,
            id: tenantID.value || undefined,
            user_id: ownerUserID.value || undefined,
            name: nameKeyword.value,
            code: codeKeyword.value,
            status: status.value,
            created_at_from: createdAtFrom.value || undefined,
            created_at_to: createdAtTo.value || undefined,
            sortField: sortField.value,
            sortOrder: sortOrder.value
        });
        creators.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;
    loadCreators();
}

function onReset() {
    tenantID.value = null;
    ownerUserID.value = null;
    nameKeyword.value = '';
    codeKeyword.value = '';
    status.value = '';
    createdAtFrom.value = null;
    createdAtTo.value = null;
    sortField.value = 'id';
    sortOrder.value = -1;
    page.value = 1;
    rows.value = 10;
    loadCreators();
}

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

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

async function openStatusDialog(tenant) {
    statusTenant.value = tenant;
    statusValue.value = tenant?.status ?? null;
    statusDialogVisible.value = true;
    try {
        await ensureStatusOptionsLoaded();
    } catch (error) {
        toast.add({ severity: 'error', summary: '加载失败', detail: error?.message || '无法加载状态选项', life: 4000 });
    }
}

async function confirmUpdateStatus() {
    const id = statusTenant.value?.id;
    if (!id || !statusValue.value) return;

    statusUpdating.value = true;
    try {
        await TenantService.updateTenantStatus({ tenantID: id, status: statusValue.value });
        toast.add({ severity: 'success', summary: '更新成功', detail: `TenantID: ${id}`, life: 3000 });
        statusDialogVisible.value = false;
        await loadCreators();
    } catch (error) {
        toast.add({ severity: 'error', summary: '更新失败', detail: error?.message || '无法更新状态', life: 4000 });
    } finally {
        statusUpdating.value = false;
    }
}

onMounted(() => {
    loadCreators();
    ensureStatusOptionsLoaded().catch(() => {});
});
</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="TenantID">
                <InputNumber v-model="tenantID" :min="1" placeholder="精确匹配" class="w-full" />
            </SearchField>
            <SearchField label="Owner UserID">
                <InputNumber v-model="ownerUserID" :min="1" placeholder="精确匹配" class="w-full" />
            </SearchField>
            <SearchField label="名称">
                <IconField>
                    <InputIcon>
                        <i class="pi pi-search" />
                    </InputIcon>
                    <InputText v-model="nameKeyword" placeholder="模糊匹配" class="w-full" @keyup.enter="onSearch" />
                </IconField>
            </SearchField>
            <SearchField label="Code">
                <IconField>
                    <InputIcon>
                        <i class="pi pi-search" />
                    </InputIcon>
                    <InputText v-model="codeKeyword" placeholder="模糊匹配" class="w-full" @keyup.enter="onSearch" />
                </IconField>
            </SearchField>
            <SearchField label="状态">
                <Select v-model="status" :options="statusOptions" optionLabel="label" optionValue="value" placeholder="请选择" :loading="statusOptionsLoading" 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="creators"
            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 field="code" header="Code" style="min-width: 10rem" />
            <Column field="name" header="名称" sortable style="min-width: 16rem">
                <template #body="{ data }">
                    <Button :label="data.name || '-'" icon="pi pi-external-link" text size="small" class="p-0" as="router-link" :to="`/superadmin/tenants/${data.id}`" />
                </template>
            </Column>
            <Column field="owner.username" header="Owner" style="min-width: 12rem">
                <template #body="{ data }">
                    <span v-if="data.owner?.username">{{ data.owner.username }}</span>
                    <span v-else class="text-muted-color">{{ data.user_id ?? '-' }}</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)" class="cursor-pointer" @click="openStatusDialog(data)" />
                </template>
            </Column>
            <Column field="user_count" header="成员数" style="min-width: 8rem" />
            <Column field="created_at" header="创建时间" sortable style="min-width: 14rem">
                <template #body="{ data }">
                    {{ formatDate(data.created_at) }}
                </template>
            </Column>
        </DataTable>
    </div>

    <Dialog v-model:visible="statusDialogVisible" :modal="true" :style="{ width: '420px' }">
        <template #header>
            <div class="flex items-center gap-2">
                <span class="font-medium">更新创作者状态</span>
                <span class="text-muted-color truncate max-w-[240px]">{{ statusTenant?.name ?? '-' }}</span>
            </div>
        </template>
        <div class="flex flex-col gap-4">
            <div>
                <label class="block font-medium mb-2">状态</label>
                <Select v-model="statusValue" :options="statusOptions" optionLabel="label" optionValue="value" placeholder="选择状态" :disabled="statusUpdating" :loading="statusOptionsLoading" fluid />
            </div>
        </div>
        <template #footer>
            <Button label="取消" icon="pi pi-times" text @click="statusDialogVisible = false" :disabled="statusUpdating" />
            <Button label="确认" icon="pi pi-check" @click="confirmUpdateStatus" :loading="statusUpdating" :disabled="!statusValue" />
        </template>
    </Dialog>
</template>
