<template>
	<view class="content">
		<view class="header-search">
			<zzx-icon name="search" size="16"></zzx-icon>
			<input type="text" v-model="searchText" placeholder="搜索俱乐部名称" />
			<view class="search-btn" @click="to_search">
				搜索
			</view>
		</view>
		<view class="search-title" v-if="historyList.length>0">
			<view class="">历史搜索</view>
			<view @click="clearHistory">
				<zzx-icon name="delete" size="14"></zzx-icon>
			</view>
		</view>
		<view class="search-text">
			<view class="item-text" v-for="(item, index) in historyList" :key="index" @click="selectHistory(item)">
				{{ item }}
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref, computed, onMounted } from 'vue';
	import { useCacheStore } from '@/stores/cache';
	import {TipsUtils,RouterUtils} from '@/utils/util'
	const cache = useCacheStore();
	const searchText = ref('');
	const historyList = ref<string[]>([]);
	onMounted(() => {
		const saved = cache.get('SEARCH_INFO');
		historyList.value = Array.isArray(saved) ? saved : [];
	});

	const to_search = () => {
		const keyword = searchText.value.trim();
		if (!keyword) return TipsUtils.tips_toast('请输入搜索内容');
		//移除已存在的相同关键词
		const index = historyList.value.indexOf(keyword);
		if (index !== -1) {
			historyList.value.splice(index, 1);
		}
		historyList.value.unshift(keyword);
		if (historyList.value.length > 20) {
			historyList.value.pop(); // 移除最后一条
		}
		//保存到缓存
		cache.set('SEARCH_INFO', historyList.value);
		searchText.value = '';
		// 这里添加实际搜索逻辑，例如跳转到搜索结果页
		console.log('执行搜索:', keyword);
		RouterUtils.to_page('/pages/index/searchPage/index')
	};
	const selectHistory = (keyword : string) => {
		searchText.value = keyword;
	};
	const clearHistory = async () => {
		let res = await TipsUtils.tips_alert('确定清除历史记录吗？',true) 
		if(res.confirm){
			historyList.value = [];
			cache.remove('SEARCH_INFO');
		}
	};
</script>

<style>
	page {
		background-color: #FFFFFF;
	}
</style>
<style lang="less" scoped>
	.header-search {
		display: flex;
		align-items: center;
		gap: 10rpx;
		background: #F6F6F6;
		width: 700rpx;
		border-radius: 40rpx;

		&>input {
			width: 670rpx;
			font-weight: bold;
			font-size: 24rpx;
		}

		.search-btn {
			width: 144rpx;
			height: 52rpx;
			background: #222222;
			border-radius: 28rpx;
			font-weight: bold;
			font-size: 28rpx;
			color: #C8FF0C;
			line-height: 52rpx;
			text-align: center;
		}
	}

	.search-title {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-top: 28rpx;
		font-weight: bold;
		font-size: 28rpx;
		color: #222222;
	}

	.search-text {
		display: flex;
		align-items: center;
		gap: 20rpx;
		flex-wrap: wrap;
		margin-top: 20rpx;

		.item-text {
			min-width: 50rpx;
			padding: 16rpx;
			background: #F6F6F6;
			border-radius: 16rpx;
			font-size: 28rpx;
			color: #222222;
			text-align: center;
		}
	}
</style>