<template>
	<view :class="!empty ? 'padding-top-big' : '' ">

		<!-- 空白页 -->
		<use-empty v-if="empty" e-style="round" e-type="search" tip="搜索数据为空" btn-tip="重新搜索" height="70vh" :auto="false"
			@goto="tosearch"></use-empty>

		<!-- 列表区 -->
		<view v-else>
			<!-- 筛选区 -->
			<view class="navbar pos-f w-full dflex bg-main" :style="{ position: headerPosition }">
				<view class="nav-item dflex-c flex1 pos-r h-full" :class="{active: filterIndex === 0}"
					@click="navbarClick(0)">
					综合排序
				</view>
				<!-- <view class="nav-item dflex-c flex1 pos-r h-full" :class="{active: filterIndex === 1}"
					@click="navbarClick(1)">
					销量优先
				</view> -->
				<view class="nav-item dflex-c flex1 pos-r h-full" :class="{active: filterIndex === 2}"
					@click="navbarClick(2)">
					<text>价格</text>
					<view class="">
						<view class="iconfont iconjiantou02 ft-dark dflex-c"
							:class="{active: priceOrder === 1 && filterIndex === 2}"></view>
						<view class="iconfont iconjiantou ft-dark dflex-c"
							:class="{active: priceOrder === 2 && filterIndex === 2}"></view>
					</view>
				</view>
			</view>

			<!-- 商品列表区 -->
			<view class="goods-list">
				<view class="list dflex-b dflex dflex-wrap-w w-full" style="padding-top: 60px;">
					<view class="item bg-main border-radius-sm padding-bottom-sm" v-for="(item, index) in goodsDatas"
						:key="index" @click="togoods(item)">
						<view class="image-wrapper">
							<image mode="aspectFill" :lazy-load="true" v-if="((item.imgs).indexOf(',')) != -1"
							 :src="((item.imgs).substring(0, ((item.imgs).indexOf(','))))"></image>
							 <image mode="aspectFill" :lazy-load="true" v-else
							  :src="item.imgs"></image>
						</view>
						<text class="title clamp padding-sm">{{ item.name }}</text>
						<view class="padding-left-sm dflex-b">
							<text class="price">{{ item.price }}</text>
							<text class="ft-dark margin-right-sm fs-xs">
								<template v-if="item.state=='1'">已售 {{item.saleCnt }}</template>
								<template v-if="item.state=='0'">已下架</template>
								<template v-if="item.state=='2'">审核中</template>
							</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 上拉加载更多 -->
			<use-loadmore :type="loadmoreType"></use-loadmore>
		</view>

		<!-- 置顶 -->
		<use-totop ref="usetop"></use-totop>

		<!-- 03. 猜你想要 -->
		<use-hot-goods v-if="empty" title-type="round" title="猜你想要"></use-hot-goods>
	</view>
</template>

