<template>
    <view class="community-page">
        <view class="community-header" :style="{ paddingTop: statusBarHeight + 'px' }">
            <view class="community-header__bar">
                <image v-if="websiteLogo" class="community-header__logo" :src="websiteLogo" mode="aspectFill" />
                <view class="community-header__search" @tap="goSearch">
                    <text class="community-header__search-icon">🔍</text>
                    <text class="community-header__search-text">搜索世博头条</text>
                </view>
                <AiAssistantEntry size="large" />
            </view>
        </view>

        <view class="community-tags">
            <scroll-view scroll-x class="community-tags__scroll">
                <view class="community-tags__item" :class="{ 'community-tags__item--active': activeTag === 0 }"
                    @tap="switchTag(0)">
                    <text>全部</text>
                </view>
                <view v-if="isLogin" class="community-tags__item"
                    :class="{ 'community-tags__item--active': activeTag === -1 }" @tap="switchTag(-1)">
                    <text>关注</text>
                </view>
                <view v-for="tag in tagList" :key="tag.id" class="community-tags__item"
                    :class="{ 'community-tags__item--active': activeTag === tag.id }" @tap="switchTag(tag.id)">
                    <text>{{ tag.name }}</text>
                    <text v-if="tag.is_hot" class="community-tags__hot">热</text>
                </view>
            </scroll-view>
        </view>

        <scroll-view scroll-y class="community-list" @scrolltolower="loadMore">
            <view v-if="loading && postList.length === 0" class="community-loading">
                <u-loading mode="circle" />
            </view>

            <post-card v-for="post in postList" :key="post.id" :post="post" @tap="goDetail(post.id)"
                @unlock="handleUnlock(post)" @avatar-tap="goUserProfile" @like="handleLike(post)"
                @share="handleShare(post)" @ai-analysis="handleAiAnalysis" />

            <view v-if="!loading && postList.length === 0" class="community-empty">
                <u-empty text="暂无帖子" mode="data" />
            </view>

            <view v-if="loadingMore" class="community-loadmore">
                <u-loading mode="circle" size="32" />
                <text>加载中...</text>
            </view>
            <view v-if="finished && postList.length > 0" class="community-loadmore">
                <text>没有更多了</text>
            </view>
        </scroll-view>

        <view class="community-fab" @tap="goPublish">
            <u-icon name="edit-pen" size="44" color="#fff" />
        </view>

        <share-popup v-if="showSharePopup" v-model:show="showSharePopup" page-type="post" :page-id="sharePostId"
            :title="sharePostTitle || '帖子'" />
    </view>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { getCommunityPosts, getTagLists, purchasePost, toggleLike } from '@/api/community'
import { useAppStore } from '@/stores/app'
import { useUserStore } from '@/stores/user'
import { getToken } from '@/utils/auth'
import AiAssistantEntry from '@/components/ai-assistant-entry/ai-assistant-entry.vue'
import PostCard from '@/packages_community/components/post-card.vue'
import SharePopup from '@/components/share-popup/share-popup.vue'

const appStore = useAppStore()
const userStore = useUserStore()
const COMMUNITY_ACTIVE_TAG_KEY = 'community_active_tag'

const isLogin = computed(() => userStore.isLogin)

const websiteLogo = computed(() => {
    const logo = appStore.config?.website?.shop_logo
    if (!logo) return ''
    if (logo.startsWith('http')) return logo
    return (appStore.config?.domain || '') + logo
})

const goSearch = () => {
    uni.navigateTo({ url: '/pages/search/search' })
}

const statusBarHeight = ref(0)
const activeTag = ref(0)
const tagList = ref<any[]>([])
const postList = ref<any[]>([])
const loading = ref(false)
const loadingMore = ref(false)
const finished = ref(false)
const page = ref(1)
const pageSize = 15
const needRefresh = ref(false)
const fetchRequestId = ref(0)

const getSavedActiveTag = () => {
    const tagId = Number(uni.getStorageSync(COMMUNITY_ACTIVE_TAG_KEY))
    if (!Number.isFinite(tagId)) return 0
    if (tagId === -1 && !getToken()) return 0
    return tagId
}

onMounted(() => {
    const sysInfo = uni.getSystemInfoSync()
    // #ifdef APP-PLUS || MP
    statusBarHeight.value = sysInfo.statusBarHeight || 44
    // #endif
    // #ifdef H5
    statusBarHeight.value = 0
    // #endif
    activeTag.value = getSavedActiveTag()
    fetchTags()
    fetchPosts(true)
    needRefresh.value = false
})

