<template>
	<view>
		<view class="search-box">
			<view class="search ddflex" @click="search()">
				<image src="../../static/images/ssico.png"></image>
				<view>搜索商品</view>
			</view>
		</view>
		<block v-if="sort">
			<!-- #ifndef H5 -->
			<scroll-view scroll-y="true" class="sort-left" :style="'bottom:' + (bottomBlankHeignt + 115) + 'rpx;'">
				<block v-for="(item, index) in sortCategorys" :key="index">
					<view :class="'li ' + (selectTab == index ? 'active' : '')" :data-index="index" @tap="toScrollView"
						:data-id="item.id">{{item.title}}</view>
				</block>
			</scroll-view>
			<!-- #endif -->
			<!-- #ifdef H5 -->
			<scroll-view scroll-y="true" class="sort-left"
				:style="'bottom:' + (bottomBlankHeignt + 115) + 'rpx;' +'top: 43px'">
				<block v-for="(item, index) in sortCategorys" :key="index">
					<view :class="'li ' + (selectTab == index ? 'active' : '')" :data-index="index" @tap="toScrollView"
						:data-id="item.id">{{item.title}}</view>
				</block>
			</scroll-view>
			<!-- #endif  -->
			<scroll-view scroll-y="true" class="sort-right" :style="'height:' + scrollHeight + 'px;'"
				:scroll-into-view="toView" scroll-top="0" @scroll="scrollTo" scroll-with-animation="true">
				<view class="rcon">
					<view v-for="(cats, idx) in sortCategorys" :key="idx" :id="'position' + idx">
						<view class="tit" @tap="goUrl" :data-id="cats.id" :data-title="cats.title">{{cats.title}}</view>
						<view class="list dflex">
							<view v-for="(item, index) in cats.nodes" :key="index" class="li" @tap="goUrl"
								:data-id="item.id" :data-title="item.title">
								<image :src="item.icon" v-if="item.icon" lazy-load="true"></image>
								<view class="litext" :data-key="key" :style="'background-color:' + item.colors" v-else>
									{{item.first}}
								</view>
								{{item.title}}
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</block>
		<block v-else>
			<!-- #ifndef H5 -->
			<scroll-view scroll-y="true" class="left savepadding">
				<block v-for="(item, index) in categorys" :key="index">
					<view :class="'li ' + (current == index ? 'active' : '')" :data-current="index" :data-id="item.id"
						@tap="cateTab">{{item.title}}</view>
				</block>
			</scroll-view>
			<!-- #endif -->
			<!-- #ifdef H5 -->
			<scroll-view scroll-y="true" class="left"
				:style="'bottom:' + (bottomBlankHeignt + 115) + 'rpx;'+'top: 43px;'">
				<block v-for="(item, index) in categorys" :key="index">
					<view :class="'li ' + (current == index ? 'active' : '')" :data-current="index" :data-id="item.id"
						@tap="cateTab">{{item.title}}</view>
				</block>
			</scroll-view>
			<!-- #endif  -->
			<view class="right" :style="'padding-top:' +heightEle+'rpx'">
				<view class="savepadding">
					<view class="right-top">
						<view class="coupons" @click="jumpUrl('/product/couponList/index?categoryId='+categorys[current].id)" v-if="couponList.length>0 && is_show_coupons == 1">
							<view class="ddflex" style="justify-content: space-between;">
								<view class="coupon-num">{{couponList.length}}个优惠</view>
								<image src="../../static/pages/images/rico_red.png" class="rico"></image>
							</view>
							<view class="coupons-list fflex">
								<scroll-view scroll-x="true" class="coupons-s">
									<view class="li" v-for="(item,index) in couponList" :key="index" @click.stop="recieveCoupon(item,index)">
										<view class="ddflex">
											<view class="coupons-tit">{{item.couponTitle}}</view>
											<text>{{item.userCount >= item.userReceive&&item.userCount!=0&&item.userReceive!=-1 ? '已领' : '领'}}</text>
										</view>
									</view>
								</scroll-view>
							</view>
						</view>
						<scroll-view scroll-X="true" class="tab">
							<view :class="'li ' + (currents == -1 ? 'active' : '')" @tap="all">全部</view>
							<block v-for="(item, index) in cates" :key="index" v-if="!merchantId">
								<view :class="'li ' + (currents == index ? 'active' : '')" @tap="cateTabs"
									:data-currents="index" :data-id="item.id">{{item.title}}{{merchantId}}</view>
							</block>
						</scroll-view>
					</view>
					<view class="sort">
						<block v-for="(item, index) in pageList" :key="index">
							<view class="li dflex">
								<view class="proimgs" @tap="toDetail" :data-id="item.id">
									<image :src="item.pic + '?x-oss-process=style/w160'" mode="aspectFit" class="proimg" lazy-load="true"></image>
									<image src="../../static/pages/images/shouqing.png" class="shouqing" v-if="item.stock < 1"></image>
								</view>
								<view class="flex">
									<view class="proname" @tap="toDetail" :data-id="item.id">{{item.title}}</view>
									<view :class="[item.brandName?'':'nopronames','pronames']">
										{{item.brandName?item.brandName:''}}
									</view>
									<view class="operate dflex">
										<view class="price">
											￥<text>{{item.salePrice}}</text>
											<view class="vip-news ddflex" v-if="show_membership_price==1&&item.actualPrice < item.salePrice"><text class="vip-sale">会员价</text><text class="vip-members">￥{{item.actualPrice}}</text></view>
											<view class="vip-news ddflex" v-if="show_membership_price==1&&item.membersPrice<item.salePrice"><text class="vip-sale">会员价</text><text class="vip-members">￥{{item.membersPrice}}</text></view>
											<!-- <text class="vip" v-if="show_membership_price==1&&item.actualPrice < item.salePrice"><text class="sale">VIP</text><text class="members">{{item.actualPrice}}</text></text>
											<text class="vip"
												v-if="show_membership_price==1&&item.membersPrice<item.salePrice"><text
													class="sale">VIP</text><text
													class="members">{{item.membersPrice}}</text></text> -->
											<text class="del" v-if="show_membership_price!=1">
												<block v-if="item.marketPrice!=0&&item.marketPrice>item.salePrice">
													￥{{item.marketPrice}}
												</block>
											</text>
										</view>
										<view class="add-cart"><!-- addShopCart -->
											<image src="/static/pages/images/jia.png" @tap="toDetail" :data-id="item.id"
												:data-skuid="item.skuId" :data-index="index" :data-state="item.state">
											</image>
										</view>
									</view>
								</view>
							</view>
						</block>
						<view class="nodata nosp bgfff" v-if="show">
							<image :src="picUrlss+'empty_sp.png'"></image>
							<text>暂无商品</text>
						</view>
					</view>
				</view>
			</view>
		</block>


		<foot channel="sort" :isUpdate="isUpdate"></foot>
	</view>
