<script setup>
import { postApi } from '@/api/postApi'
import { useIntersectionObserver } from '@vueuse/core'
import { onMounted, onUnmounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import Player, { Events, I18N } from 'xgplayer'
import 'xgplayer/dist/index.min.css'
import ZH from 'xgplayer/es/lang/zh-cn'
import MobilePreset from 'xgplayer/es/presets/mobile'

// 启用中文
I18N.use(ZH)

const router = useRouter()
const purchasedArticles = ref([])
const loadingTrigger = ref(null)
const loading = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)
const activeArticle = ref(null)
const player = ref(null)
const limit = 10

const fetchArticles = async () => {
    if (loading.value) return
    loading.value = true
    try {
        const { data } = await postApi.mine({
            page: currentPage.value,
            limit
        })
        if (data.items?.length === 0) {
            hasMore.value = false
        } else {
            purchasedArticles.value.push(...data.items)
            currentPage.value += 1
        }
    } catch (error) {
        console.error('Failed to fetch purchased articles:', error)
    } finally {
        loading.value = false
    }
}

const initializePlayer = async (source) => {
    try {
        player.value = new Player({
            id: 'player',
            url: source,
            autoplay: true,
            // poster: article.head_images[0],
            marginControls: true,
            width: '100%',
            fitVideoSize: 'fixWidth',
            videoFillMode: 'fill',
            fluid: true,
            presets: [MobilePreset],
            playsinline: true,
            playbackRate: [0.5, 0.75, 1],
        })

        player.value.on(Events.ERROR, (error) => {
            alert(`视频播放失败: ${error.errorCode} ${error.message}`)
        })
    } catch (error) {
        console.error("Failed to load video:", error)
        alert("视频加载失败")
    }
}

const playArticle = async (article) => {
    try {
        if (activeArticle.value && activeArticle.value.id === article.id) {
            return
        }

        const { data } = await postApi.play(article.id)
        if (!data.url) {
            alert("视频地址不存在")
            return
        }
        activeArticle.value = article

        if (!player.value) {
            await initializePlayer(data.url)
        } else {
            await player.value.playNext({ url: data.url })
        }
    } catch (error) {
        console.error("Failed to load video:", error)
        alert("视频加载失败")
    }
}

useIntersectionObserver(
    loadingTrigger,
    ([{ isIntersecting }]) => {
        if (isIntersecting && !loading.value && hasMore.value) {
            fetchArticles()
        }
    },
    {
        threshold: 0,
        rootMargin: '100px'
    }
)

onMounted(async () => {
    await fetchArticles()
})

onUnmounted(() => {
    if (player.value) {
        player.value.destroy()
        player.value = null
    }
})
</script>

<template>
    <div class="h-full flex flex-col bg-gray-100">
        <!-- 固定的播放器区域 -->
        <div class="flex-none">
            <div id="player"></div>
        </div>

        <!-- 可滚动的列表区域 -->
        <div class="flex-1 overflow-y-auto">
            <div class="p-2">
                <div v-if="purchasedArticles.length === 0 && !loading" class="text-center text-gray-500 py-8">
                    暂无已购买
                </div>

                <div v-for="article in purchasedArticles" :key="article.id" @click="playArticle(article)" :class="['flex items-center shadow p-4 bg-white rounded mb-2 cursor-pointer hover:bg-gray-50',
                    { 'border-2 border-orange-500': activeArticle?.id === article.id }]">
                    <span class="p-1 bg-sky-500 rounded-full"></span>

                    <div class="ml-3 flex-1 min-w-0">
                        <h3 class="font-medium text-gray-800 line-clamp-2">{{ article.title }}</h3>
                    </div>
                </div>

                <div ref="loadingTrigger" class="py-4 text-center" v-show="hasMore || loading">
                    <div v-if="loading"
                        class="animate-spin rounded-full h-8 w-8 border-4 border-gray-200 border-t-blue-600 mx-auto">
                    </div>
                    <div v-else class="h-8">
                        <!-- 空白占位，保持触发器可见 -->
                    </div>
                </div>

                <div v-if="!hasMore && purchasedArticles.length > 0" class="text-center text-gray-500 py-4">
                    没有更多了
                </div>
            </div>
        </div>
    </div>
</template>