<script>
	import {
		searchadd
	} from '../../utils/api_goods.js'
	import {
		goodslistlimit
	} from '../../utils/api_home.js'
	import useEmpty from '../../components/use-empty/use-empty.vue'
	import useLoadmore from '../../components/use-loadmore/use-loadmore.vue'
	import useTotop from '../../components/use-totop/use-totop.vue'
	import useHotGoods from '../../components/use-hot-goods/use-hot-goods.vue'
	export default {
		components:{
			useEmpty,
			useLoadmore,
			useTotop,
			useHotGoods
		},
		data() {
			return {
				empty: false,
				headerPosition: "fixed",
				// 0综合排序 1销量优先 2价格排序
				filterIndex: 0,
				// 1价格从低到高 2价格从高到低
				priceOrder: 0,
				// 商品数据
				goodsDatas: [],
				// 加载更多状态
				loadmoreType: 'more',
				// 请求数据
				reqdata: {
					page: 1,
					rows: 8,
					sidx: 'sort',
					sord: 'asc'
				},
				scrollTop: 0,
				pan:0,//0是搜索，1是热门，2是限时
				leiId:'',//类别id
				leiLevel:'',//类别level
				keyword:'',//关键字
				now_date:'',//当前时间
			};
		},
		watch: {
			// 显示空白页
			goodsDatas(e) {
				let empty = e.length === 0;
				if (this.empty !== empty) {
					this.empty = empty;
				}
			}
		},
		onPageScroll(e) {
			// 兼容iOS端下拉时顶部漂移
			if (e.scrollTop >= 0) {
				this.headerPosition = "fixed";
			} else {
				this.headerPosition = "absolute";
			}
			// this.scrollTop = e.scrollTop
			this.$refs.usetop.change(e.scrollTop);
		},
		//下拉刷新
		onPullDownRefresh() {
			this.loadData('refresh');
		},
		//加载更多
		onReachBottom() {
			this.loadData();
		},
		onLoad(options) {
			this.getNowDate()
			var userId=options.userId || ''
			var searchCnt=options.searchCnt || 1
			var createBy=options.createBy || ''
			var createTime=decodeURIComponent(options.createTime) || this.now_date
			this.leiId=options.cid || ''
			this.leiLevel=options.level || ''
			this.keyword=decodeURIComponent(options.keyword) || ''
			let title = '搜索列表';
			if (options && options.hot) {
				title = '热门推荐';
				this.pan=1
			} else if (options && options.limited) {
				title = '限时精选';
				this.pan=2
			}

			uni.setNavigationBarTitle({
				title: title
			})

			for (let key in options) {
				this.reqdata[key] = decodeURIComponent(options[key]);
			}
			var data={
				"id": 0,
				"userId": '',
				"keyword": this.keyword,
				"searchCnt": searchCnt,
				"createBy": createBy,
				"createTime": this.now_date,
				"updateTime": this.now_date,
				"updateBy": ""
			}
			var headers={
			   'Content-Type': 'application/json; charset=utf-8',
			}
			//新增历史搜索
			searchadd(data,headers).then((res) => {
				if(res.success){
				}
			})

			this.loadData();
		},
		methods: {
			//获取当前时间
			getNowDate() {
			  var _this = this;
			  // this.timer = setInterval(function() {
				var aData = new Date();
				var month = aData.getMonth() < 9 ? "0" + (aData.getMonth() + 1) : aData.getMonth() + 1;
				var date = aData.getDate() <= 9 ? "0" + aData.getDate() : aData.getDate();
				var date2 = aData.getDate() <= 9 ? "0" + (aData.getDate()-1) : (aData.getDate()-1);
				var Hour = aData.getHours() <= 9 ? "0" + (aData.getHours()) : aData.getHours();
				var Miunte = aData.getMinutes() <= 9 ? "0" + (aData.getMinutes()) : aData.getMinutes();
				var Seconds = aData.getSeconds() <= 9 ? "0" + (aData.getSeconds()) : aData.getSeconds();
				// console.log(aData.getTime())
				_this.now_date = aData.getFullYear() + "-" + month + "-" + date + ' '+ Hour +":"+ Miunte +":"+ Seconds;
				// console.log(aData.getFullYear() + "-" + month + "-" + date2)昨天
			  // }, 86400000);
			},
			// 加载商品，下拉刷新|上拉加载
			loadData(type = 'add', loading) {

				if (this.loadmoreType === 'loading') {
					// 防止重复加载
					return;
				}

				if (loading == 1 || type == 'refresh') {
					// 从首页开始加载
					this.reqdata.page = 1;
				}

				// 没有更多直接返回 
				if (type === 'add') {
					if (this.loadmoreType === 'nomore') {
						return;
					}
					// 加载中
					this.loadmoreType = 'loading';
				} else {
					// 更多
					this.loadmoreType = 'more'
				}
				
				if (this.pan==2){
					//限时精选
					let _self = this;
					_self.goodsDatas=[]
					var data='?limited=1&state=1&orderField='+_self.reqdata.sidx+'&order='+_self.reqdata.sord
					goodslistlimit(data).then((res) => {
						if (res.success) {
							var total=res.data.totalCount
							data='?limited=1&state=1&pageSize='+total+'&orderField='+_self.reqdata.sidx+'&order='+_self.reqdata.sord
							goodslistlimit(data).then((res) => {
								if (res.success) {
									res.data.list.forEach(data => {
										_self.goodsDatas.push(data)
									})
								}else{
									_self.$message.warning('没有符合条件的数据！')
								}
							})
						}
					})
				}else if (this.pan==1){
					let _self = this;
					_self.goodsDatas=[]
					var data='?hot=1'+'&state=1&orderField='+_self.reqdata.sidx+'&order='+_self.reqdata.sord
					// 热门推荐
					goodslistlimit(data).then((res) => {
						if (res.success) {
							var total=res.data.totalCount
							data='?hot=1&state=1&pageSize='+total+'&orderField='+_self.reqdata.sidx+'&order='+_self.reqdata.sord
							goodslistlimit(data).then((res) => {
								if (res.success) {
									res.data.list.forEach(data => {
										_self.goodsDatas.push(data)
									})
								}else{
									_self.$message.warning('没有符合条件的数据！')
								}
							})
						}
					})
				}
				
				let _self = this;
				//根据类别
				var data='?categoryId='+_self.leiId+'&state=1&categoryLevel='+_self.leiLevel
					+'&curPage='+_self.reqdata.page+'&pageSize='+_self.reqdata.rows
					+'&orderField='+_self.reqdata.sidx+'&order='+_self.reqdata.sord
				goodslistlimit(data).then((res) => {
					if (res.success) {
						if (res.data) {
							if (loading == 1 || type == 'refresh') {
								_self.goodsDatas = [];
							}
							let _datas = [];
							res.data.list.forEach((row) => {
								if(row.state === '1'){
									_datas.push(row);
								}
							});
							_self.goodsDatas = [..._self.goodsDatas, ..._datas];
											
							if (res.data.list.length >= _self.reqdata.rows) {
								_self.reqdata.page++;
								_self.loadmoreType = 'more'
							} else {
								_self.loadmoreType = 'nomore'
							}
						} else {
							_self.loadmoreType = 'nomore'
						}
					}
					if (_self.goodsDatas.length === 0) {
						_self.empty = true;
					}
										
					if (loading == 1) {
						uni.hideLoading()
					} else if (type == 'refresh') {
						uni.stopPullDownRefresh();
					}
				})
			},
			// 点击筛选 
			navbarClick(index) {
				// 
				if (this.filterIndex === index && index !== 2) {
					return;
				}

				this.filterIndex = index;

				if (index === 2) {
					this.priceOrder = this.priceOrder === 1 ? 2 : 1;
				} else {
					this.priceOrder = 0;
				}

				if (this.filterIndex == 0) {
					// 综合排序
					this.reqdata.sidx = 'sort';
					this.reqdata.sord = 'asc';
				} else if (this.filterIndex == 1) {
					// 销量优先
					this.reqdata.sidx = 'saleCnt';
					this.reqdata.sord = 'desc';
				} else if (this.filterIndex == 2) {
					// 价格排序
					this.reqdata.sidx = 'price';
					if (this.priceOrder == 1) {
						// 降序
						this.reqdata.sord = 'desc';
					} else if (this.priceOrder == 2) {
						// 升序
						this.reqdata.sord = 'asc';
					}
				}

				uni.pageScrollTo({
					duration: 300,
					scrollTop: 0
				})

				this.loadData('refresh', 1);
				uni.showLoading({
					title: '正在加载'
				})
			},
			// 搜索页
			tosearch() {
				if (this.$api.pages().length > 1) {
					uni.navigateBack();
					return;
				}
				this.$api.tosearch();
			},
			// 商品详情
			togoods(options) {
				this.$api.togoods({
					id: options.id
				});
			}
		},
	}
