<template>
	<view class="search-container">
		<view class="search-main">
			<view class="gosearch-btn">
				<text class="iconfont icon-sousuo"></text>
				<input class="input" maxlength="20" :focus="isFocus" type="text" value="" confirm-type="search" @focus="onFocus" @input="onShowClose" @confirm="SubMitSearch()" placeholder="请输入搜索关键字" v-model.trim="listQuery.name"/>
				<text class="iconfont icon-quxiao" v-if="isShowClose" @click.stop="delInputText()"></text>
			</view>
			<view class="search-btn" @click="SubMitSearch()">搜索</view>
		</view>
		<view class="search-container-history clearfix" v-if="!isShowWrapper">
			<view :class="'s-' + themeClass" v-if="serachRecordList.length>0">
				<view class="header">搜索历史<text class="iconfont icon-shanchu" @click="confirmDetele"></text></view>
				<view class="list">
					<view class="list-main">
						<view v-for="(item,index) in serachRecordList" :key="index" @click="keywordsClick(item)">{{item}}</view>
					</view>
				</view>
			</view>
		</view>
		<view v-else class="commodity-list-wrapper"  :style="{'overflow':'auto','height':(productList.length>4? windowHeight + 'px' : 'auto')}">
			<scroll-view :style="{'height':(productList.length>4? scrollHeight+'px' : 'auto')}" @scrolltolower="scrolltolower" scroll-y v-if="!showEmpty">
				<view v-for="(pro,index) in productList" :key="index" :id="pro.id" class="product-list-type commodity-list" @click.stop="navToDetailPage(pro.productId)">
					<view class="product-list-image">
						<image class="product-image" :src="pro.mainImage" mode=""></image>
					</view>
					<view class="product-list-msgs">
						<view class="product-name">{{ pro.name }}</view>
						<view class="product-unit">规格：{{ pro.unit }}</view>
						<view class="product-tags" v-if="pro.activistatus == 1"><text class="tag">活动价</text></view>
						<view class="product-pric">
							<view class="price">￥{{ pro.price | PriceFormat }}</view>
							<view class="carts" @click.stop="handAddCarts(pro)">
								<view class="carts-add">
									<text class="iconfont icon-gouwuche"></text>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view v-if="showLoading && productList.length > 5">
					<view class="loading-wrapper loading-wrapper-now" v-if="loadingNow">{{loadingText}}<text v-if="loadingText === '已至底部'">‧ ‧ ‧</text></view>
					<view class="loading-wrapper loading-wrapper-btm" v-else>———<text class="btm-text">已至底部</text>———</view>
				</view>
			</scroll-view>
			<view class="empty-container" v-if="showEmpty">
				<image class="empty-container-image" :src="StaticUrl+'icon-empty-search.png'"></image>
				<text class="error-text">暂无搜索结果~</text>
			</view>
		</view>
		<!-- 操作弹窗 -->
		<tui-modal :show="modal" @click="handleClick" @cancel="hideMobel" :content="contentModalText" color="#333" :size="32" shape="circle" :maskClosable="false"></tui-modal>
		<!-- 透明模态层 -->
		<modal-layer v-if='isModallayer'></modal-layer>
	</view>
</template>

