<template>
	<view>
		<view :class="'top' + (isScroll ? ' top-background' : '')" :style="'height:' + systems.barHeight + 'rpx;'">
			<view class="top-nav ddflex" :style="'height:' + systems.navigationHeight + 'rpx;top:' + systems.ktxStatusHeight + 'rpx;'">
				<navigator open-type="navigateBack" hover-class="none" class="back ddflex"><image :src="picUrlss + 'back_black.png'"></image></navigator>
				<view class="top-nav-title fflex" :style="'line-height:' + systems.navigationHeight + 'rpx;'" v-if="isScroll">产品</view>
			</view>
		</view>
		<view class="top-con">
			<image :src="merchant.mainGraph" class="top-bg"></image>
			<view class="shop">
				<view class="shop-info ddflex">
					<view class="fflex">
						<view class="shop-name tover">{{ merchant.title }}</view>
						<view class="shop-datas">
							{{ merchant.range ? '距您' + (merchant.mDistance < 1000 ? merchant.mDistance + 'm · ' : merchant.range + 'km · ') : ''
							}}{{ merchant.buyPerson }}位朋友买过
						</view>
					</view>
					<view class="shop-pic"><image :src="merchant.logo" mode="aspectFill" class="shop-logo"></image></view>
				</view>
				<view class="discount ddflex">
					<view class="ddflex fflex">
						<view class="li ddflex" v-for="(item, indexl) in label" :key="indexl">{{ item }}</view>
					</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>
		<view class="ddflex" style="align-items: flex-start;margin-top: 30rpx;" v-else>
			<!-- #ifndef H5 -->
			<scroll-view scroll-y="true" :class="'left savepadding' + (isFixed ? ' left-position' : '')" :style="'top:' + systems.barHeight + 'rpx;'">
				<block v-for="(item, index) in categorys" :key="index">
					<view :class="'li ' + (current == index ? 'active' : '')" :data-current="index" :data-id="item.id" @tap="cateTab">
						<view class="ddflex">{{ item.title }}</view>
					</view>
				</block>
			</scroll-view>
			<!-- #endif -->
			<!-- #ifdef H5 -->
			<scroll-view scroll-y="true" :class="'left' + (isFixed ? ' left-position' : '')" :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">
						<view class="ddflex">{{ item.title }}</view>
					</view>
				</block>
			</scroll-view>
			<!-- #endif  -->
			<view :class="'right' + (isFixed ? ' right-position' : '')">
				<view class="savepadding">
					<scroll-view scroll-X="true" :class="'tab' + (isFixed ? ' tab-position' : '')" :style="'top:' + systems.barHeight + 'rpx;'">
						<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 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="picUrlss + '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>
		</view>
		<cart :isUpdate="isUpdate"></cart>
	</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';
import cart from '../../components/shopping-cart/index';
export default {
	data() {
		return {
			isUpdate: false,
			picUrlss: req.public.picUrls,
			systems: {},
			topHeight: 0,
			isFixed: false,
			isScroll: false,
			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,
			pageList: [],
			_key: '',
			show: Boolean,
			cateid: '',
			merchant: {},
			label: []
		};
	},

	components: {
		foot,
		cart
	},
	props: {},
	onLoad: async function(options) {
		// console.log(options);
		this.setData({
			current: options.current ? options.current : 0,
			merchantId: options.merchantId,
			id: options.id
		});
		this.merchant = req.getStorage('MERCHANT');
		if (this.merchant.label) {
			this.label = this.merchant.label.split(',');
		}
		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);
		console.log('this.topHeight?????', this.topHeight);
	},

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

	onReachBottom() {
		this.page++;
		if (this.currents > -1) {
			this.getList(this.cateid);
		} else {
			this.getList(this.id);
		}
	},

	methods: {
		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
						});
					}

					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, res => {
				// console.log(res);
				let data = {};
				data[dataName] = res;

				if (id == 0) {
					if (listId) {
						this.getList(listId); // this.initCate(listId, 'cates');
					} else {
						this.getList(res[0].id);
						this.initCate(res[0].id, 'cates');
						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);
		},

		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.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;

			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
					});
				}
			}
		}
	},
	created() {
		const systemInfo = uni.getSystemInfoSync();
		// px转换到rpx的比例
		let pxToRpxScale = 750 / systemInfo.windowWidth;
		let systems = {
			ktxStatusHeight: systemInfo.statusBarHeight * pxToRpxScale, // 状态栏的高度
			navigationHeight: 44 * pxToRpxScale // 导航栏的高度
		};
		systems.barHeight = systems.ktxStatusHeight + systems.navigationHeight;
		this.systems = systems;
	},
	mounted: function(e) {
		let that = this;
		const query = wx.createSelectorQuery();
		query
			.select('.top-con')
			.boundingClientRect(function(res) {
				console.log('top-con==', res);
				that.topHeight = res.height;
				console.log('that.topHeight==', that.topHeight);
			})
			.exec();
	},
	onPageScroll(e) {
		const systemInfo = uni.getSystemInfoSync();
		let height = systemInfo.statusBarHeight + 44;
		if (e.scrollTop > height) {
			this.isScroll = true;
		} else {
			this.isScroll = false;
		}
		console.log('this.topHeight=======', this.topHeight);
		if (e.scrollTop > this.topHeight - 15) {
			this.isFixed = true;
		} else {
			this.isFixed = false;
		}
	}
};
</script>
<style>
@import './sort.css';
</style>
