<template>
	<view class="goods-search">
		<tui-skeleton v-if="isRequest" loadingType="2"></tui-skeleton>
		
		<!-- 搜索输入框 -->
		<view class="order-top">
			<cm-search
				placeholder="请输入商品名称"
				v-model="keyword"
				:clearable="true"
				:keywordList="keywordList"
				:keywordVisible="keywordVisible"
				@focus="keywordVisible = true"
				@clear="keywordVisible = true"
				@remove="removeKeywordModal = true"
				@search="handleSearch"
			></cm-search>
		</view>

		<!-- 列表为空 || 无搜索记录 -->
		<view class="order-empty" v-if="productList.length === 0">
			<cm-empty :image="emptyInfo.image" :message="emptyInfo.message" :offset="100"></cm-empty>
		</view>
		<!-- 商品列表 -->
		<view class="goods-list" v-else>
			<view v-for="(goods, index) in productList" :key="index">
				<view class="line" v-if="index !== 0"></view>
				<view class="goods-section" @click.stop="handleToDetail(goods)">
					<image :src="goods.mainImage" class="cover"></image>
					<view class="content">
						<view class="title" v-text="goods.name"></view>
						<view class="unit">规格：{{ goods.unit }}</view>
						<!-- 标签 -->
						<view class="tags">
							<view class="tag type3" v-if="goods.collageStatus === 1">拼团价</view>
							<view class="tag type2" v-if="goods.activeStatus == 1 && goods.collageStatus === 0">
								活动价
							</view>
							<view class="tag type2" v-if="goods.couponsLogo">优惠券</view>
						</view>
						<!-- 底部 -->
						<view class="footer">
							<!-- 价格 -->
							<view class="price">
								<text>￥{{ goods.price | formatPrice }}</text>
								<text class="delete" v-if="goods.normalPrice">
									￥{{ goods.normalPrice | formatPrice }}
								</text>
							</view>
							<!-- 加入购物车 -->
							<view
								class="add-cart iconfont icon-gouwuche"
								@click.stop="addToCart({ productId: goods.productId })"
								v-if="data.collageStatus !== 1"
							></view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- loading -->
		<view class="loading-more" v-if="productList.length > 0">
			<tui-loadmore :index="3" :visible="loadmore"></tui-loadmore>
			<tui-nomore :text="loadMoreText" :visible="!loadmore" backgroundColor="#fff"></tui-nomore>
		</view>

		<!-- 操作弹窗 -->
		<tui-modal
			:show="removeKeywordModal"
			content="确认清空搜索历史记录？"
			:size="32"
			:maskClosable="false"
			color="#333"
			shape="circle"
			@click="clearSearchRecord"
		></tui-modal>
	</view>
</template>

<script>
import CmSearch from '@/components/cm-module/cm-search/cm-search.vue'
import CmEmpty from '@/components/cm-module/cm-empty/cm-empty.vue'
import { debounce } from '@/common/common.js'
import { mapGetters, mapActions } from 'vuex'

