<script setup>
import SearchField from '@/components/SearchField.vue';
import SearchPanel from '@/components/SearchPanel.vue';
import { TenantService } from '@/service/TenantService';
import { UserService } from '@/service/UserService';
import { useToast } from 'primevue/usetoast';
import { computed, onMounted, ref, watch } from 'vue';
import { useRoute } from 'vue-router';

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

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

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

const tabValue = ref('owned');

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

function hasRole(role) {
    const roles = user.value?.roles || [];
    return Array.isArray(roles) && roles.includes(role);
}

async function loadUser() {
    const id = userID.value;
    if (!id || Number.isNaN(id)) return;
    loading.value = true;
    try {
        user.value = await UserService.getUserDetail(id);
    } catch (error) {
        toast.add({ severity: 'error', summary: '加载失败', detail: error?.message || '无法加载用户详情', life: 4000 });
    } finally {
        loading.value = false;
    }
}

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

const statusFilterOptions = computed(() => [{ label: '全部', value: '' }, ...(statusOptions.value || [])]);

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

async function openStatusDialog() {
    statusValue.value = user.value?.status ?? null;
    statusDialogVisible.value = true;
    await ensureStatusOptionsLoaded();
}

async function confirmUpdateStatus() {
    const id = userID.value;
    if (!id || !statusValue.value) return;
    statusLoading.value = true;
    try {
        await UserService.updateUserStatus({ userID: id, status: statusValue.value });
        toast.add({ severity: 'success', summary: '更新成功', detail: `用户ID: ${id}`, life: 3000 });
        statusDialogVisible.value = false;
        await loadUser();
    } catch (error) {
        toast.add({ severity: 'error', summary: '更新失败', detail: error?.message || '无法更新用户状态', life: 4000 });
    } finally {
        statusLoading.value = false;
    }
}

const rolesDialogVisible = ref(false);
const rolesLoading = ref(false);
const rolesSuperAdmin = ref(false);

function openRolesDialog() {
    rolesSuperAdmin.value = hasRole('super_admin');
    rolesDialogVisible.value = true;
}

async function confirmUpdateRoles() {
    const id = userID.value;
    if (!id) return;

    const roles = ['user'];
    if (rolesSuperAdmin.value) roles.push('super_admin');

    rolesLoading.value = true;
    try {
        await UserService.updateUserRoles({ userID: id, roles });
        toast.add({ severity: 'success', summary: '更新成功', detail: `用户ID: ${id}`, life: 3000 });
        rolesDialogVisible.value = false;
        await loadUser();
    } catch (error) {
        toast.add({ severity: 'error', summary: '更新失败', detail: error?.message || '无法更新用户角色', life: 4000 });
    } finally {
        rolesLoading.value = false;
    }
}

const ownedTenantsLoading = ref(false);
const ownedTenants = ref([]);
const ownedTenantsTotal = ref(0);
const ownedTenantsPage = ref(1);
const ownedTenantsRows = ref(10);

async function loadOwnedTenants() {
    const uid = userID.value;
    if (!uid) return;
    ownedTenantsLoading.value = true;
    try {
        const result = await TenantService.listTenants({
            page: ownedTenantsPage.value,
            limit: ownedTenantsRows.value,
            user_id: uid,
            sortField: 'id',
            sortOrder: -1
        });
        ownedTenants.value = result.items;
        ownedTenantsTotal.value = result.total;
    } catch (error) {
        toast.add({ severity: 'error', summary: '加载失败', detail: error?.message || '无法加载该用户拥有的租户', life: 4000 });
    } finally {
        ownedTenantsLoading.value = false;
    }
}

function onOwnedTenantsPage(event) {
    ownedTenantsPage.value = (event.page ?? 0) + 1;
    ownedTenantsRows.value = event.rows ?? ownedTenantsRows.value;
    loadOwnedTenants();
}