onShow(() => {
    if (needRefresh.value) {
        needRefresh.value = false
        page.value = 1
        finished.value = false
        fetchPosts(true)
    }
})

const fetchTags = async () => {
    try {
        const res = await getTagLists()
        tagList.value = res || []
    } catch (e) {
        console.warn('fetchTags error', e)
    }
}

const shouldHidePost = (post: any) => {
    const tags = Array.isArray(post?.tags) ? post.tags : []
    const images = Array.isArray(post?.images) ? post.images : []
    const content = typeof post?.content === 'string' ? post.content.trim() : ''
    const contentShort = typeof post?.content_short === 'string' ? post.content_short.trim() : ''
    return tags.includes('特朗普') && images.length > 0 && !content && !contentShort
}

const isAbortError = (error: any) => {
    const message = String(error?.errMsg || error?.message || error || '')
    return message.includes('abort')
}

const fetchPosts = async (reset = false) => {
    if (reset) {
        page.value = 1
        finished.value = false
    }
    if (finished.value) return
    const requestId = ++fetchRequestId.value

    if (page.value === 1) {
        loading.value = true
    } else {
        loadingMore.value = true
    }

    try {
        const params: Record<string, any> = {
            page_no: page.value,
            page_size: pageSize
        }
        if (activeTag.value === -1) {
            params.follow = 1
        } else if (activeTag.value > 0) {
            params.tag_id = activeTag.value
        }
        const res = await getCommunityPosts(params)
        const rawList = res?.lists || []
        const list = rawList.filter((item: any) => !shouldHidePost(item))
        if (requestId !== fetchRequestId.value) return

        if (reset || page.value === 1) {
            postList.value = list
        } else {
            postList.value.push(...list)
        }

        if (rawList.length < pageSize) {
            finished.value = true
        }
        page.value++
    } catch (e) {
        if (requestId === fetchRequestId.value && !isAbortError(e)) {
            uni.showToast({ title: '加载失败，请重试', icon: 'none' })
        }
    } finally {
        if (requestId === fetchRequestId.value) {
            loading.value = false
            loadingMore.value = false
        }
    }
}

const loadMore = () => {
    if (finished.value || loadingMore.value) return
    fetchPosts()
}

const switchTag = (id: number) => {
    if (activeTag.value === id) return
    activeTag.value = id
    uni.setStorageSync(COMMUNITY_ACTIVE_TAG_KEY, id)
    postList.value = []
    fetchPosts(true)
}

const goDetail = (id: number) => {
    uni.navigateTo({ url: `/packages_community/pages/post_detail?id=${id}` })
}

const goUserProfile = (userId: number) => {
    if (!userId) return
    uni.navigateTo({ url: `/packages_community/pages/user_profile?user_id=${userId}` })
}

const goPublish = () => {
    if (!getToken()) {
        uni.showModal({
            title: '提示',
            content: '发布内容需要登录，是否前往登录？',
            confirmText: '去登录',
            success: (res) => {
                if (res.confirm) {
                    uni.navigateTo({ url: '/pages/login/login' })
                }
            }
        })
        return
    }
    needRefresh.value = true
    uni.navigateTo({ url: '/packages_community/pages/publish' })
}

const checkLogin = () => {
    if (!getToken()) {
        uni.showModal({
            title: '提示',
            content: '该操作需要登录，是否前往登录？',
            confirmText: '去登录',
            success: (res) => {
                if (res.confirm) {
                    uni.navigateTo({ url: '/pages/login/login' })
                }
            }
        })
        return false
    }
    return true
}

const handleUnlock = async (post: any) => {
    if (!getToken()) {
        uni.showModal({
            title: '提示',
            content: '解锁内容需要登录，是否前往登录？',
            confirmText: '去登录',
            success: (res) => {
                if (res.confirm) {
                    uni.navigateTo({ url: '/pages/login/login' })
                }
            }
        })
        return
    }
    try {
        const res = await purchasePost({ post_id: post.id, confirm: 0 })
        if (res?.content) {
            post.is_unlocked = 1
            post.content = res.content
            post.content_short = res.content
            return
        }
        if (res?.needs_payment) {
            uni.showModal({
                title: '解锁内容',
                content: `确认花费 ${res.cost || post.price_points} 积分解锁此内容？`,
                confirmText: '确认解锁',
                confirmColor: '#185dff',
                success: async (modalRes) => {
                    if (modalRes.confirm) {
                        try {
                            const payRes = await purchasePost({ post_id: post.id, confirm: 1 })
                            post.is_unlocked = 1
                            if (payRes?.content) {
                                post.content = payRes.content
                                post.content_short = payRes.content
                            }
                            needRefresh.value = true
                            uni.showToast({ title: '解锁成功', icon: 'success' })
                        } catch (_e) {
                            // 请求层已自动提示错误信息
                        }
                    }
                }
            })
        }
    } catch (_e) {
        // 请求层已自动提示错误信息
    }
}