</script>

<style lang="scss">
	@import url('/packageShang/components/iconfont/iconfont.css');
	@import url('/packageShang/common/common.scss');
	page {
		background-color: $page-color-base;
	}

	.navbar {
		top: var(--window-top);
		left: 0;
		height: 100rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, .06);
		z-index: 10;

		.nav-item {
			font-size: 30rpx;

			&.active {
				&:after {
					content: '';
					position: absolute;
					left: 50%;
					bottom: 0;
					transform: translateX(-50%);
					width: 120rpx;
					height: 0;
					border-bottom: 4rpx solid $base-color;
				}
			}
		}

		.iconfont {
			width: 30rpx;
			height: 14rpx;
			font-size: 20rpx;
			line-height: 1;
			margin-left: 4rpx;
		}
	}

	.goods-list {
		.list {
			padding: 0 3vw 20rpx;
		}

		.item {
			width: 46vw;
			overflow: hidden;
			margin-top: 2vw;

			&:nth-child(2n) {
				margin-left: 1vw;
			}

			&:nth-child(2n + 1) {
				margin-right: 1vw;
			}
		}

		.image-wrapper {
			width: 100%;
			height: 300rpx;
			overflow: hidden;

			image {
				width: 100%;
				height: 100%;
				opacity: 1;
			}
		}
	}
</style>
