<template>
    <view class="channel-manage-page" :style="{ paddingTop: statusBarHeight + 'px' }">
        <!-- 顶部导航 -->
        <view class="page-header">
            <view class="page-header__back" @tap="handleBack">
                <u-icon name="arrow-left" size="36" color="#333" />
            </view>
            <text class="page-header__title">频道管理</text>
            <view class="page-header__right" />
        </view>

        <scroll-view scroll-y class="page-scroll">
            <!-- 我的频道 -->
            <view class="channel-section">
                <view class="channel-section__header">
                    <text class="channel-section__title">我的频道</text>
                    <text class="channel-section__tip">{{ isEditing ? '拖拽可排序' : '点击进入频道' }}</text>
                    <text class="channel-section__edit" @tap="toggleEdit">{{ isEditing ? '完成' : '编辑' }}</text>
                </view>
                <view class="channel-grid">
                    <view v-for="(item, index) in myChannels" :key="item.id || '__recommend__'" class="channel-tag"
                        :class="{
                            'channel-tag--active': index === activeIndex,
                            'channel-tag--fixed': item.fixed,
                        }" @tap="handleMyChannelClick(index)">
                        <text>{{ item.name }}</text>
                        <view v-if="isEditing && !item.fixed" class="channel-tag__remove-btn">
                            <text class="channel-tag__remove">×</text>
                        </view>
                    </view>
                </view>
            </view>

            <!-- 推荐频道 -->
            <view v-for="group in recommendGroups" :key="group.title" class="channel-section">
                <view class="channel-section__header">
                    <text class="channel-section__title">{{ group.title }}</text>
                </view>
                <view class="channel-grid">
                    <view v-for="item in group.channels" :key="item.id" class="channel-tag channel-tag--add"
                        @tap="handleAddChannel(item)">
                        <text>{{ item.name }}</text>
                        <text v-if="isEditing" class="channel-tag__add">+</text>
                    </view>
                </view>
            </view>
        </scroll-view>
    </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getArticleCate } from '@/api/news'
import { getUserChannels, setUserChannels } from '@/api/user'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

const CHANNEL_STORAGE_KEY = 'user_my_channels'
const statusBarHeight = ref(0)
const isEditing = ref(false)
const myChannels = ref<any[]>([])
const allCateList = ref<any[]>([])
const activeIndex = ref(-1)
const recommendGroups = ref<{ title: string; channels: any[] }[]>([])
const changed = ref(false)

uni.getSystemInfo({
    success: (res) => {
        // #ifdef APP-PLUS || MP
        statusBarHeight.value = res.statusBarHeight || 44
        // #endif
        // #ifdef H5
        statusBarHeight.value = 0
        // #endif
    }
})

const buildDefaultChannels = (cateList: any[]) => {
    return (cateList || []).map((item: any) => ({ ...item, fixed: false }))
}

const loadData = async () => {
    try {
        const allCate = await getArticleCate()
        allCateList.value = allCate || []
        const defaultChannels = buildDefaultChannels(allCate)

        if (userStore.isLogin) {
            try {
                const res = await getUserChannels() as any
                if (res && Array.isArray(res.channel_ids)) {
                    const savedIds = res.channel_ids
                    const cateMap = new Map(allCate.map((c: any) => [String(c.id), c]))
                    const restored: any[] = []
                    savedIds.forEach((id: any) => {
                        const cate = cateMap.get(String(id))
                        if (cate) restored.push({ ...cate, fixed: false })
                    })
                    myChannels.value = restored
                    filterRecommend()
                    return
                }
            } catch (e) {
                console.log('获取用户频道配置失败=>', e)
            }
        } else {
            const cachedIds = uni.getStorageSync(CHANNEL_STORAGE_KEY)
            if (cachedIds && cachedIds.length) {
                const cateMap = new Map(allCate.map((c: any) => [String(c.id), c]))
                const restored: any[] = []
                cachedIds.forEach((id: any) => {
                    const cate = cateMap.get(String(id))
                    if (cate) restored.push({ ...cate, fixed: false })
                })
                if (restored.length) {
                    myChannels.value = restored
                    filterRecommend()
                    return
                }
            }
        }

        myChannels.value = defaultChannels
        filterRecommend()
    } catch (e) {
        console.log('获取分类失败=>', e)
        if (!myChannels.value.length) {
            uni.showToast({ title: '加载失败，请重试', icon: 'none' })
        }
    }
}

