<template>
	<view class="pages">
		<u-navbar
			title="产品搜索"
			:placeholder="true"
			:autoBack="true"
			 :safeAreaInsetTop="true"
		>
		</u-navbar>
		<view class="search-wrap">
			<u-search
				placeholder="请输入搜索的商品" 
				:clearabled="true"
				:showAction="false"
				height="80rpx"
				@search="search"
				@custom="search"
				bgColor="#fff"
				borderColor="#00A447"
				v-model="keyword">
			</u-search>
		</view>
		<view class="search-history page-wrap" v-if="searchHistory.length>0">
			<view class="search-title u-flex u-row-between">
				<text>最近搜索</text>
				<u-icon @click="clearStorage" name="trash" color="#666" size="30"></u-icon>
			</view>
			<view class="history-wrap">
				<view class="history" v-for="(item,index) in searchHistory" :key="index" @click="keywordClick(item)">
					{{item.name}}
					<!-- <u-icon @click="clearStorage" name="trash" color="#666" size="20"></u-icon> -->
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				keyword:'',
				searchHistory:[],
			}
		},
		onShow() {
			let that = this;
			uni.getStorage({
				key:'searchgoodshistory',
				 success: function(storagedata) {
					 that.searchHistory = storagedata.data;
					 console.log('storagedata',storagedata.data);
				 }
			})
		},
		onLoad() {

		},
		methods: {
			goSearch(keyword){
				uni.$u.route('/shopping/productsearch', {
					goodsName: keyword
				});
			},
			search(e){
				let that = this;
				// 存储历史数据
				let index = this.searchHistory.findIndex(item => item.name === this.keyword);
				// console.log('index',index);
				console.log('11',this.keyword.length<1);
				if (index !== -1||this.keyword.length<1) {
					this.goSearch(this.keyword)
				  // 已经存在，不用重复添加了
				  return;
				}
				this.searchHistory.push({ name: this.keyword });
				uni.setStorage({
				  key: 'searchgoodshistory',
				  data: that.searchHistory,
				  success: function() {
					  that.goSearch(this.keyword)
				    // console.log('数据存储成功')
				  },
				  fail: function() {
				    // console.log('数据存储失败')
				  }
				});
			},
			keywordClick(item){
				this.goSearch(item.name)
				// console.log('keywordClick',item);
			},
			clearStorage(){
				let that = this;
				uni.clearStorage({
					key:'searchgoodshistory',
					success:function(){
						that.searchHistory = []
					}
				})
			}

		}
	}
</script>

<style lang="scss" scoped>
.search-history{
	color: #333333;
	margin-bottom: 30rpx;
	.search-title{
		font-size: 32rpx;
		font-weight: 600;
		line-height: 45rpx;
		margin-bottom: 20rpx;
	}
	.history{
		display: inline-block;
		height: 48rpx;
		line-height: 48rpx;
		background: #F5F5F5;
		border-radius: 24rpx;
		padding: 0 24rpx;
		min-width: 100rpx;
		margin-left: 20rpx;
		margin-bottom: 20rpx;
		text-align: center;
		position: relative;
		/deep/ .u-icon{
			position: absolute;
			right: 0;
			top: 2px;
		}
	}
}
</style>