const handleLike = async (post: any) => {
    if (!checkLogin()) return
    try {
        const res = await toggleLike({ target_id: post.id, target_type: 1 })
        const nextLiked = !!res?.is_liked
        const currentCount = Number(post.like_count || 0)
        post.is_liked = nextLiked
        post.like_count = Math.max(0, currentCount + (nextLiked ? 1 : -1))
    } catch (_e) {
        // 请求层已自动提示错误信息
    }
}

// 分享弹窗
const showSharePopup = ref(false)
const sharePostId = ref(0)
const sharePostTitle = ref('')

const handleShare = (post: any) => {
    sharePostId.value = post.id
    sharePostTitle.value = post.content?.substring(0, 50) || ''
    showSharePopup.value = true
}

const handleAiAnalysis = (post: any) => {
    const tags = Array.isArray(post?.tags) ? post.tags : []
    if (!tags.includes('旧澳六合') && !tags.includes('新澳六合')) {
        return
    }
    const title = encodeURIComponent(String(post?.content || '帖子AI分析').split('\n')[0].trim().slice(0, 28) || '帖子AI分析')
    uni.navigateTo({ url: `/pages/ai_analysis/ai_analysis?type=post&id=${post.id}&title=${title}` })
}
</script>

<style lang="scss" scoped>
.community-page {
    height: 100vh;
    min-height: 0;
    display: flex;
    flex-direction: column;
    background: #fff;
    overflow: hidden;
}

.community-header {
    background: #fff;
    padding: 0 24rpx 16rpx;
    flex-shrink: 0;

    &__bar {
        display: flex;
        align-items: center;
        gap: 16rpx;
        padding-top: 16rpx;
    }

    &__logo {
        width: 68rpx;
        height: 68rpx;
        border-radius: 12rpx;
        flex-shrink: 0;
    }

    &__search {
        flex: 1;
        height: 76rpx;
        display: flex;
        align-items: center;
        gap: 12rpx;
        padding: 0 24rpx;
        background: #f4f5f7;
        border-radius: 12rpx;
    }

    &__search-icon {
        font-size: 28rpx;
        color: #808080;
        line-height: 1;
    }

    &__search-text {
        font-size: 28rpx;
        color: #808080;
    }

}

.community-tags {
    background: #fff;
    padding: 0;
    margin-bottom: 0;
    flex-shrink: 0;

    &__scroll {
        white-space: nowrap;
        display: block;
        padding: 16rpx 24rpx 12rpx;
        font-size: 0;
        line-height: 0;
    }

    &__item {
        display: inline-flex;
        align-items: center;
        gap: 6rpx;
        height: 64rpx;
        padding: 0 24rpx;
        margin-right: 12rpx;
        vertical-align: top;
        border-radius: 12rpx;
        font-size: 28rpx;
        color: #666;
        background: #f4f5f7;

        &--active {
            background: #e5edff;
            color: #185dff;
        }
    }

    &__hot {
        font-size: 20rpx;
        color: #ee3835;
        background: #ffe5e5;
        padding: 2rpx 6rpx;
        border-radius: 6rpx;
        margin-left: 2rpx;
        line-height: 1;
    }

    &__item--active &__hot {
        color: #ee3835;
        background: #ffe5e5;
    }
}

.community-list {
    flex: 1;
    height: 0;
    min-height: 0;
    box-sizing: border-box;
    display: block;
    margin-top: 0;
    padding-top: 0;
    background: #fff;
}

.community-loading {
    display: flex;
    justify-content: center;
    padding: 60rpx 24rpx;
}

.community-empty {
    padding: 120rpx 24rpx;
}

.community-loadmore {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 12rpx;
    padding: 24rpx 0 48rpx;
    font-size: 24rpx;
    color: #999;
}

.community-fab {
    position: fixed;
    right: 32rpx;
    bottom: 180rpx;
    width: 100rpx;
    height: 100rpx;
    border-radius: 50%;
    background: linear-gradient(135deg, #185dff, #ff6b5a);
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 8rpx 24rpx rgba(229, 77, 66, 0.4);
    z-index: 999;
}
</style>
