<template>
    <view class="search-page">
        <!-- 顶部搜索栏 -->
        <view class="search-header">
            <view class="search-header__logo" @tap="goBack">
                <image src="/static/images/logo.png" mode="aspectFit" class="search-header__logo-img" />
            </view>
            <view class="search-header__input">
                <u-icon name="search" size="28" color="#999" />
                <input v-model="keyword" class="search-header__field" :placeholder="searchPlaceholder"
                    :focus="autoFocus" confirm-type="search" @confirm="handleSearch(keyword)" @input="handleInput" />
                <u-icon v-if="keyword" name="close-circle-fill" size="32" color="#666666" @click="clearKeyword" />
            </view>
            <view class="search-header__btn" @tap="handleSearch(keyword)">
                <text class="search-header__btn-text">搜索</text>
            </view>
        </view>

        <!-- 搜索结果 -->
        <view v-if="isSearching" class="search-result">
            <z-paging ref="paging" v-model="resultList" @query="queryList" :fixed="false" height="100%">
                <template v-for="item in resultList" :key="item.id">
                    <feed-video-card v-if="item.is_video" :item="item" />
                    <feed-card v-else :item="item" />
                </template>
            </z-paging>
        </view>

        <!-- 搜索建议（未搜索时） -->
        <scroll-view v-else scroll-y class="search-suggest">
            <!-- 联想词 -->
            <view v-if="suggestList.length" class="suggest-words">
                <view v-for="(item, index) in suggestList" :key="index" class="suggest-words__item"
                    @tap="handleSearch(item)">
                    <u-icon name="search" size="28" color="#ccc" />
                    <text class="suggest-words__text">{{ item }}</text>
                </view>
            </view>

            <!-- 热搜榜Tab -->
            <view v-show="!keyword" class="hot-search">
                <view class="hot-search__tabs">
                    <view v-for="(tab, index) in hotTabs" :key="index" class="hot-search__tab"
                        :class="{ 'hot-search__tab--active': currentHotTab === index }" @tap="currentHotTab = index">
                        <text>{{ tab.name }}</text>
                    </view>
                    <view class="hot-search__tab-actions">
                        <u-icon name="reload" size="28" color="#999" @click="refreshHot" />
                        <u-icon name="eye-off" size="28" color="#999" />
                    </view>
                </view>

                <view class="hot-search__list">
                    <view v-for="(item, index) in currentHotList" :key="index" class="hot-search__item"
                        @tap="handleSearch(item.name)">
                        <text class="hot-search__rank" :class="{ 'hot-search__rank--top': index < 3 }">{{ index + 1
                            }}</text>
                        <text class="hot-search__name" :class="{ 'hot-search__name--top': index < 3 }">{{ item.name
                            }}</text>
                        <view v-if="item.tag" class="hot-search__tag"
                            :class="'hot-search__tag--' + (item.tagType || 'hot')">
                            <text>{{ item.tag }}</text>
                        </view>
                    </view>
                </view>
            </view>

            <!-- 历史搜索 -->
            <view v-show="!keyword && hisSearch.length" class="history-search">
                <view class="history-search__header">
                    <text class="history-search__title">历史搜索</text>
                    <view @tap="handleClear">
                        <u-icon name="trash" size="32" color="#999" />
                    </view>
                </view>
                <view class="history-search__list">
                    <view v-for="(item, index) in hisSearch" :key="index" class="history-search__tag"
                        @tap="handleSearch(item)">
                        <text>{{ item }}</text>
                    </view>
                </view>
            </view>

            <view class="search-feedback">
                <text class="search-feedback__text">© 反馈</text>
            </view>
        </scroll-view>
    </view>
</template>

<script lang="ts" setup>
import { ref, computed, shallowRef } from 'vue'
import { HISTORY } from '@/enums/constantEnums'
import { getHotSearch } from '@/api/shop'
import cache from '@/utils/cache'
import { getArticleList } from '@/api/news'