const filterRecommend = () => {
    const myIds = new Set(myChannels.value.map(c => String(c.id)))
    const remaining = allCateList.value.filter(c => !myIds.has(String(c.id)))
    recommendGroups.value = remaining.length
        ? [{ title: '推荐频道', channels: remaining }]
        : []
}

const toggleEdit = () => {
    if (!isEditing.value && !userStore.isLogin) {
        uni.showModal({
            title: '提示',
            content: '登录后才能编辑频道，是否前往登录？',
            confirmText: '去登录',
            success: (res) => {
                if (res.confirm) {
                    uni.navigateTo({ url: '/pages/login/login' })
                }
            }
        })
        return
    }
    if (isEditing.value && changed.value) {
        saveChannels()
        changed.value = false
    }
    isEditing.value = !isEditing.value
}

const handleMyChannelClick = (index: number) => {
    if (isEditing.value) {
        const item = myChannels.value[index]
        if (item.fixed) return
        myChannels.value.splice(index, 1)
        filterRecommend()
        changed.value = true
    } else {
        activeIndex.value = index
        saveAndBack(index)
    }
}

const handleAddChannel = (item: any) => {
    if (!isEditing.value) return
    if (myChannels.value.some((c) => String(c.id) === String(item.id))) return
    myChannels.value.push({ ...item, fixed: false })
    filterRecommend()
    changed.value = true
}

const saveChannels = () => {
    const channelIds = myChannels.value.filter(c => c.id).map(c => c.id)
    if (userStore.isLogin) {
        setUserChannels({ channel_ids: channelIds }).catch((e: any) => {
            console.log('保存频道配置失败=>', e)
            uni.showToast({ title: '保存失败', icon: 'none' })
        })
    } else {
        uni.setStorageSync(CHANNEL_STORAGE_KEY, channelIds)
    }
}

const saveAndBack = (selectIndex?: number) => {
    if (changed.value) {
        saveChannels()
    }
    uni.$emit('channelChanged', {
        channels: changed.value ? [...myChannels.value] : null,
        selectIndex: selectIndex ?? -1
    })
    uni.navigateBack()
}

const handleBack = () => {
    saveAndBack()
}

onLoad(() => {
    changed.value = false
    loadData()
})
</script>

<style lang="scss" scoped>
.channel-manage-page {
    min-height: 100vh;
    background: #fff;
}

.page-header {
    display: flex;
    align-items: center;
    height: 88rpx;
    padding: 0 24rpx;
    border-bottom: 1rpx solid #f0f0f0;

    &__back {
        width: 64rpx;
        height: 64rpx;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    &__title {
        flex: 1;
        text-align: center;
        font-size: 34rpx;
        font-weight: bold;
        color: #222;
    }

    &__right {
        width: 64rpx;
    }
}

.page-scroll {
    height: calc(100vh - 88rpx);
}

.channel-section {
    padding: 30rpx;

    &__header {
        display: flex;
        align-items: center;
        margin-bottom: 24rpx;
    }

    &__title {
        font-size: 34rpx;
        font-weight: bold;
        color: #222;
    }

    &__tip {
        font-size: 24rpx;
        color: #999;
        margin-left: 16rpx;
    }

    &__edit {
        font-size: 26rpx;
        color: #185DFF;
        margin-left: auto;
        padding: 8rpx 24rpx;
        border: 1rpx solid #185DFF;
        border-radius: 28rpx;
    }
}

.channel-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
}

.channel-tag {
    position: relative;
    min-width: 140rpx;
    height: 72rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #F4F5F7;
    border-radius: 8rpx;
    padding: 0 28rpx;
    font-size: 28rpx;
    color: #333;

    &--active {
        color: #185DFF;
        font-weight: bold;
        background: #E5EDFF;
    }

    &--fixed {
        color: #185DFF;
    }

    &--add {
        color: #666;
        background: #F4F5F7;
    }

    &__remove-btn {
        position: absolute;
        top: -10rpx;
        right: -10rpx;
        width: 36rpx;
        height: 36rpx;
        background: #ccc;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    &__remove {
        font-size: 28rpx;
        color: #fff;
        line-height: 1;
    }

    &__add {
        margin-left: 8rpx;
        font-size: 32rpx;
        font-weight: bold;
        color: #185DFF;
    }
}
</style>