const joinedTenantsLoading = ref(false);
const joinedTenants = ref([]);
const joinedTenantsTotal = ref(0);
const joinedTenantsPage = ref(1);
const joinedTenantsRows = ref(10);
const joinedTenantsTenantID = ref(null);
const joinedTenantsCode = ref('');
const joinedTenantsName = ref('');
const joinedTenantsRole = ref('');
const joinedTenantsStatus = ref('');
const joinedTenantsJoinedAtFrom = ref(null);
const joinedTenantsJoinedAtTo = ref(null);

async function loadJoinedTenants() {
    const uid = userID.value;
    if (!uid) return;

    joinedTenantsLoading.value = true;
    try {
        const result = await UserService.listUserTenants(uid, {
            page: joinedTenantsPage.value,
            limit: joinedTenantsRows.value,
            tenant_id: joinedTenantsTenantID.value || undefined,
            code: joinedTenantsCode.value,
            name: joinedTenantsName.value,
            role: joinedTenantsRole.value || undefined,
            status: joinedTenantsStatus.value || undefined,
            created_at_from: joinedTenantsJoinedAtFrom.value || undefined,
            created_at_to: joinedTenantsJoinedAtTo.value || undefined
        });
        joinedTenants.value = result.items;
        joinedTenantsTotal.value = result.total;
    } catch (error) {
        toast.add({ severity: 'error', summary: '加载失败', detail: error?.message || '无法加载该用户加入的租户', life: 4000 });
    } finally {
        joinedTenantsLoading.value = false;
    }
}

function onJoinedTenantsSearch() {
    joinedTenantsPage.value = 1;
    loadJoinedTenants();
}

function onJoinedTenantsReset() {
    joinedTenantsTenantID.value = null;
    joinedTenantsCode.value = '';
    joinedTenantsName.value = '';
    joinedTenantsRole.value = '';
    joinedTenantsStatus.value = '';
    joinedTenantsJoinedAtFrom.value = null;
    joinedTenantsJoinedAtTo.value = null;
    joinedTenantsPage.value = 1;
    joinedTenantsRows.value = 10;
    loadJoinedTenants();
}

function onJoinedTenantsPage(event) {
    joinedTenantsPage.value = (event.page ?? 0) + 1;
    joinedTenantsRows.value = event.rows ?? joinedTenantsRows.value;
    loadJoinedTenants();
}

watch(
    () => userID.value,
    () => {
        ownedTenantsPage.value = 1;
        joinedTenantsPage.value = 1;
        loadUser();
        loadOwnedTenants();
        loadJoinedTenants();
    },
    { immediate: true }
);