<script>
	import { mapState,mapMutations } from 'vuex'
	import modalLayer from "@/components/modal-layer"
	import uniGrader from '@/components/uni-grade/uni-grade.vue'
	import authorize from '@/common/config/authorize.js'
	import wxLogin from "@/services/wxLogin.js"
	
	export default {
		components: {
			modalLayer,
			uniGrader
		},
		data() {
			return {
				StaticUrl:this.$Static,
				shopId:0,
				userID:0,
				themeClass: 'block',
				show:false,
				userIdentity:'',	
				searchKeyType:1,
				isShowClose:false,	//是否显示清空输入框图标
				isSearchHistory:false,//是都显示搜索历史
				serachRecordList:[
					{searchWord:'奥术大师大所打'},
					{searchWord:'奥术大师大所打'},
					{searchWord:'奥术大师大所打'},
					{searchWord:'奥术大师大所打'},
					{searchWord:'奥术大师大所打'},
					{searchWord:'奥术大师大所打'},
				],//历史搜索记录
				isShowWrapper:true,
				isModallayer:false,
				isFocus:false,
				priceLoading:true,
				windowHeight: '',
				showEmpty: false,
				scrollHeight: '',
				productList:[],//商品列表				productIds:'',//查询价格的商品ID
				showLoading: false,
				loadingNow: true,
				loadingText: '上拉加载更多',
				hasNextPage:false,
				pullFlag: true,
				listQuery:{ 
					userId:0,
					name:'',
					pageNum: 1,
					pageSize: 20,
				},
				modal:false,
				contentModalText:'确定删除历史记录？'
			}
		},
		onLoad(option) {
			if(option.type =='share'){
				wxLogin.wxLoginAuthorize()
			}
			this.$api.getStorage().then((resolve) =>{
				this.listQuery.userId = resolve.userId ? resolve.userId : 0;
				this.userIdentity = resolve.userIdentity;
				if(option.keyWord){
					this.listQuery.name = option.keyWord
					this.getListFromServer()
					this.isFocus = false
				}else{
					this.isFocus = true
					this.InitGetSerachRecord()
				}
			})	
		},
		filters: {
			PriceFormat:function(text) {//处理金额
				return Number(text).toFixed(2);
			},
		},
		computed: {
			...mapState(['hasLogin','userInfo','identity'])
		},
		methods:{
			InitGetSerachRecord(){//查询搜索历史记录
				this.ProductService.GetProductSearchHistory({userId:this.listQuery.userId}).then(response =>{
					if(response.code == 0){
						this.serachRecordList = response.data
					}
				})
			},
			SubMitSearch() {//搜索
				if (this.listQuery.name == '') {
					this.$util.msg('请输入搜索关键词',2000);
				}else{
					this.productList =[]
					this.getListFromServer()
					this.isFocus = false
				}
			},
			scrolltolower() {
				if(this.total>this.productList.length && this.pullFlag) {
					this.getListFromServer(true);
				}
			},
			getListFromServer(loadMore) {//搜索商品
				this.showLoading = true;
				this.loadingNow = true;
				this.loadingText = '加载中';
				this.showEmpty = false;				
				if(loadMore) {
					this.listQuery.pageNum += 1;
				}
				this.ProductService.QueryProductList(this.listQuery).then(response =>{
					this.isShowWrapper = true
					const data = response.data;
					const dataList = data.list;
					if(dataList && dataList.length > 0){
						this.hasNextPage = data.hasNextPage;
						this.showEmpty = false;
						if(loadMore) {
							this.productList = [...this.productList,...dataList];
						} else {
							this.productList = [...dataList];
						}
						// 防上拉暴滑
						this.pullFlag = false;
						setTimeout(()=>{ this.pullFlag = true; },500)
						// 底部提示文案
						if(this.hasNextPage) {
							this.loadingText = '上拉加载更多';
						} else {
							this.showLoading = true;
							this.loadingNow = false;
						}
					} else {
						if(!loadMore) {
							this.showEmpty = true;
						}
					}
				}).catch(error =>{
					this.$util.msg(error.msg,2000);
				})
			},
			handAddCarts(pro){
				if(!this.hasLogin){
					this.$api.navigateTo(`/pages/login/login`)
				}else{
					this.ProductService.shoppingAddCart(
						{
							productId:pro.productId,
							userId:this.listQuery.userId,
							productCount:1,
							heUserId:0,
						}
					)
					.then(response => {
						this.$util.msg('加入购物车成功',1500,true,'success')
						this.GetCartNumber()
					})
					.catch(error =>{
						this.$util.msg(error.msg,2000);
					})
				}
			}, 
			onShowClose () {//输入框输入时触发
				this.inputEmpty(this.listQuery.name)
			},
			onFocus () { //输入框获取焦点时触发
				this.inputEmpty(this.listQuery.name)
				this.InitGetSerachRecord()
			},
			delInputText () { //清除输入框内容
				this.listQuery.name = ''
				this.isShowClose = false
				this.isShowWrapper = false
				this.inputEmpty(this.listQuery.name)
				this.InitGetSerachRecord()
			},
			keywordsClick (item) {//关键词搜索与历史搜索
				this.listQuery.name = item;
				this.isShowClose = true;
				this.isFocus = false
				this.SubMitSearch();
			},
			confirmDetele() {//清空历史记录
				this.modal = true;
			},
			handleClick(e) {//用户操作订单
				let index = e.index;
				if(index == 1){
					this.ProductService.GetDeleteProductSearchHistory({userId:this.listQuery.userId}).then(response =>{
						this.$util.msg('删除成功',2000,true,'success')
						this.serachRecordList=[];
					}).catch(error =>{
						this.$util.msg(error.msg,2000)
					})
				}
				this.modal = false;
			},
			hideMobel(){
				this.modal = false;
			},
			inputEmpty(val){
				this.isShowWrapper = false
				if(val != ''){
					this.isShowClose = true
					this.isFocus = true
				}else{					
					this.isShowClose = false
					this.isFocus = true
				}
			},
			isInterceptHtmlFn(text){
				let name = this.$reg.interceptHtmlFn(text)
				return name
			},
			navToDetailPage(id) {
				this.isModallayer = true;
				this.$api.navigateTo(`/pages/goods/product?productId=${id}`);
				this.isModallayer = false;
			},
			setScrollHeight() {
				const {windowHeight, pixelRatio} = wx.getSystemInfoSync();
				this.windowHeight = windowHeight - 1;
				this.scrollHeight = windowHeight - 1;
			},
			toLoginPage() {
				let searchLoginType = 'search'
				uni.navigateTo({
					url:`/pages/login/login?type=${searchLoginType}`
				})
			},
			topBubble() {//显隐搜索项
				this.show = !this.show;
			},
		},
		onShareAppMessage(res){//分享转发
			if (res.from === 'button') {
		      // 来自页面内转发按钮
		    }
			return {
			  title: `点击查看“${this.listQuery.name}”相关的商品`,
			  path: `/pages/goods/search?type=share&keyWord=${this.listQuery.name}`
			}
		},
		onShow() {
			this.setScrollHeight();
		}
	}
