<script setup>
import { userService } from '@/api/userService';
import { formatDate } from '@/utils/date';
import Badge from 'primevue/badge';
import Button from 'primevue/button';
import Column from 'primevue/column';
import DataTable from 'primevue/datatable';
import ProgressSpinner from 'primevue/progressspinner';
import { onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();
const loading = ref(false);
const user = ref(null);
const userArticles = ref([]);
const totalArticles = ref(0);
const lazyParams = ref({
    page: 1,
    limit: 10
});

const fetchUserDetail = async () => {
    loading.value = true;
    try {
        const response = await userService.getUserById(route.params.id);
        user.value = response.data;
    } catch (error) {
        console.error('Failed to fetch user details:', error);
    } finally {
        loading.value = false;
    }
};

const fetchUserArticles = async () => {
    try {
        const response = await userService.getUserArticles(
            route.params.id,
            lazyParams.value.page,
            lazyParams.value.limit
        );
        userArticles.value = response.data.items;
        totalArticles.value = response.data.total;
    } catch (error) {
        console.error('Failed to fetch user articles:', error);
    }
};

const handleBack = () => {
    router.push('/users');
};

const onPage = (event) => {
    lazyParams.value = {
        page: event.page + 1,
        limit: event.rows
    };
    fetchUserArticles();
};

onMounted(() => {
    fetchUserDetail();
    fetchUserArticles();
});



const formatPrice = (price) => {
    return (price / 100).toFixed(2);
};
</script>

<template>
    <div class="w-full">
        <div class="flex justify-between items-center mb-6">
            <div class="flex items-center gap-4">
                <Button icon="pi pi-arrow-left" text @click="handleBack" />
                <h1 class="text-2xl font-semibold text-gray-800">用户详情</h1>
            </div>
        </div>

        <div v-if="loading" class="flex justify-center items-center p-8">
            <ProgressSpinner />
        </div>

        <div v-else-if="user" class="grid grid-cols-1 gap-6">
            <!-- 用户基本信息卡片 -->
            <div class="card p-6">
                <div class="flex items-start space-x-6">
                    <img :src="user.avatar" :alt="user.username" class="w-24 h-24 rounded-lg">
                    <div class="flex-1">
                        <h2 class="text-xl font-bold mb-2">{{ user.username }}</h2>
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <p class="text-gray-500">ID</p>
                                <p>{{ user.id }}</p>
                            </div>
                            <div>
                                <p class="text-gray-500">余额</p>
                                <p>{{ (user.balance / 100).toFixed(2) }}</p>
                            </div>
                            <div>
                                <p class="text-gray-500">OpenID</p>
                                <p>{{ user.open_id }}</p>
                            </div>
                            <div>
                                <p class="text-gray-500">状态</p>
                                <Badge :value="user.status === 0 ? '活跃' : '禁用'"
                                    :severity="user.status === 0 ? 'success' : 'danger'" />
                            </div>
                            <div>
                                <p class="text-gray-500">创建时间</p>
                                <p>{{ formatDate(user.created_at) }}</p>
                            </div>
                            <div>
                                <p class="text-gray-500">更新时间</p>
                                <p>{{ formatDate(user.updated_at) }}</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 用户购买的曲谱列表 -->
            <div class="card">
                <h3 class="text-xl font-semibold mb-4">购买的曲谱</h3>
                <DataTable :value="userArticles" stripedRows class="p-datatable-sm" responsiveLayout="scroll"
                    :lazy="true" :totalRecords="totalArticles" :rows="lazyParams.limit" :loading="loading"
                    @page="onPage" paginator :rows-per-page-options="[10, 20, 50]">
                    <Column field="title" header="标题"></Column>
                    <Column field="price" header="价格">
                        <template #body="{ data }">
                            &yen; {{ formatPrice(data.price) }}
                        </template>
                    </Column>
                    <Column field="bought_at" header="购买时间">
                        <template #body="{ data }">
                            {{ formatDate(data.bought_at) }}
                        </template>
                    </Column>
                </DataTable>
            </div>
        </div>
    </div>
</template>