onMounted(() => {
    ensureStatusOptionsLoaded().catch(() => {});
});
</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">UserID: {{ userID || '-' }}</span>
            </div>
            <div class="flex items-center gap-2">
                <Button label="角色" icon="pi pi-user-edit" severity="secondary" @click="openRolesDialog" :disabled="loading" />
                <Button label="状态" icon="pi pi-tag" @click="openStatusDialog" :disabled="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="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">{{ user?.username ?? '-' }}</div>
                <div class="text-sm text-muted-color">Roles: {{ (user?.roles || []).join(', ') || '-' }}</div>
            </div>
            <div class="col-span-12 md:col-span-6">
                <div class="text-sm text-muted-color">状态</div>
                <Tag :value="user?.status_description || user?.status || '-'" :severity="getStatusSeverity(user?.status)" />
            </div>
            <div class="col-span-12 md:col-span-4">
                <div class="text-sm text-muted-color">余额</div>
                <div class="font-medium">{{ formatCny(user?.balance) }}</div>
            </div>
            <div class="col-span-12 md:col-span-4">
                <div class="text-sm text-muted-color">冻结</div>
                <div class="font-medium">{{ formatCny(user?.balance_frozen) }}</div>
            </div>
            <div class="col-span-12 md:col-span-4">
                <div class="text-sm text-muted-color">超管</div>
                <div class="font-medium">{{ hasRole('super_admin') ? '是' : '否' }}</div>
            </div>
            <div class="col-span-12 md:col-span-4">
                <div class="text-sm text-muted-color">认证时间</div>
                <div class="font-medium">{{ formatDate(user?.verified_at) }}</div>
            </div>
            <div class="col-span-12 md:col-span-4">
                <div class="text-sm text-muted-color">创建时间</div>
                <div class="font-medium">{{ formatDate(user?.created_at) }}</div>
            </div>
            <div class="col-span-12 md:col-span-4">
                <div class="text-sm text-muted-color">更新时间</div>
                <div class="font-medium">{{ formatDate(user?.updated_at) }}</div>
            </div>
        </div>
    </div>

    <div class="card">
        <Tabs v-model:value="tabValue" value="owned">
            <TabList>
                <Tab value="owned">拥有的租户</Tab>
                <Tab value="joined">加入的租户</Tab>
            </TabList>
            <TabPanels>
                <TabPanel value="owned">
                    <div class="flex flex-col gap-4">
                        <div class="flex items-center justify-between">
                            <span class="text-muted-color">共 {{ ownedTenantsTotal }} 条</span>
                        </div>
                        <DataTable
                            :value="ownedTenants"
                            dataKey="id"
                            :loading="ownedTenantsLoading"
                            lazy
                            :paginator="true"
                            :rows="ownedTenantsRows"
                            :totalRecords="ownedTenantsTotal"
                            :first="(ownedTenantsPage - 1) * ownedTenantsRows"
                            :rowsPerPageOptions="[10, 20, 50, 100]"
                            @page="onOwnedTenantsPage"
                            currentPageReportTemplate="显示第 {first} - {last} 条，共 {totalRecords} 条"
                            paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
                            scrollable
                            scrollHeight="420px"
                            responsiveLayout="scroll"
                        >
                            <Column field="id" header="ID" style="min-width: 6rem" />
                            <Column field="code" header="Code" style="min-width: 10rem" />
                            <Column field="name" header="名称" style="min-width: 14rem">
                                <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="status_description" header="状态" style="min-width: 10rem" />
                            <Column field="user_count" header="用户数" style="min-width: 8rem" />
                            <Column field="income_amount_paid_sum" header="累计收入" style="min-width: 10rem">
                                <template #body="{ data }">
                                    {{ formatCny(data.income_amount_paid_sum) }}
                                </template>
                            </Column>
                            <Column field="expired_at" header="过期时间" style="min-width: 14rem">
                                <template #body="{ data }">
                                    {{ formatDate(data.expired_at) }}
                                </template>
                            </Column>
                        </DataTable>
                    </div>
                </TabPanel>
                <TabPanel value="joined">
                    <div class="flex flex-col gap-4">
                        <div class="flex items-center justify-between">
                            <span class="text-muted-color">共 {{ joinedTenantsTotal }} 条</span>
                        </div>

                        <SearchPanel :loading="joinedTenantsLoading" @search="onJoinedTenantsSearch" @reset="onJoinedTenantsReset">
                            <SearchField label="TenantID">
                                <InputNumber v-model="joinedTenantsTenantID" :min="1" placeholder="精确匹配" class="w-full" />
                            </SearchField>
                            <SearchField label="Code">
                                <InputText v-model="joinedTenantsCode" placeholder="请输入" class="w-full" @keyup.enter="onJoinedTenantsSearch" />
                            </SearchField>
                            <SearchField label="名称">
                                <InputText v-model="joinedTenantsName" placeholder="请输入" class="w-full" @keyup.enter="onJoinedTenantsSearch" />
                            </SearchField>
                            <SearchField label="成员角色">
                                <Select
                                    v-model="joinedTenantsRole"
                                    :options="[
                                        { label: '全部', value: '' },
                                        { label: 'tenant_admin', value: 'tenant_admin' },
                                        { label: 'member', value: 'member' }
                                    ]"
                                    optionLabel="label"
                                    optionValue="value"
                                    placeholder="请选择"
                                    class="w-full"
                                />
                            </SearchField>
                            <SearchField label="成员状态">
                                <Select v-model="joinedTenantsStatus" :options="statusFilterOptions" optionLabel="label" optionValue="value" placeholder="请选择" :loading="statusOptionsLoading" class="w-full" />
                            </SearchField>
                            <SearchField label="加入时间 From">
                                <DatePicker v-model="joinedTenantsJoinedAtFrom" showIcon showButtonBar placeholder="开始时间" class="w-full" />
                            </SearchField>
                            <SearchField label="加入时间 To">
                                <DatePicker v-model="joinedTenantsJoinedAtTo" showIcon showButtonBar placeholder="结束时间" class="w-full" />
                            </SearchField>
                        </SearchPanel>

                        <DataTable
                            :value="joinedTenants"
                            dataKey="tenant_id"
                            :loading="joinedTenantsLoading"
                            lazy
                            :paginator="true"
                            :rows="joinedTenantsRows"
                            :totalRecords="joinedTenantsTotal"
                            :first="(joinedTenantsPage - 1) * joinedTenantsRows"
                            :rowsPerPageOptions="[10, 20, 50, 100]"
                            @page="onJoinedTenantsPage"
                            currentPageReportTemplate="显示第 {first} - {last} 条，共 {totalRecords} 条"
                            paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
                            scrollable
                            scrollHeight="420px"
                            responsiveLayout="scroll"
                        >
                            <Column field="tenant_id" header="TenantID" style="min-width: 7rem" />
                            <Column field="code" header="Code" style="min-width: 10rem" />
                            <Column field="name" header="名称" style="min-width: 14rem">
                                <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.tenant_id}`" />
                                </template>
                            </Column>
                            <Column header="Owner" style="min-width: 12rem">
                                <template #body="{ data }">
                                    <span>{{ data?.owner?.username ?? '-' }}</span>
                                </template>
                            </Column>
                            <Column header="租户状态" style="min-width: 12rem">
                                <template #body="{ data }">
                                    <Tag :value="data.tenant_status_description || data.tenant_status || '-'" severity="secondary" />
                                </template>
                            </Column>
                            <Column header="成员角色" style="min-width: 14rem">
                                <template #body="{ data }">
                                    <div class="flex flex-wrap gap-1">
                                        <Tag v-for="r in data.role || []" :key="r" :value="r" severity="secondary" />
                                        <span v-if="!data.role || data.role.length === 0" class="text-muted-color">-</span>
                                    </div>
                                </template>
                            </Column>
                            <Column header="成员状态" style="min-width: 10rem">
                                <template #body="{ data }">
                                    <Tag :value="data.member_status_description || data.member_status || '-'" :severity="getStatusSeverity(data.member_status)" />
                                </template>
                            </Column>
                            <Column field="joined_at" header="加入时间" style="min-width: 14rem">
                                <template #body="{ data }">
                                    {{ formatDate(data.joined_at) }}
                                </template>
                            </Column>
                            <Column field="expired_at" header="过期时间" style="min-width: 14rem">
                                <template #body="{ data }">
                                    {{ formatDate(data.expired_at) }}
                                </template>
                            </Column>
                        </DataTable>
                    </div>
                </TabPanel>
            </TabPanels>
        </Tabs>
    </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]">{{ user?.username ?? '-' }}</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="statusLoading" :loading="statusOptionsLoading" fluid />
            </div>
        </div>
        <template #footer>
            <Button label="取消" icon="pi pi-times" text @click="statusDialogVisible = false" :disabled="statusLoading" />
            <Button label="确认" icon="pi pi-check" @click="confirmUpdateStatus" :loading="statusLoading" :disabled="!statusValue" />
        </template>
    </Dialog>

    <Dialog v-model:visible="rolesDialogVisible" :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]">{{ user?.username ?? '-' }}</span>
            </div>
        </template>
        <div class="flex flex-col gap-4">
            <div class="flex items-center gap-2">
                <Checkbox inputId="rolesSuperAdmin" v-model="rolesSuperAdmin" binary :disabled="rolesLoading" />
                <label for="rolesSuperAdmin" class="cursor-pointer">super_admin</label>
            </div>
            <div class="text-sm text-muted-color">默认包含 user 角色。</div>
        </div>
        <template #footer>
            <Button label="取消" icon="pi pi-times" text @click="rolesDialogVisible = false" :disabled="rolesLoading" />
            <Button label="确认" icon="pi pi-check" @click="confirmUpdateRoles" :loading="rolesLoading" />
        </template>
    </Dialog>
</template>
