<!-- 搜索頁面 -->
<template>
	<view class="search-page">
		<view class="search-head" :style="{ height: (statusBarH + 44) + 'px' }">
			<view class="search-bar fixed" :style="{ height: (statusBarH + 44) + 'px', paddingTop: statusBarH + 'px' }">
				<view class="head-left" @tap="goBack">
					<text v-if="pagesNum > 1" class="wlIcon wlIcon-fanhui1 back-icon"></text>
					<text v-else class="wlIcon wlIcon-fanhui4 home-icon"></text>
				</view>
				<view class="search-input-wrap">
					<text class="wlIcon wlIcon-sousuo1 search-icon"></text>
					<input class="search-input" type="text" maxlength="12" confirm-type="search" placeholder="搜索商品、分類"
						:value="searchKeywords" focus @confirm="onSearchInputConfirmed" @input="onSearchInputChanged" />
					<text class="wlIcon wlIcon-guanbi search-clear" v-if="inputVal" @tap="onClearInput"></text>
				</view>
				<view class="search-cancel" @tap="goBack">
					<text>取消</text>
				</view>
			</view>
		</view>

		<view class="search-body" v-if="isHistory">
			<view class="history-section" v-if="historyList.length > 0">
				<view class="section-title">
					<text>搜索历史</text>
					<text class="wlIcon wlIcon-shanchu1 clear-btn" @tap="removeHistory"></text>
				</view>
				<view class="tag-list">
					<view class="tag-item" v-for="(item, index) in historyList" :key="index" @tap="keywordsToList(item.keywords)">
						<text>{{ item.keywords }}</text>
					</view>
				</view>
			</view>
			<view class="hot-section">
				<view class="section-title">
					<text>熱門搜索</text>
				</view>
				<view class="tag-list">
					<view class="tag-item" v-for="(item, index) in searchList" :key="index" :class="{ hot: item.flag === 'hot' }"
						@tap="keywordsToList(item.keywords)">
						<text>{{ item.keywords }}</text>
						<text class="hot-badge" v-if="item.flag === 'hot'">hot</text>
					</view>
				</view>
			</view>
		</view>

		<view class="search-suggest" v-else>
			<view class="suggest-list" v-if="search.searchList.length > 0">
				<view class="suggest-item" v-for="(item, index) in search.searchList" :key="index"
					@tap="keywordsToList(item.keywords)">
					<text class="wlIcon wlIcon-sousuo1 suggest-icon"></text>
					<text class="suggest-text">{{ item.keywords }}</text>
				</view>
			</view>
			<view class="category-list" v-if="search.categoryList.length > 0">
				<view class="category-item" v-for="(item, index) in search.categoryList" :key="item.id"
					@tap="categoryToList(item.id, item.name)">
					<text class="category-name">{{ item.name }}</text>
					<view class="category-tag">
						<text>{{ item.name }}分類</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { pullMallSearchList, pullMallSearch, pullMallSetSearch } from '@/features/mall/mall-gateway'

