<template>
	<view class="search-page">
		<!-- 状态栏占位 -->
		<view class="status-bar"></view>
		
		<!-- 搜索框 -->
		<view class="search-header">
			<view class="search-input-wrap">
				<input class="search-input" type="text" v-model="keyword" placeholder="搜索商品" confirm-type="search" @confirm="handleSearch" />
				<text class="clear-btn" v-if="keyword" @tap="clearKeyword">×</text>
			</view>
			<text class="cancel-btn" @tap="goBack">取消</text>
		</view>

		<!-- 搜索历史和热门搜索 -->
		<view v-if="!showProductList" class="search-content">
			<!-- 搜索历史 -->
			<view class="search-history" v-if="historyList.length > 0">
				<view class="section-header">
					<text class="section-title">历史记录</text>
					<text class="clear-history" @tap="clearHistory">清空历史</text>
				</view>
				<view class="tag-list">
					<view class="tag-item" v-for="(item, index) in historyList" :key="index" @tap="handleTagClick(item)">
						{{item}}
					</view>
				</view>
			</view>

			<!-- 热门搜索 -->
			<view class="hot-search">
				<view class="section-header">
					<text class="section-title">大家都在搜</text>
				</view>
				<view class="tag-list">
					<view class="tag-item" v-for="(item, index) in hotList" :key="index" @tap="handleTagClick(item)">
						{{item}}
					</view>
				</view>
			</view>
		</view>

		<!-- 商品列表 -->
		<view v-else class="product-section">
			<!-- 排序栏 -->
			<view class="sort-bar">
				<view class="sort-item" :class="{ active: !params.sort }" @tap="handleSort(0)">
					综合
				</view>
				<view class="sort-item" :class="{ active: params.sort === 1 }" @tap="handleSort(1)">
					价格
					<text class="sort-arrow" :class="{ up: params.sort === 1 && params.arrow === 1, down: params.sort === 1 && params.arrow === 2 }">
						⇅
					</text>
				</view>
				<view class="sort-item" :class="{ active: params.sort === 2 }" @tap="handleSort(2)">
					销量
					<text class="sort-arrow" :class="{ up: params.sort === 2 && params.arrow === 1, down: params.sort === 2 && params.arrow === 2 }">
						⇅
					</text>
				</view>
			</view>

			<!-- 商品列表 -->
			<scroll-view 
				class="product-list" 
				scroll-y 
				@scrolltolower="loadMore"
				:refresher-enabled="true"
				:refresher-triggered="isRefreshing"
				@refresherrefresh="onRefresh"
			>
				<view class="product-item" v-for="item in productList" :key="item.id" @tap="goDetail(item.id)">
					<image class="product-image" :src="item.images" mode="aspectFill"></image>
					<view class="product-info">
						<view class="product-name">{{item.name}}</view>
						<view class="product-price">
							<text class="current-price">¥{{item.price}}</text>
							<text class="original-price" v-if="item.originalPrice">¥{{item.originalPrice}}</text>
						</view>
						<view class="product-meta">
							<text class="sales">已售{{item.salesTotal}}件</text>
							<text class="rating" v-if="item.productAvg">评分：{{item.productAvg}}</text>
						</view>
					</view>
				</view>
				
				<!-- 加载状态 -->
				<view class="loading-more" v-if="productList.length > 0">
					{{ hasMore ? '加载中...' : '没有更多了' }}
				</view>
				<view class="empty-state" v-if="productList.length === 0 && !isLoading">
					暂无相关商品
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
import { productSearch } from '@/config/api.js';