const keyword = ref('')
const autoFocus = ref(true)
const isSearching = ref(false)
const searchPlaceholder = ref('搜索世博头条')
const resultList = ref<any[]>([])
const paging = shallowRef()
const suggestList = ref<string[]>([])
const hisSearch = ref<string[]>(cache.get(HISTORY) || [])
const currentHotTab = ref(0)

const hotTabs = ref([
    {
        name: '猜你想搜',
        list: [
            { name: '英超联赛最新战报', tag: '' },
            { name: 'NBA季后赛对阵', tag: '热', tagType: 'hot' },
            { name: '中超积分榜', tag: '' },
            { name: '欧冠八强对阵', tag: '新', tagType: 'new' },
            { name: 'AI赛事分析准确率', tag: '' },
            { name: '世预赛国足赛程', tag: '' },
            { name: '足球竞彩推荐', tag: '' },
            { name: 'CBA总决赛', tag: '热', tagType: 'hot' }
        ]
    },
    {
        name: '热榜',
        list: [
            { name: '欧冠淘汰赛精彩回顾', tag: '热', tagType: 'hot' },
            { name: '英超争冠分析', tag: '' },
            { name: 'NBA交易截止日', tag: '新', tagType: 'new' },
            { name: '中超新赛季引援', tag: '' },
            { name: '世界杯预选赛', tag: '' },
            { name: '足球数据分析工具', tag: '' },
            { name: '体育AI预测趋势', tag: '' },
            { name: '篮球战术解析', tag: '' }
        ]
    },
    {
        name: '体育热搜',
        list: [
            { name: '梅西最新动态', tag: '热', tagType: 'hot' },
            { name: 'C罗进球纪录', tag: '' },
            { name: '姚明谈CBA改革', tag: '新', tagType: 'new' },
            { name: '武磊留洋表现', tag: '' },
            { name: '詹姆斯生涯里程碑', tag: '热', tagType: 'hot' },
            { name: '乒乓球世锦赛', tag: '' },
            { name: '网球大满贯赛程', tag: '' },
            { name: 'F1新赛季', tag: '' }
        ]
    }
])

const currentHotList = computed(() => {
    return hotTabs.value[currentHotTab.value]?.list || []
})

const handleInput = () => {
    if (keyword.value.trim()) {
        suggestList.value = hotTabs.value[0].list
            .filter(item => item.name.includes(keyword.value))
            .map(item => item.name)
            .slice(0, 6)
    } else {
        suggestList.value = []
        isSearching.value = false
    }
}

const handleSearch = (value: string) => {
    if (!value || !value.trim()) return
    keyword.value = value
    suggestList.value = []

    if (!hisSearch.value.includes(value)) {
        hisSearch.value.unshift(value)
        if (hisSearch.value.length > 20) hisSearch.value.pop()
        cache.set(HISTORY, hisSearch.value)
    }

    isSearching.value = true
    paging.value?.reload()
}

const clearKeyword = () => {
    keyword.value = ''
    suggestList.value = []
    isSearching.value = false
}

const handleClear = async () => {
    const res: any = await uni.showModal({
        title: '温馨提示',
        content: '是否清空历史记录？'
    })
    if (res.confirm) {
        cache.set(HISTORY, '')
        hisSearch.value = []
    }
}

const queryList = async (pageNo: number, pageSize: number) => {
    try {
        const { lists } = await getArticleList({
            keyword: keyword.value,
            page_no: pageNo,
            page_size: pageSize
        })
        const formatted = (lists || []).map((item: any) => ({
            ...item,
            author: item.author || '体育小编',
            comment_count: item.click || 0
        }))
        paging.value?.complete(formatted)
    } catch (e) {
        console.log('搜索失败=>', e)
        paging.value?.complete(false)
    }
}

const refreshHot = () => {
    uni.showToast({ title: '已刷新', icon: 'none' })
}

const goBack = () => {
    uni.navigateBack()
}