export default {
	data() {
		return {
			statusBarH: 0,
			searchType: 'goods',
			searchKeywords: '',
			inputVal: '',
			isHistory: true,
			searchList: [],
			historyList: [],
			search: {
				searchList: [],
				categoryList: []
			},
			pagesNum: 0
		}
	},
	onLoad(option) {
		this.statusBarH = uni.getSystemInfoSync().statusBarHeight || 0
		this.pagesNum = getCurrentPages().length
		if (option.keywords) this.searchKeywords = option.keywords
		if (option.type) this.searchType = option.type
	},
	onReady() {
		this.loadData()
		this.historyList = uni.getStorageSync('search:history') || []
	},
	methods: {
		async loadData() {
			try {
				this.searchList = await pullMallSearchList()
			} catch (e) {
				console.error('加载热门搜索失败:', e)
			}
		},
		async loadSearch(val) {
			try {
				this.search = await pullMallSearch({ search: val })
				if (this.search.searchList.length > 0 || this.search.categoryList.length > 0) {
					this.isHistory = false
				}
			} catch (e) {
				console.error('实时搜索失败:', e)
			}
		},
		setHistory(text) {
			pullMallSetSearch({ keywords: text })
			this.loadData()
			let searchHistory = uni.getStorageSync('search:history') || []
			this.historyList = searchHistory
			let serachData = {}
			if (typeof text === 'string') {
				serachData = { keywords: text }
			} else {
				serachData = text
			}
			for (var i = 0; i < searchHistory.length; i++) {
				if (searchHistory[i].keywords === serachData.keywords) {
					searchHistory.splice(i, 1)
					break
				}
			}
			searchHistory.unshift(serachData)
			uni.setStorage({ key: 'search:history', data: searchHistory })
		},
		removeHistory() {
			uni.showModal({
				title: '提示',
				content: '確定清空搜索歷史嗎？',
				success: res => {
					if (res.confirm) {
						this.historyList = []
						uni.removeStorage({ key: 'search:history' })
					}
				}
			})
		},
		keywordsToList(keywords) {
			this.setHistory(keywords)
			uni.navigateTo({
				url: `/pages/product/list?type=${this.searchType}&search=${keywords}`
			})
		},
		categoryToList(categoryId, categoryName) {
			this.setHistory(categoryName)
			const data = JSON.stringify({ category_id: categoryId, category_name: categoryName })
			uni.navigateTo({
				url: `/pages/product/list?type=${this.searchType}&data=${encodeURIComponent(data)}`
			})
		},
		onSearchInputChanged(event) {
			let value = event.detail.value
			this.inputVal = value
			if (!value) {
				this.isHistory = true
				return
			} else {
				this.loadSearch(value)
			}
		},
		onSearchInputConfirmed(event) {
			let value = event.detail.value
			if (!value) {
				this.isHistory = true
				if (this.searchKeywords) {
					this.keywordsToList(this.searchKeywords)
				} else {
					uni.showModal({ title: '提示', content: '請輸入搜索關鍵詞' })
					return
				}
			} else {
				this.isHistory = true
				uni.hideKeyboard()
				this.historyList = uni.getStorageSync('search:history') || []
				this.keywordsToList(value)
			}
		},
		onClearInput() {
			this.inputVal = ''
			this.isHistory = true
		},
		goBack() {
			if (this.pagesNum > 1) {
				uni.navigateBack({ delta: 1 })
			} else {
				uni.switchTab({ url: '/pages/index/index' })
			}
		}
	}
}
</script>

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

 .search-head { background: #fff; }
.search-bar.fixed { position: fixed; top: 0; left: 0; right: 0; background: #fff; z-index: 999; display: flex; align-items: center; padding: 0 20rpx; }

.head-left {
	width: 60rpx;
}

.back-icon {
	font-size: 44rpx;
	color: #333;
}

.home-icon {
	font-size: 44rpx;
	color: #333;
}

.search-input-wrap {
	flex: 1;
	display: flex;
	align-items: center;
	height: 64rpx;
	background: #f5f5f5;
	border: 2rpx solid #fe6600;
	border-radius: 32rpx;
	padding: 0 20rpx;
	background-color: #fff;
}

.search-icon {
	font-size: 26rpx;
	margin-right: 10rpx;
	flex-shrink: 0;
}

.search-input {
	flex: 1;
	font-size: 26rpx;
	height: 64rpx;
}

.search-clear {
	font-size: 28rpx;
	color: #999;
	padding: 0 10rpx;
}

.search-cancel {
	width: 80rpx;
	text-align: center;
	font-size: 28rpx;
	color: #333;
}

.search-body { padding: 20rpx 30rpx; }

.section-title {
	display: flex;
	justify-content: space-between;
	align-items: center;
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 20rpx;
}

.clear-btn {
	font-size: 32rpx;
}

.tag-list {
	display: flex;
	flex-wrap: wrap;
	gap: 16rpx;
	margin-bottom: 30rpx;
}

.tag-item {
	padding: 10rpx 24rpx;
	background: #f7f7f7;
	border-radius: 30rpx;
	font-size: 26rpx;
	color: #666;
	position: relative;
}

.tag-item.hot {
	background: #fff5f0;
	color: #e54d42;
}

.hot-badge {
	font-size: 18rpx;
	background: #e54d42;
	color: #fff;
	padding: 2rpx 8rpx;
	border-radius: 6rpx;
	margin-left: 6rpx;
	vertical-align: middle;
}

.suggest-list {
	padding: 0 30rpx;
}

.suggest-item {
	display: flex;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f5f5f5;
}

.suggest-icon {
	font-size: 24rpx;
	margin-right: 16rpx;
	color: #999;
}

.suggest-text {
	font-size: 26rpx;
	color: #333;
}

.category-list {
	padding: 0 30rpx;
}

.category-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f5f5f5;
}

.category-name {
	font-size: 26rpx;
	color: #999;
}

.category-tag {
	background: #fff5f0;
	padding: 6rpx 16rpx;
	border-radius: 20rpx;
	font-size: 22rpx;
	color: #f37b1d;
}
</style>