export default {
	data() {
		return {
			keyword: '',
			historyList: [],
			hotList: ['鸡蛋', '大蒜', '蔬菜', '王守义十三香', '西瓜', '包菜'],
			showProductList: false,
			productList: [],
			params: {
				current: 1,
				size: 10,
				name: '',
				sort: 0,
				arrow: 1
			},
			isLoading: false,
			hasMore: true,
			isRefreshing: false
		}
	},
	onLoad(options) {
		// 从本地存储获取搜索历史
		const history = uni.getStorageSync('searchHistory');
		if (history) {
			this.historyList = JSON.parse(history);
		}
		
		// 如果有关键词参数，直接搜索
		if (options.keyword) {
			this.keyword = decodeURIComponent(options.keyword);
			this.handleSearch();
		}
	},
	methods: {
		// 处理搜索
		handleSearch() {
			if (!this.keyword.trim()) return;
			
			// 保存到历史记录
			this.saveHistory(this.keyword);
			
			// 重置参数并搜索
			this.params.current = 1;
			this.params.name = this.keyword;
			this.productList = [];
			this.hasMore = true;
			this.showProductList = true;
			this.searchProducts();
		},
		
		// 搜索商品
		async searchProducts() {
			if (this.isLoading || !this.hasMore) return;
			
			this.isLoading = true;
			uni.showLoading({
				title: '加载中...'
			});
			
			try {
				const res = await productSearch(this.params);
				
				if (res.code === 200) {
					const { records, total } = res.data;
					
					// 过滤上架商品
					const validProducts = records.filter(item => item.shelfLife === 1);
					
					if (this.params.current === 1) {
						this.productList = validProducts;
					} else {
						this.productList = [...this.productList, ...validProducts];
					}
					
					this.hasMore = this.productList.length < total;
					
					if (this.hasMore) {
						this.params.current++;
					}
				} else {
					uni.showToast({
						title: res.msg || '获取商品列表失败',
						icon: 'none'
					});
				}
			} catch (err) {
				console.error('搜索商品失败:', err);
				uni.showToast({
					title: '搜索失败，请重试',
					icon: 'none'
				});
			} finally {
				uni.hideLoading();
				this.isLoading = false;
				this.isRefreshing = false;
			}
		},
		
		// 处理排序
		handleSort(sortType) {
			if (sortType === 0) {
				this.params.sort = 0;
				this.params.arrow = 1;
			} else {
				if (this.params.sort === sortType) {
					this.params.arrow = this.params.arrow === 1 ? 2 : 1;
				} else {
					this.params.sort = sortType;
					this.params.arrow = 1;
				}
			}
			
			this.params.current = 1;
			this.productList = [];
			this.hasMore = true;
			this.searchProducts();
		},
		
		// 加载更多
		loadMore() {
			if (!this.isLoading && this.hasMore) {
				this.searchProducts();
			}
		},
		
		// 下拉刷新
		async onRefresh() {
			this.isRefreshing = true;
			this.params.current = 1;
			this.hasMore = true;
			await this.searchProducts();
		},
		
		// 保存搜索历史
		saveHistory(keyword) {
			let history = this.historyList;
			// 去重
			const index = history.indexOf(keyword);
			if (index !== -1) {
				history.splice(index, 1);
			}
			// 最多保存10条
			if (history.length >= 10) {
				history.pop();
			}
			history.unshift(keyword);
			this.historyList = history;
			uni.setStorageSync('searchHistory', JSON.stringify(history));
		},
		
		// 清空历史记录
		clearHistory() {
			uni.showModal({
				title: '提示',
				content: '确定要清空搜索历史吗？',
				success: (res) => {
					if (res.confirm) {
						this.historyList = [];
						uni.removeStorageSync('searchHistory');
					}
				}
			});
		},
		
		// 点击标签
		handleTagClick(keyword) {
			this.keyword = keyword;
			this.handleSearch();
		},
		
		// 清除输入
		clearKeyword() {
			this.keyword = '';
			if (this.showProductList) {
				this.showProductList = false;
				this.productList = [];
			}
		},
		
		// 返回
		goBack() {
			if (this.showProductList) {
				this.showProductList = false;
				this.productList = [];
				this.keyword = '';
			} else {
				uni.navigateBack();
			}
		},
		
		// 跳转到商品详情
		goDetail(id) {
			uni.navigateTo({
				url: '/packageShop/pages/detail/index?id=' + id
			});
		}
	}
}
</script>

<style lang="scss" scoped>
	.search-page {
		min-height: 100vh;
		background: #fff;
		padding-bottom: env(safe-area-inset-bottom);
	}

	.status-bar {
		height: var(--status-bar-height);
		width: 100%;
		background: #fff;
	}

	.search-header {
		display: flex;
		align-items: center;
		padding: 20rpx 30rpx;
		background: #fff;
		position: sticky;
		top: var(--status-bar-height);
		z-index: 100;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.search-content {
		padding-top: 20rpx;
	}

	.search-input-wrap {
		flex: 1;
		height: 72rpx;
		background: #F5F5F5;
		border-radius: 36rpx;
		display: flex;
		align-items: center;
		padding: 0 30rpx;
		margin-right: 20rpx;
		position: relative;
	}

	.search-input {
		flex: 1;
		height: 100%;
		font-size: 28rpx;
	}

	.clear-btn {
		position: absolute;
		right: 20rpx;
		font-size: 40rpx;
		color: #999;
		padding: 10rpx;
	}

	.cancel-btn {
		font-size: 28rpx;
		color: #333;
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin: 40rpx 0 20rpx;
		padding: 0 30rpx;
	}

	.section-title {
		font-size: 28rpx;
		color: #333;
		font-weight: bold;
	}

	.clear-history {
		font-size: 24rpx;
		color: #999;
	}

	.tag-list {
		display: flex;
		flex-wrap: wrap;
		padding: 0 30rpx;
	}

	.tag-item {
		padding: 12rpx 30rpx;
		background: #F5F5F5;
		border-radius: 30rpx;
		font-size: 24rpx;
		color: #666;
		margin: 0 20rpx 20rpx 0;
	}

	.product-section {
		display: flex;
		flex-direction: column;
		height: calc(100vh - var(--status-bar-height) - 112rpx);
	}

	.sort-bar {
		display: flex;
		align-items: center;
		height: 88rpx;
		background: #fff;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.sort-item {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		color: #666;
		position: relative;
		
		&.active {
			color: #D93025;
		}
		
		.sort-arrow {
			margin-left: 4rpx;
			font-size: 24rpx;
			
			&.up {
				transform: scaleY(-1);
			}
			
			&.down {
				transform: scaleY(1);
			}
		}
	}

	.product-list {
		flex: 1;
		background: #f5f5f5;
	}

	.product-item {
		margin: 20rpx;
		background: #fff;
		border-radius: 12rpx;
		overflow: hidden;
	}

	.product-image {
		width: 100%;
		height: 360rpx;
	}

	.product-info {
		padding: 20rpx;
	}

	.product-name {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 16rpx;
	}

	.product-price {
		margin-bottom: 12rpx;
		
		.current-price {
			font-size: 32rpx;
			color: #D93025;
			font-weight: bold;
		}
		
		.original-price {
			font-size: 24rpx;
			color: #999;
			text-decoration: line-through;
			margin-left: 12rpx;
		}
	}

	.product-meta {
		display: flex;
		align-items: center;
		font-size: 24rpx;
		color: #999;
		
		.rating {
			margin-left: 20rpx;
		}
	}

	.loading-more {
		text-align: center;
		font-size: 24rpx;
		color: #999;
		padding: 20rpx 0;
	}

	.empty-state {
		text-align: center;
		font-size: 28rpx;
		color: #999;
		padding: 100rpx 0;
	}
</style> 