</template>

<script>
	// pages/sort/sort.js
	//获取应用实例
	const app = getApp();
	const req = require("../../utils/request.js");
	let scrollDdirection = 0; // 用来计算滚动的方向
	import foot from "../../components/nav-bar/index";

	export default {
		data() {
			return {
				picUrlss: req.public.picUrls,
				bottomBlankHeignt: app.globalData.isIPhoneX ? 68 : 0,
				categorys: [],
				//产品一级分类列表
				cates: [],
				//产品二级分类列表
				current: 0,
				currents: -1,
				page: 1,
				sort: false,
				sortCategorys: [],
				//产品一级分类列表
				selectTab: 0,
				scrollTop: 0,
				scrollHeight: 0,
				// 滚动视图的高度
				toView: 'position0',
				// 滚动视图跳转的位置
				scrollInfo: [],
				isload: false,
				// 自定义自己喜欢的颜色
				colorArr: ["#e83fa0", "#0cd4c5", "#b146f4", "#18c88b", "#227bfe", "#e8a52f", "#f78d58"],
				// 存储随机颜色
				randomColorArr: [],
				isUpdate: false // 是否更新消息
					,
				merchantId: "",
				id: "",
				show_membership_price: 0,
				Is_Store_Price_Stock: 0,
				is_show_coupons: 0,
				pageList: [],
				_key: "",
				show: Boolean,
				cateid:'',
				couponList: [],
				heightEle: ''
			};
		},

		components: {
			foot
		},
		props: {},
		onLoad: async function(options) {
			// console.log(options);
			this.setData({
				current: options.current ? options.current : 0,
				merchantId: options.merchantId,
				id: options.id
			});
			await this.getConfig();
			uni.getSystemInfo({
				success: res => {
					this.setData({
						scrollHeight: res.windowHeight - 136 * res.windowWidth / 750
					});
				}
			});
			if (this.sort) this.sortCategory();
			else this.category('0', 'categorys', options.id);
		},

		onShow() {
			this.setData({
				isUpdate: !this.isUpdate
			});
		},

		onReachBottom() {
			this.page++;
			if(this.currents>-1){
				this.getList(this.cateid);
			}else{
				this.getList(this.id);
			}
		},
		methods: {
			loadCoupon(id) {
				let form = {
					page: 1,
					limit: 4,
					categoryId: id,
					bindType: 'use'
				};
				return new Promise((resolve,reject)=>{
					req.getRequest('/api/coupon/list', form, data => {
						if(data&&data.length>0){
							this.couponList = data;
						}else{
							this.couponList = [];
						}
						resolve()
					});
				})
			},
			getConfig() {
				var _this = this;
				return new Promise((resolve, reject) => {
					req.getRequest('/api/config', {}, function(res) {
						if (res && res.Product_Sort_ico == 1) _this.setData({
							sort: true
						});

						if (res && res.show_membership_price == 1) {
							_this.setData({
								show_membership_price: 1
							});
						}

						if (res && res.Is_Store_Price_Stock == 1) {
							_this.setData({
								Is_Store_Price_Stock: 1
							});
						}
						if (res && res.is_show_coupons == 1) {
							_this.is_show_coupons = 1
						}

						resolve();
					});
				});
			},

			category(id, dataName, listId) {
				//产品分类
				let that = this;
				// console.log(id, dataName, listId);
				let from = {
					page: 1,
					size: 1000,
					pid: id
				};

				if (this.Is_Store_Price_Stock == 1) {
					if (req.getStorage('smallShop')) {
						from.merchantId = req.getStorage('smallShop').merchantDTO.id;
					} else if (req.getStorage('MERCHANT')) {
						from.merchantId = req.getStorage('MERCHANT').id;
					}
				}

				req.getRequest('/api/category/list', from, async res => {
					// console.log(res);
					let data = {};
					data[dataName] = res;
					if (id == 0) {
						if (listId) {
							this.getList(listId); // this.initCate(listId, 'cates');
						} else {
							if(this.is_show_coupons == 1){
								await this.loadCoupon(res[0].id);
							}
							await this.initCate(res[0].id, 'cates');
							await this.getList(res[0].id);
							that.setData({
								id: res[0].id
							});
						}
					}

					that.setData(data);
					// console.log(data);
				});
			},

			async initCate(id, dataName) {
				await this.category(id, dataName); // if(this.data.merchantId){
				//   return false
				// }

				this.getList(id);
			},

			async cateTab(e) {
				let current = e.currentTarget.dataset.current;
				let id = e.currentTarget.dataset.id;
				this.categoryId = id; // this.category(id, 'cates')
				// this.getList(id)

				this.setData({
					current: current,
					currents: -1,
					id: id,
					page: 1,
					pageList: []
				});
				this.couponList = [];
				this.heightEle = '';
				if(this.is_show_coupons == 1){
					await this.loadCoupon(id);
				}
				await this.initCate(id, 'cates');
			},

			getList(id) {
				// console.log("====================")
				//产品列表
				let that = this;
				var startTime = new Date().getTime();
				// console.log(id);
				let from = {
					page: that.page,
					limit: 6,
					categoryId: id
				};

				if (this.Is_Store_Price_Stock == 1) {
					if (req.getStorage('MERCHANT')) {
						if (req.getStorage('MERCHANT').isDefault != 1) {
							from.merchantId = req.getStorage('MERCHANT').id;
						} else {
							delete from.merchantId;
						}
					}
				} // if (!that.data.isLoad) return false;
				// that.data.isLoad = false;
				const systemInfo = uni.getSystemInfoSync();
				// px转换到rpx的比例
				if(!this.heightEle){
					let pxToRpxScale = 750 / systemInfo.windowWidth;
					uni.createSelectorQuery().in(this).select(".right-top").boundingClientRect(data => {
					  this.heightEle = data.height*pxToRpxScale
					  console.log('this.heightEle==',this.heightEle)
					  this.$forceUpdate();
					}).exec()
				}

				req.getRequest('/api/product/list', from, res => {
					// console.log(new Date().getTime() - startTime);
					if (res && res.length >= 10) that.isLoad = true;
					if (that.page > 1) res = that.pageList.concat(res);
					if (res.length <= 0) {
						that.setData({
							show: true
						})
					} else {
						that.setData({
							show: false
						})
					}
					that.setData({
						pageList: res
					});
				});
			},

			cateTabs(e) {
				let current = e.currentTarget.dataset.currents;
				let id = e.currentTarget.dataset.id;
				this.setData({
					currents: current,
					page: 1,
					pageList: [],
					cateid: id
				});
				this.getList(id);
			},

			all() {
				// console.log(this.id); // this.getList(this.data.id)

				this.setData({
					currents: -1
				});
				this.initCate(this.id, 'cates');
			},

			toDetail(e) {
				let id = e.currentTarget.dataset.id; // let merchant = e.currentTarget.dataset.merchant
				// let shopId = e.currentTarget.dataset.shopid

				if (this.Is_Store_Price_Stock == 1) {
					if (req.getStorage('smallShop')) {
						var merchantId = req.getStorage('smallShop').merchantDTO.id;
						var shopId = req.getStorage('smallShop').id;
						app.globalData.openPage("product/detail/detail?id=" + id + "&merchantId=" + merchantId +
							"&shopId=" + shopId);
					} else if (req.getStorage('MERCHANT')) {
						if (req.getStorage('MERCHANT').isDefault != 1) {
							merchantId = req.getStorage('MERCHANT').id;
							app.globalData.openPage("product/detail/detail?id=" + id + "&merchantId=" + merchantId);
						} else {
							app.globalData.openPage("product/detail/detail?id=" + id);
						}
					}
				} else {
					app.globalData.openPage("product/detail/detail?id=" + id);
				} // if (!shopId) {
				//   app.openPage("product/detail/detail?id=" + id + "&merchantId=" + merchantId)
				// } else {
				//   app.openPage("product/detail/detail?id=" + id + "&merchantId=" + merchantId + "&shopId=" + shopId)
				// }
				// app.openPage("product/detail/detail?id=" + id)

			},

			addShopCart(e) {
				let that = this;
				let skuId = e.currentTarget.dataset.skuid;
				let id = e.currentTarget.dataset.id;
				let index = e.currentTarget.dataset.index;
				let pageList = that.pageList;
				let state = e.currentTarget.dataset.state; // let merchant = req.getStorage('MERCHANT');

				req.isLogin().then(success => {
					if (success) {
						let params = {
							skuId: skuId,
							quantity: 1,
							productId: id
						};

						if (req.getStorage('smallShop')) {
							params.merchantId = req.getStorage('smallShop').merchantDTO.id;
							params.shopId = req.getStorage('smallShop').id;
						} else if (req.getStorage('MERCHANT')) {
							params.merchantId = req.getStorage('MERCHANT').id;
						} // if(state!=1){
						//   return req.msg('您来晚了，商品已经下架')
						// }


						req.postRequest('/api/purchase/cart', params, res => {
							that.setData({
								isUpdate: !that.isUpdate
							});
							req.msg('加入购物车成功');
						});
					}
				});
			},

			sortCategory() {
				//产品分类
				let that = this;
				let params = {
					page: 1,
					size: 1000
				};

				if (this.Is_Store_Price_Stock == 1) {
					if (req.getStorage('smallShop')) {
						params.merchantId = req.getStorage('smallShop').merchantDTO
							.id; // params.shopId= req.getStorage('smallShop').id
					} else if (req.getStorage('MERCHANT')) {
						if (req.getStorage('MERCHANT').isDefault != 1) {
							params.merchantId = req.getStorage('MERCHANT').id;
						}
					}
				}

				req.getRequest('/api/category/list', params, res => {
					if (res) {
						let array = res.filter(it => it.pid == 0).map(item => {
							item.nodes = res.filter(ite => ite.pid == item.id).map(mp => {
								mp.first = mp.title.substr(0, 1);
								let random = that.colorArr[Math.floor(Math.random() * that.colorArr
									.length)];
								mp.colors = random;
								return mp;
							});
							return item;
						});
						that.setData({
							sortCategorys: array
						});
						setTimeout(() => {
							that.lisenerScroll();
						}, 100);
					}
				});
			},

			goUrl(e) {
				let id = e.currentTarget.dataset.id;
				let title = e.currentTarget.dataset.title;

				if (this.Is_Store_Price_Stock == 1) {
					if (req.getStorage('smallShop')) {
						var merchantId = req.getStorage('smallShop').merchantDTO.id;
						app.globalData.openPage("product/list/list?id=" + id + '&smallShop=true' + '&title=' + title);
					} else if (req.getStorage('MERCHANT')) {
						if (req.getStorage('MERCHANT').isDefault != 1) {
							merchantId = req.getStorage('MERCHANT').id;
							app.globalData.openPage("product/list/list?id=" + id + "&merchantId=" + merchantId +
								'&title=' + title);
						} else {
							app.globalData.openPage("product/list/list?id=" + id + '&title=' + title);
						}
					}
				} else {
					app.globalData.openPage("product/list/list?id=" + id + '&title=' + title);
				} // app.openPage(e.currentTarget.dataset.url)

			},

			toScrollView(e) {
				const {
					index
				} = e.currentTarget.dataset;
				this.setData({
					selectTab: index,
					toView: `position${index}`
				});
			},

			/**
			 * 获取右边每个分类的头部偏移量
			 */
			lisenerScroll() {
				// var _ts=this;

				/* setTimeout(() => {
				   _ts.setHeight(0);
				 }, 10000);*/
				// 获取各分类容器距离顶部的距离
				new Promise(resolve => {
					let query = uni.createSelectorQuery();
					var clength = this.sortCategorys.length;

					for (var k = 0; k < clength; k++) {
						query.select(`#position${k}`).boundingClientRect();
					}

					query.exec(function(res) {
						resolve(res);
					});
				}).then(res => {
					var categorys = this.sortCategorys;

					if (res.length == categorys.length) {
						categorys.forEach((item, index) => {
							item.offsetTop = res[index].top;
						});
						this.setData({
							scrollInfo: res,
							sortCategorys: categorys
						});
					}
				});
			},

			setHeight(k) {
				var _ts = this;

				if (_ts.isload) {
					return;
				}

				_ts.isload = false;
				let query = uni.createSelectorQuery();
				query.select(`#position${k}`).boundingClientRect();
				query.exec(function(res) {
					var _key = "categorys[" + k + "].offsetTop";

					_ts.setData({
						[_key]: res[0].top
					});

					_ts.isload = true;
				});
			},

			/**
			 * 监听滚动条滚动事件
			 */
			scrollTo(e) {
				const scrollTop = e.detail.scrollTop; //滚动的Y轴

				const {
					selectTab,
					sortCategorys
				} = this;

				if (scrollDdirection < scrollTop) {
					// 向上滑动
					scrollDdirection = scrollTop; // 计算偏移位置
					//  console.log(current, scrollTop,categorys[current + 1].offsetTop);

					if (selectTab < sortCategorys.length - 1 && scrollTop >= sortCategorys[selectTab + 1].offsetTop) {
						// console.log("chua");
						this.setData({
							selectTab: selectTab + 1
						});
					}
				} else {
					// 向下滑动
					scrollDdirection = scrollTop; // 计算偏移位置

					if (selectTab > 0 && scrollTop < sortCategorys[selectTab].offsetTop && scrollTop > 0) {
						this.setData({
							selectTab: selectTab - 1
						});
					}
				}
			},
			search() {
				// app.openPage('pages/search/search')
				app.globalData.openPage('pages/search/search')
			},
			recieveCoupon(item,index) {
				let _ts = this;
				const coupon = item;
				if (coupon.userReceive > -1 && coupon.userCount >= coupon.userReceive) {
					return req.msg('超出优惠券领取限制，无法领取');
				}
				req.postRequest('/api/coupon/receive', {
					id: coupon.id
				}, res => {
					// console.log(res);
					req.msg('领取成功', () => {
						// console.log("11111111111111");
						let isLoading = true;
						this.loadCoupon(this.categorys[this.current].id);
						// _ts.loadCoupon(isLoading);
					});
				});
			},
			jumpUrl(url){
				uni.navigateTo({
					url: url
				})
			}
		}
	};
</script>
<style>
	@import "./sort.css";
</style>