const getHotSearchFunc = async () => {
    try {
        const data = await getHotSearch()
        if (data?.data?.length) {
            hotTabs.value[0].list = data.data.map((item: any) => ({
                name: item.name,
                tag: '',
                tagType: ''
            }))
        }
    } catch (e) {
        console.log('获取热搜失败=>', e)
    }
}
getHotSearchFunc()
</script>

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

/* 顶部搜索栏 */
.search-header {
    display: flex;
    align-items: center;
    padding: 16rpx 24rpx;
    padding-top: calc(var(--status-bar-height, 44px) + 16rpx);
    background: #fff;
    gap: 16rpx;

    &__logo {
        width: 56rpx;
        height: 56rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
    }

    &__logo-img {
        width: 56rpx;
        height: 56rpx;
        border-radius: 12rpx;
    }

    &__input {
        flex: 1;
        height: 68rpx;
        background: #f5f5f5;
        border-radius: 16rpx;
        display: flex;
        align-items: center;
        padding: 0 24rpx;
        gap: 12rpx;
    }

    &__field {
        flex: 1;
        font-size: 28rpx;
        color: #333;
        height: 68rpx;
    }

    &__btn {
        flex-shrink: 0;

        &-text {
            font-size: 30rpx;
            color: #185dff;
            font-weight: 500;
        }
    }
}

/* 搜索结果 */
.search-result {
    height: calc(100vh - 120rpx - var(--status-bar-height, 44px));
}

/* 搜索建议 */
.search-suggest {
    height: calc(100vh - 120rpx - var(--status-bar-height, 44px));
}

/* 联想词 */
.suggest-words {
    &__item {
        display: flex;
        align-items: center;
        padding: 24rpx 30rpx;
        gap: 16rpx;
        border-bottom: 1rpx solid #f5f5f5;
    }

    &__text {
        font-size: 28rpx;
        color: #333;
    }
}

/* 热搜榜 */
.hot-search {
    padding: 30rpx;

    &__tabs {
        display: flex;
        align-items: center;
        margin-bottom: 24rpx;
        gap: 8rpx;
    }

    &__tab {
        font-size: 28rpx;
        color: #999;
        padding: 8rpx 20rpx;
        border-radius: 4rpx;

        &--active {
            color: #222;
            font-weight: bold;
            position: relative;

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

        &-actions {
            margin-left: auto;
            display: flex;
            gap: 24rpx;
        }
    }

    &__list {
        display: flex;
        flex-wrap: wrap;
    }

    &__item {
        width: 50%;
        display: flex;
        align-items: center;
        padding: 20rpx 0;
        gap: 12rpx;
        overflow: hidden;
        min-width: 0;
    }

    &__rank {
        font-size: 28rpx;
        color: #666;
        width: 40rpx;
        text-align: center;
        font-weight: bold;

        &--top {
            color: #f93b37;
        }
    }

    &__name {
        font-size: 26rpx;
        color: #333;
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;

        &--top {
            color: #f93b37;
        }
    }

    &__tag {
        flex-shrink: 0;
        margin-left: 4rpx;
        padding: 2rpx 12rpx;
        border-radius: 6rpx;
        font-size: 20rpx;

        &--hot {
            background: #ffe5e5;
            color: #ee3835;
        }

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

/* 历史搜索 */
.history-search {
    padding: 30rpx;
    border-top: 16rpx solid #f5f5f5;

    &__header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 20rpx;
    }

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

    &__list {
        display: flex;
        flex-wrap: wrap;
        gap: 16rpx;
    }

    &__tag {
        padding: 8rpx 15rpx;
        background: #f5f5f5;
        border-radius: 12rpx;
        font-size: 26rpx;
        color: #666;
    }
}

/* 反馈 */
.search-feedback {
    display: flex;
    justify-content: center;
    padding: 60rpx 0;

    &__text {
        font-size: 24rpx;
        color: #ccc;
    }
}
</style>
