<template>
	<view class="page">
		<!-- 全局搜索框 -->
		<Search placeholder="请输入关键字" showCancelBtn padding="0 30rpx 20rpx" @change="searchChange" @search="goSearchResult" ></Search>
		<!-- 最近搜索 -->
		<TitleOperate v-if="historyList.length > 0" title="最近搜索" padding="10rpx 30rpx 24rpx 30rpx">
			<view class="remove" @click="showRemoveHistory = true"><u-icon name="trash"></u-icon></view>
		</TitleOperate>
		<view class="list" v-if="historyList.length > 0">
			<Tag v-for="(item, index) in historyList" :key="index" @click="goSearchResult(item)">{{ item }}</Tag>
		</view>
		<!-- 间隔 -->
		<view style="height: 30rpx; width: 100%;"></view>
		<!-- 热门搜索 -->
		<TitleOperate v-if="hotList.length > 0" title="热门搜索" padding="10rpx 30rpx 24rpx 30rpx"></TitleOperate>
		<view class="list" v-if="hotList.length > 0">
			<Tag v-for="(item, index) in hotList" :key="index" @click="goSearchResult(item)">{{ item }}</Tag>
		</view>
		<!-- 删除最近搜索的模态框 -->
		<u-modal v-model="showRemoveHistory" content="是否清空最近搜索记录？" @confirm="removeHistory" show-cancel-button :confirm-color="confirmColor"></u-modal>
	</view>
</template>

<script>
import Search from '@/components/search/search.vue';
import TitleOperate from '@/components/title-operate.vue';
import Tag from '@/components/tag.vue';
var _self;
export default {
	components: { Search, TitleOperate, Tag },
	data() {
		return {
			// 直接写在html里不识别，需要在data里转一下
			confirmColor: this.$appTheme.appThemeColor.toString(),
			// 是否显示删除最近搜索的模态框
			showRemoveHistory: false,
			// 是否正在搜索，用于判断是否显示最近搜索和热门搜索
			isInput: false,
			// 最近搜索
			historyList: [],
			// 热门搜索
			hotList: []
		};
	},
	onLoad() {
		_self = this;
		const hist = uni.getStorageSync('historySearch');
		console.log('historySearch>>>',hist)
		if(hist){
			this.historyList = [].concat(hist);
		}
	},
	methods: {
		// 搜索框正在输入
		searchChange(e) {
			if (e) {
				this.isInput = true;
			} else {
				this.isInput = false;
			}
		},


		// 跳转搜索结果页
		goSearchResult(e) {
			this.saveSeaHistory(e);
			uni.navigateTo({
				url: '/pages/search-result?key='+e
			});
		},
		//保存搜索记录
		saveSeaHistory(e) {
			let _self = this;
			let index = _self.historyList.indexOf(e);
			if (index != -1) {
				//获取 e 在数组中的位置
				// let thisindex = 0;
				// for (var i = 0; i < _self.historyList.length; i++) {
				// 	if (_self.historyList[i] == e)
				// 		thisindex = i;
				// }
				//将 e 在数组中删除
				_self.historyList.splice(index, 1);
			}
			//将 e 重新追加到数组第一位
			_self.historyList.unshift(e);
			//超过10位移除
			_self.historyList.splice(20, 1);
			//存入缓存
			uni.setStorageSync('historySearch', _self.historyList);
		},
		// 清空最近搜索记录
		removeHistory() {
			this.historyList = [];
			uni.removeStorageSync('historySearch');
		},
	}
};
</script>

<style lang="scss" scoped>
.page {
	background-color: #fff;
}
.list {
	padding: 0 30rpx;
}
</style>