export default {
	components: {
		CmSearch,
		CmEmpty
	},
	data() {
		return {
			isRequest: false,
			keyword: '',
			keywordList: ['测试'],
			keywordVisible: true,
			removeKeywordModal: false,
			pageNum: 1,
			hasMore: false,
			productList: [],

			loadmore: false // 正在加载更多
		}
	},
	computed: {
		...mapGetters(['userId', 'hasLogin']),
		// 上拉加载文案
		loadMoreText() {
			if (this.productList.length === 0) return '没有更多了'
			return this.hasMore ? '上拉加载更多' : '没有更多了'
		},
		// 列表为空
		emptyInfo() {
			const info = {}
			info.image = `${this.$Static}icon-empty-search.png`
			info.message = '暂无搜索结果~_~'

			if (this.keywordList.length <= 0) {
				info.message = '暂无任何搜索历史记录~_~'
			}

			return info
		}
	},
	watch: {
		keywordVisible(nVal) {
			if (!nVal) return
			this.fetchSerachRecord()
			this.productList = []
		}
	},
	onReachBottom() {
		if (!this.hasMore) return
		this.fetchProductList()
	},
	onLoad() {
		this.fetchSerachRecord()
	},
	methods: {
		...mapActions('cart', ['addToCart']),

		// 获取商品列表 使用防抖函数封装
		fetchProductList: debounce(function() {
			this.loadmore = true

			const params = {
				name: this.keyword,
				userId: this.userId,
				pageNum: this.pageNum,
				pageSize: 6
			}

			this.ProductService.GetProductList(params)
				.then(res => {
					this.updateProductList(res)
				})
				.catch(err => {
					console.log(err)
				})
				.finally(() => {
					this.loadmore = false
					this.isRequest = false
				})
		}, 500),

		// 更新商品列表
		updateProductList(response) {
			this.pageNum++
			this.productList = this.productList.concat(response.data.list)
			this.hasMore = response.data.hasNextPage
		},

		// 搜索
		handleSearch() {
			this.keywordVisible = false
			this.isRequest = true
			this.resetProdcutList()
		},

		// 重置商品列表
		resetProdcutList() {
			this.pageNum = 1
			this.fetchProductList()
		},

		// 跳转详情
		handleToDetail(product) {
			uni.navigateTo({
				url: `/pages/goods/product-detail?productId=${product.productId}&jumpState=1`
			})
		},
		// 获取搜索历史
		async fetchSerachRecord() {
			if(!this.hasLogin) return
			try {
				const res = await this.ProductService.GetProductSearchHistory({ userId: this.userId })
				this.keywordList = res.data
			} catch (error) {
				this.$util.msg(error.msg, 2000)
			}
		},
		// 清空搜索历史
		async clearSearchRecord(e) {
			if (!e.index) return (this.removeKeywordModal = false)
			try {
				await this.ProductService.GetDeleteProductSearchHistory({ userId: this.userId })
				await this.fetchSerachRecord()
				this.removeKeywordModal = false
				this.$util.msg('已清空搜索历史记录', 2000)
			} catch (error) {
				this.$util.msg(error.msg, 2000)
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.goods-search {
	min-height: 100vh;
	overflow: hidden;
	padding-top: 90rpx;
	box-sizing: border-box;
}

.order-top {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	z-index: 100000;
}

.line {
	width: 100%;
	height: 1px;
	background: #f7f7f7;
}

.goods-list {
	$radius: 16rpx;
	$grid: 24rpx;

	margin-top: $grid;
	padding: 0 $grid;
	.line {
		margin: $grid 0;
	}

	.goods-section {
		display: flex;
		justify-content: space-between;
		position: relative;
		background: #fff;
		border-radius: $radius;
		overflow: hidden;

		.cover {
			width: 180rpx;
			height: 180rpx;
			box-sizing: border-box;
			border-radius: 8rpx;
			border: 1px solid #e1e1e1;
			box-sizing: border-box;
		}

		.content {
			flex: 1;
			margin-left: $grid;
		}

		.title,
		.unit,
		.tags,
		.footer {
			margin: 2rpx 0;
		}
		.title {
			height: 72rpx;
			font-size: 26rpx;
			line-height: 36rpx;
			text-align: justify;
			color: #333333;
			overflow: hidden;
			text-overflow: ellipsis;
			display: -webkit-box;
			-webkit-line-clamp: 2; // 这里控制几行显示省略号
			-webkit-box-orient: vertical;
		}

		.unit {
			width: 100%;
			height: 28rpx;
			font-size: 20rpx;
			color: #999999;
		}

		.tags {
			display: flex;
			justify-content: flex-start;
			align-items: center;
			height: 36rpx;
			.tag {
				display: flex;
				justify-content: center;
				align-items: center;
				height: 30rpx;
				margin-right: 8rpx;
				font-size: 22rpx;
				&.type1 {
					width: 56rpx;
					background: #ff457b;
					border-radius: 4rpx;
					color: #ffffff;
				}
				&.type2 {
					width: 80rpx;
					background: url(https://static.caimei365.com/app/mini-hehe/icon/icon-active.png) top center
						no-repeat;
					background-size: 80rpx 30rpx;
					color: #f83c6c;
				}
				&.type3 {
					width: 80rpx;
					background: linear-gradient(270deg, #ff457b 0%, #b03bb8 51%, #6431f2 100%);
					color: #fff;
					border-radius: 4rpx;
				}
			}
		}
		.footer {
			position: relative;

			.add-cart {
				position: absolute;
				bottom: 0;
				right: $grid;
				display: flex;
				justify-content: center;
				align-items: center;
				width: 44rpx;
				height: 44rpx;
				background: #ff457b;
				color: #fff;
				border-radius: 50%;
			}
			.price {
				overflow: hidden;
				text-overflow: ellipsis;
				display: -webkit-box;
				-webkit-line-clamp: 1; // 这里控制几行显示省略号
				-webkit-box-orient: vertical;
				box-sizing: border-box;
				padding-right: $grid;
				font-size: 26rpx;
				font-weight: 600;
				color: #f83c6c;
				.delete {
					font-size: 20rpx;
					color: #999999;
					text-decoration: line-through;
					font-weight: normal;
					margin-left: 10rpx;
				}
			}
		}
	}
}
</style>