</script>

<style lang="scss">
	@import "@/uni.scss";
	page{
		background-color: #F7F7F7 !important;
	}
	.search-main{
		width: 100%;
		height: 88rpx;
		position: fixed;
		top: 0;
		left: 0;
		background: #FFFFFF;
		z-index: 1001;
		box-sizing: border-box;
		padding: 9rpx 24rpx;
		.gosearch-btn{
			width: 604rpx;
			height: 100%;
			float: left;
			border-radius: 40rpx;
			background: #F0F0F0;
			margin: 0 auto;
			padding:0 20rpx;
			font-size: 28rpx;
			line-height: 66rpx;
			padding-left: 66rpx;
			color: #8A8A8A;
			background: #F7F7F7;
			position: relative;
			box-sizing: border-box;
			.icon-sousuo{
				width: 66rpx;
				height: 66rpx;
				line-height: 66rpx;
				text-align: center;
				display: block;
				position: absolute;
				left: 0;
				top: 0;
				font-size: 34rpx;
				color: #8A8A8A;
				z-index: 10;
			}
			.icon-quxiao{
				width: 66rpx;
				height: 66rpx;
				display: block;
				line-height: 66rpx;
				font-size: 36rpx;
				text-align: center;
				color: #8A8A8A;
				position: absolute;
				right: 10rpx;
				top: 0;
				padding: 0 10rpx;
				z-index: 100;
			}
			.input{
				width: 530rpx;
				height: 100%;
				float: left;
				font-size: $font-size-24;
				box-sizing: border-box;
				padding-right: 66rpx;
			}
		}
		.search-btn{
			width: 90rpx;
			height: 66rpx;
			line-height: 66rpx;
			float: right;
			text-align: center;
			color: #666666;
			font-size: $font-size-24;
		}
	}
	.search-container{
		padding-top: 91rpx;
	}
	.search-container-history{
		width: 100%;
		height: auto;
		background-color: #FFFFFF;
	}
	.s-block{
		background: #FFFFFF;
		&.hot{
			border-top: 20rpx solid #F7F7F7;
		}
		.header{
			font-size: 32rpx;
			padding:40rpx 24rpx 22rpx 24rpx;
			line-height: 42rpx;
			font-size: 30rpx;
			font-weight: bold;
			position: relative;
			width: 100%;
			float: left;
			box-sizing: border-box;
			.icon-shanchu{
				font-size: 36rpx;
				color: #333333;
				float: right;
				padding: 0 10rpx;
				z-index: 10;
				font-weight: normal;
			}
		}
		.list{
			width: 100%;
			height: auot;
			float: left;
			padding: 0 24rpx 30rpx 24rpx;
			box-sizing: border-box;
			.list-title{
				width: 100%;
				height: 40rpx;
				font-size: $font-size-26;
				color: #333;
			}
			.list-main{
				width: 100%;
				float: left;
				display: flex;
				flex-wrap: wrap;
				view{
					color: #8A8A8A;
					font-size: 24rpx;
					box-sizing: border-box;
					text-align: center;
					height: 48rpx;
					line-height: 48rpx;
					border-radius: 24rpx;
					margin:12rpx 12rpx 12rpx 0;
					padding:.0 20rpx;
					white-space: nowrap;
					text-overflow: ellipsis;
					background-color: #F3F3F3;
					.iconfont{
						font-size: $font-size-30;
						color: #e15616;
						margin-left: 12rpx;
					}
					&.list-active{
						background-color: #fef6f3;
						color: #e15616;
					}
				}
			}
		}
	}
	.commodity-list-wrapper {
		box-sizing: border-box;
		padding: 0 24rpx;
		background: #FFFFFF;
		scroll-view {
			height: 100%;
			overflow: scroll;
		}	
		.empty-container-image {
			margin-top: -300rpx;
		}
		.toIndexPage {
			bottom: 390rpx;
		}
		.show-more-btn {
			width: 276rpx;
			height: 52rpx;
			line-height: 52rpx;
			border: 2rpx solid #D8D8D8;
			background: #F7F7F7;
			font-size: 26rpx;
			margin: 26rpx 0;
			position: absolute;
			left: 50%;
			margin-left: -138rpx;
		}
	}
	.product-list-type {
		height: 246rpx;
		padding: 32rpx 0;
		box-sizing: border-box;
		border-bottom: 1px solid #e1e1e1;
		&:last-child{
			border-bottom: none;
		}
		.product-list-image{
			width: 182rpx;
			height: 182rpx;
			box-sizing: border-box;
			border-radius: 8rpx;
			border: 1px solid #e1e1e1;
			float: left;
			.product-image{
				width: 180rpx;
				height: 180rpx;
				display: block;
				border-radius: 8rpx;
			}
		}
		.product-list-msgs{
			width: 495rpx;
			height: 100%;
			float: right;
			position: relative;
			.product-name{
				width: 100%;
				height: auto;
				line-height: 36rpx;
				text-overflow: ellipsis;
				overflow: hidden;
				display: -webkit-box;
				-webkit-line-clamp: 2;
				line-clamp: 2;
				-webkit-box-orient: vertical;
				font-size: $font-size-26;
				color: #333333;
				text-align: justify;
				float: left;
			}
			.product-unit{
				width: 100%;
				height: 28rpx;
				float: left;
				margin-top: 4rpx;
				text-align: left;
				line-height: 28rpx;
				font-size: $font-size-20;
				color: #999999;
			}
			.product-tags{
				width: 100%;
				height: 30rpx;
				margin-top: 8rpx;
				float: left;
				.tag{
					display: inline-block;
					width: 80rpx;
					height: 30rpx;
					background: url(https://static.caimei365.com/app/mini-hehe/icon/icon-active.png)top center no-repeat;
					background-size: contain;
					font-size: 22rpx;
					line-height: 30rpx;
					text-align: center;
					color: #f83c6c;
					float: left;
				}
			}
			.product-pric{
				width: 100%;
				height: 44rpx;
				position: absolute;
				bottom: -10rpx;
				left: 0;
				.price{
					float: left;
					font-size:$font-size-26;
					color: #f83c6c;
					font-weight: bold;
					line-height: 44rpx;
				}
				.carts{
					float: right;
					.carts-add{
						width: 44rpx;
						height: 44rpx;
						text-align: center;
						line-height: 44rpx;
						background-color: #ff457b;
						border-radius: 50%;
						.iconfont{
							font-size: 32rpx;
							color: #FFFFFF;
						}
					}
				}
			}
		}
	}
</style>
