<template>
    <view class="follow-page">
        <view class="follow-tabs">
            <view class="follow-tabs__item" :class="{ 'follow-tabs__item--active': currentTab === 'follow' }"
                @tap="switchTab('follow')">
                <text>关注</text>
            </view>
            <view class="follow-tabs__item" :class="{ 'follow-tabs__item--active': currentTab === 'fans' }"
                @tap="switchTab('fans')">
                <text>粉丝</text>
            </view>
        </view>

        <scroll-view scroll-y class="follow-list" style="height: calc(100vh - 90rpx)" @scrolltolower="loadMore">
            <view v-if="loading && list.length === 0" class="follow-loading">
                <u-loading mode="circle" />
            </view>

            <view v-for="item in list" :key="item.id" class="follow-item" @tap="goUserProfile(item.id)">
                <image class="follow-item__avatar" :src="item.avatar || '/static/images/avatar.png'"
                    mode="aspectFill" />
                <view class="follow-item__info">
                    <text class="follow-item__name">{{ item.nickname || '用户' }}</text>
                    <text class="follow-item__id">ID: {{ item.sn || '' }}</text>
                </view>
                <view v-if="currentTab === 'follow'" class="follow-item__actions">
                    <view class="follow-item__btn follow-item__btn--followed" @tap.stop="handleUnfollow(item)">
                        <text>{{ item.is_mutual ? '互相关注' : '已好友' }}</text>
                    </view>
                    <view class="follow-item__chat" @tap.stop="handlePrivateChat(item)">
                        <text>私聊</text>
                    </view>
                </view>
                <view v-else class="follow-item__actions">
                    <view class="follow-item__btn" :class="{ 'follow-item__btn--followed': item.is_followed }"
                        @tap.stop="handleFollow(item)">
                        <text>{{ item.is_followed ? (item.is_mutual ? '互相关注' : '已好友') : '加好友' }}</text>
                    </view>
                    <view v-if="item.is_followed" class="follow-item__chat" @tap.stop="handlePrivateChat(item)">
                        <text>私聊</text>
                    </view>
                </view>
            </view>

            <view v-if="!loading && list.length === 0" class="follow-empty">
                <u-empty :text="currentTab === 'follow' ? '暂无关注' : '暂无粉丝'" mode="data" />
            </view>

            <view v-if="finished && list.length > 0" class="follow-loadmore">
                <text>没有更多了</text>
            </view>
        </scroll-view>
    </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { toggleFollow } from '@/api/community'
import request from '@/utils/request'
import { openChat } from '@/api/chat'

const currentTab = ref('follow')
const list = ref<any[]>([])
const loading = ref(false)
const finished = ref(false)
const page = ref(1)
const pageSize = 20

onLoad((options) => {
    if (options?.type) {
        currentTab.value = options.type
    }
    uni.setNavigationBarTitle({ title: currentTab.value === 'follow' ? '我的关注' : '我的粉丝' })
    fetchList(true)
})

const switchTab = (tab: string) => {
    if (currentTab.value === tab) return
    currentTab.value = tab
    uni.setNavigationBarTitle({ title: tab === 'follow' ? '我的关注' : '我的粉丝' })
    list.value = []
    fetchList(true)
}

const fetchList = async (reset = false) => {
    if (reset) {
        page.value = 1
        finished.value = false
    }
    if (finished.value) return
    loading.value = true

    try {
        const url = currentTab.value === 'follow' ? '/community/followList' : '/community/fansList'
        const res = await request.get({ url, data: { page_no: page.value, page_size: pageSize } })
        const items = res?.lists || []
        if (reset || page.value === 1) {
            list.value = items
        } else {
            list.value.push(...items)
        }
        if (items.length < pageSize) finished.value = true
    } catch (e) {
        // ignore
    } finally {
        loading.value = false
    }
}

const loadMore = () => {
    if (finished.value || loading.value) return
    page.value++
    fetchList()
}

const handleFollow = async (item: any) => {
    try {
        const res = await toggleFollow({ follow_user_id: item.id })
        const followed = res?.is_followed
        item.is_followed = followed
        item.is_mutual = followed ? true : false
        uni.$u.toast(followed ? '已加好友' : '已取消好友')
    } catch (e) {
        uni.$u.toast('操作失败，请重试')
    }
}

const handleUnfollow = async (item: any) => {
    uni.showModal({
        title: '提示',
        content: `确定取消关注「${item.nickname || '该用户'}」吗？`,
        success: async (res) => {
            if (!res.confirm) return
            try {
                await toggleFollow({ follow_user_id: item.id })
                list.value = list.value.filter((i: any) => i.id !== item.id)
                uni.$u.toast('已取消好友')
            } catch (e) {
                uni.$u.toast('操作失败，请重试')
            }
        }
    })
}

const handlePrivateChat = async (item: any) => {
    try {
        const chatSession = await openChat({ target_user_id: Number(item.id || 0) })
        if (chatSession?.id) {
            uni.navigateTo({ url: `/pages/private_chat/room?session_id=${chatSession.id}` })
        }
    } catch (e) {
        // 请求层会提示后端返回信息
    }
}

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

<style lang="scss" scoped>
.follow-page {
    min-height: 100vh;
    background: #f5f5f5;
    overflow-x: hidden;
}

.follow-tabs {
    display: flex;
    background: #fff;
    border-bottom: 1rpx solid #f0f0f0;

    &__item {
        flex: 1;
        text-align: center;
        padding: 24rpx 0;
        font-size: 28rpx;
        color: #666;
        position: relative;

        &--active {
            color: #185dff;
            font-weight: 600;

            &::after {
                content: '';
                position: absolute;
                bottom: 0;
                left: 50%;
                transform: translateX(-50%);
                width: 48rpx;
                height: 4rpx;
                background: #185dff;
                border-radius: 2rpx;
            }
        }
    }
}

.follow-list {
    padding: 16rpx 0;
}

.follow-loading {
    display: flex;
    justify-content: center;
    padding: 120rpx 0;
}

.follow-empty {
    padding: 120rpx 0;
}

.follow-loadmore {
    display: flex;
    justify-content: center;
    padding: 24rpx 0 48rpx;
    font-size: 24rpx;
    color: #999;
}

.follow-item {
    display: flex;
    align-items: center;
    background: #fff;
    border-radius: 16rpx;
    padding: 24rpx;
    margin: 0 24rpx 16rpx;
    overflow: hidden;

    &__avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        flex-shrink: 0;
    }

    &__info {
        flex: 1;
        margin-left: 20rpx;
        min-width: 0;
    }

    &__name {
        font-size: 28rpx;
        font-weight: 600;
        color: #333;
        display: block;
    }

    &__id {
        font-size: 22rpx;
        color: #999;
        margin-top: 4rpx;
        display: block;
    }

    &__actions {
        flex-shrink: 0;
        display: flex;
        align-items: center;
        gap: 12rpx;
    }

    &__btn {
        padding: 10rpx 28rpx;
        border-radius: 8rpx;
        background: #185dff;
        color: #fff;
        font-size: 24rpx;
        flex-shrink: 0;
        border: none;
        outline: none;

        &--followed {
            background: #f0f0f0;
            color: #999;
        }
    }

    &__chat {
        padding: 10rpx 24rpx;
        border-radius: 8rpx;
        background: #111827;
        color: #fff;
        font-size: 24rpx;
        flex-shrink: 0;
        white-space: nowrap;
    }
}
</style>
