<template>
	<view>
		<!--product/list/list.wxml-->
		<view class="ssbox bgfff">
			<view class="search dflex" @tap="search">
				<image src="/static/pages/images/ssico.png"></image>
				<view>{{searchTitle ? searchTitle : '搜索你想要的商品'}}</view>
			</view>
		</view>
		<view class="filter dflex bgfff">
			<view :class="'li ' + (sort=='default'?'active':'')" @tap="ss" data-v="default">默认</view>
			<view :class="'li ' + (sort=='stock'?'active':'')" @tap="ss" data-v="stock">销量</view>
			<view v-if="sort=='default'||sort=='stock'" class="li" @tap="ss" data-v="ltPrice">价格<image
					src="/static/pages/images/jiage.png" class="updown"></image>
			</view>
			<view v-if="sort=='ltPrice'" class="li active" @tap="ss" data-v="gtPrice">价格<image
					src="/static/pages/images/up.png" class="updown"></image>
			</view>
			<view v-if="sort=='gtPrice'" class="li active" @tap="ss" data-v="ltPrice">价格<image
					src="/static/pages/images/down.png" class="updown"></image>
			</view>
			<view class="shaixuan li dflex" v-if="showview" @tap="translateshow">筛选<image
					src="/static/pages/images/shaixuan.png">
				</image>
			</view>
		</view>
		<view class="tabcon dflex" v-if="pageList.length > 0">
			<view v-for="(item, index) in pageList" :key="index" class="li">
				<view class="jsdimgs" @tap="toDetail" :data-id="item.id">
					<image :src="item.pic + '?x-oss-process=style/w375'" mode="aspectFit" class="jsdpro"
						lazy-load="true"></image>
					<image src="/static/pages/images/jishida.png" v-if="item.isJs" class="jsdimg"></image>
					<image src="../../static/pages/images/shouqing.png" class="shouqin" v-if="item.stock<1"></image>
				</view>
				<view class="jsdinfo">
					<view class="proname" @tap="toDetail" :data-id="item.id">{{item.title}}</view>
					<view class="list-tag ddflex">
						<block v-if="item.label">
						<view v-for="(it,idx) in item.label.split(',')" :key="idx" v-if="idx < 2">{{it}}</view>
						</block>
					</view>
					<view class="xiaol dflex">
						<block v-if="item.isOtc != 5 && about.is_open_shop == 1 && (isDistriUser == 2 || ascription)">
						<view class="zhuan dflex" v-if="item.commission>0">
							<block>
							<text>赚</text>
							<view class="dflex">￥{{item.commission }}</view>
							</block>
						</view>
						</block>
						<block v-else>
							<view class="vip-news ddflex" v-if="about.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="about.show_membership_price==1&&item.membersPrice<item.salePrice"><text class="vip-sale">会员价</text><text class="vip-members">￥{{item.membersPrice}}</text></view>
						</block>
						<view class="yishou">{{item.sellStock}}件已售</view>
					</view>
					<view class="operate dflex">
						<view class="price">
							￥<text>{{item.salePrice}}</text>
							<!-- <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">
							<view class="dot" :animation="ani" :hidden="!showdot">+1</view><!-- 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>
							<!-- <block v-else>v-if="item.stock>0"
								<text class="color999">已售罄</text>
							</block> -->
							<!-- <view class="nums dflex">
              <image src="/pages/images/jian.png"></image>
              <view class="num">1</view>
              <image src="/pages/images/jia1.png"></image>
            </view> -->
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="nodata" v-if="ishow">
			<image :src="picUrlss+'empty_sp.png'"></image>
			<text>暂无商品</text>
		</view>
		<block v-else>
			<view class="nomore dflex" v-if="!isLoad&&hasmore">亲，没有更多了</view>
			<block v-else>
				<view class="nomore dflex" v-if="!isShowLoading">加载中···</view>
			</block>
		</block>
		<!-- <view class="contact_index1" id="contact_index1" bindtap="goshopCar">
  <image src="/pages/images/cart.png"></image>
  <text class="dots" wx:if="{{count > 0}}">{{count}}</text>
</view> -->
		<cart-pop :isUpdate="isUpdate"></cart-pop>
		<!-- 筛选 -->
		<view :class="isRuleTrue?'isRuleShow':'isRuleHide'">
			<view class="mask" @tap="cancel"></view>
			<view class="shai" :animation="animationData">
				<view class="shai-box">
					<!-- <view class="shai-tit">分类<view class="quanbu dflex">全部<image src="/pages/images/bico.png"></image></view></view> -->
					<view class="shai-tit">分类</view>
					<view class="shai-lis dflex" v-if="categoryList.length>0">
						<view v-for="(item, index) in categoryList" :key="index"
							:class="'li ' + (showId == item.id ? 'active' : '')" :data-id="item.id"
							@tap="childCategory">{{item.title}}</view>
					</view>
				</view>
				<view class="shai-bot dflex">
					<!-- <view class="reset">重置</view> -->
					<!-- <view class="confirm" bindtap="success">确定<text>(124件商品)</text></view> -->
					<view class="confirm" @tap="success">确定</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	// product/list/list.js
	const app = getApp();
	const req = require("../../utils/request.js");

	export default {
		data() {
			return {
				picUrlss: req.public.picUrls,
				page: 1,
				pageList: [],
				pid: '',
				showId: 0,
				showview: true,
				isLoad: true,
				hasmore: false,
				categoryId: '',
				categoryList: [],
				searchTitle: '',
				sort: 'default',
				//stock 库存 ltPrice 价格升序 gtPrice 价格降序
				attr: '',
				//属性 boutique 精品， news 新品，sell_well 爆款，Recommend 推荐,
				isUpdate: false,
				//是否更新消息
				isRuleTrue: false,
				//筛选是否显示
				ishow: false,
				isShowLoading: true, // //购物车x坐标
					// animationx: 0,
					// //购物车y坐标
					// animationy: 0,
					// //是否显示飞行物，默认不显示
					showdot: false,
					// //动画对象
					ani: {},
				merchantId: "",
				shopId: "",
				merchant: "",
				show_membership_price: 0,
				hasemore: false,
				animation: "",
				animationData: {},
				about: {},
				isDistriUser: 0, // 判断用户是否是分销员 2为分销员
				ascription: false,//是否开启小店
			};
		},
		props: {},
		onLoad: function(options) {
			// console.log(options);
			this.query = options;
			let merchant;

			if (req.getStorage('smallShop')) {
				merchant = req.getStorage('smallShop');
			} else {
				merchant = req.getStorage('MERCHANT');
			}

			if (options.merchantId) {
				this.setData({
					merchantId: options.merchantId
				});
			}
			if (options.shopId) {
				this.shopId = options.shopId
			}

			this.setData({
				showId: options.categoryId,
				merchant: merchant,
				pid: options.id
			}); // let attr = ''
			// this.setData({
			//   pid: options.id
			// })
			// if (options.title) {
			//   switch (options.title) {
			//     case "精选榜单":
			//       attr = "boutique";
			//       break;
			//     case "店长推荐":
			//       attr = "Recommend";
			//       break;
			//   }
			// }

			this.attr = options.attr;
			uni.setNavigationBarTitle({
				title: options.title ? options.title : '产品'
			});

			if (options.searchTitle) {
				this.setData({
					searchTitle: options.searchTitle
				});
			}

			this.categoryId = options.id;
			this.getList();
		},

		// onReady() {
		// 	//页面渲染完后获取购物车在页面中的坐标
		//   const query = wx.createSelectorQuery()
		//   query.select('#contact_index1').boundingClientRect()
		//   query.selectViewport().scrollOffset()
		//   query.exec(function(res) {
		//     console.log(res)
		//     let point = res[0]
		//     //坐标修正，让飞行物可以正好落在购物车正中心，20是飞行物宽度一半然后转化成px
		//     var xtemp = (point.left + point.right) / 2 - 20 / 750 * wx.getSystemInfoSync().windowWidth
		//     var ytemp = (point.top + point.bottom) / 2 - 20 / 750 * wx.getSystemInfoSync().windowWidth
		//     console.log('xtemp : ' + xtemp + ' ytemp : ' + ytemp)
		//     that.setData({
		//     	//获取修正后坐标
		//       animationx: xtemp,
		//       animationy: ytemp
		//     })
		//   })
		// },
		onShow() {
			this.getConfig();
			this.getMy();
		},

		onReachBottom() {
			this.page++;
			this.getList();
		},
		
		onReady: function() {
			this.animation = uni.createAnimation();
		},
		methods: {
			getMy() {
				let that = this;
				let userInfo = req.getStorage('userInfo');
				if(!userInfo || userInfo == null) return false;
				req.getRequest('/api/user/my', {}, data => {
					that.isDistriUser = data.isDistriUser;
					if (data && data.listShopBase && data.listShopBase != null && data.listShopBase.length >0) {
						if (data.listShopBase[0].merchant_id == that.merchant.id && that.merchant.type != 5) {
							that.ascription = true;
						}
					}
				});
			},
			getConfig() {
				var _this = this;
				return new Promise((resolve, reject) => {
					req.getRequest('/api/config', {}, function(res) {
						_this.about = res;
						if (res && res.show_membership_price == 1) {
							_this.setData({
								show_membership_price: 1
							});
						}
						resolve();
					});
				});
			},

			ss(e) {
				var dt = e.currentTarget.dataset;
				// console.log(dt)
				this.isLoad = true;
				this.refresh(dt.v);
			},

			refresh(s, t) {
				this.setData({
					hasemore: true,
					sort: s
				});
				this.page = 1;
				this.getList();
			},

			search() {
				// app.openPage('pages/search/search?searchTitle=' + this.data.searchTitle)
				let supplier = '';

				if (this.query.supplier) {
					supplier = '&supplier=' + this.query.supplier;
				}
				if (this.query.merchantId) {
					if (this.query.shopId) {
						app.globalData.redirectTab('pages/search/search?searchTitle=' + this.searchTitle + "&merchantId=" +
							this.query.merchantId + '&shopId=' + this.query.shopId + supplier);
					} else {
						app.globalData.redirectTab('pages/search/search?searchTitle=' + this.searchTitle + '&merchantId=' +
							this.merchantId +
							supplier);
					}
				} else {
					app.globalData.redirectTab('pages/search/search?searchTitle=' + this.searchTitle + supplier);
				}
			},

			getList() {
				let isShowLoading = false;

				if (this.page == 1 && !isShowLoading) {
					req.loadIng('加载中');
					isShowLoading = true;
				} 

				let that = this;
				// console.log(that.isLoad);

				if (!that.isLoad) {
					this.setData({
						isLoad: false
					});
					return false;
				}

				that.isLoad = false;
				that.translate(1);
				let form = {
					page: that.page,
					limit: 10,
					
					sort: that.sort,
					attr: that.attr,
					categoryId: that.categoryId,
					merchantId: that.query.merchantId
				}; // if(that.data.merchant.isDefault!=1){
				//   form.merchantId=that.data.merchant.id
				// }
				if (this.query.supplier) {
					form.supplier = this.query.supplier;
				}
				if(that.searchTitle) form.searchTitle= that.searchTitle
				if (this.query.shopId&&that.query.searchTitle) {
					form.sid = this.query.shopId
					form.merchantId = this.query.merchantId
					delete form.searchTitle;
					if(that.searchTitle) form.title = that.searchTitle;
					
					form.type = 1;
					req.getRequest('/api/shopProduct/list', form, data => {
						// console.log(form);

						if (data && data.length >= 10) {
							that.isLoad = true;
						} else {
							that.setData({
								hasmore: true,
								isLoad: false
							});
						}

						;
						if (that.page > 1) data = that.pageList.concat(data);
						data = data.map(it => {
							if (it.deliverWay && JSON.parse(it.deliverWay).indexOf(3) != -1) it.isJs =
							true;
							return it;
						});
						that.setData({
							pageList: data
						});
						// console.log(data);

						if (data.length <= 0) {
							that.setData({
								ishow: true
							});
						} else {
							that.setData({
								ishow: false
							});
						}

						if (isShowLoading) {
							uni.hideLoading();
							this.setData({
								isShowLoading: false
							});
							isShowLoading = false;
						}
					});
				} else {
					req.getRequest('/api/product/list', form, data => {
						// console.log(form);

						if (data && data.length >= 10) {
							that.isLoad = true;
						} else {
							that.setData({
								hasmore: true,
								isLoad: false
							});
						}

						;
						if (that.page > 1) data = that.pageList.concat(data);
						data = data.map(it => {
							if (it.deliverWay && JSON.parse(it.deliverWay).indexOf(3) != -1) it.isJs =
							true;
							return it;
						});
						that.setData({
							pageList: data
						});
						// console.log(data);

						if (data.length <= 0) {
							that.setData({
								ishow: true,

							});
						} else {
							that.setData({
								ishow: false
							});
						}

						if (isShowLoading) {
							uni.hideLoading();
							this.setData({
								isShowLoading: false
							});
							isShowLoading = false;
						}
					});
				}
			},

			toDetail(e) {
				let id = e.currentTarget.dataset.id;
				if (this.query.shopId) {
					app.globalData.openPage("product/detail/detail?id=" + id + "&merchantId=" + this.query.merchantId +
						'&shopId=' + this.query.shopId);
				}

				if (this.query.merchantId && !this.query.shopId) {
					app.globalData.openPage("product/detail/detail?id=" + id + "&merchantId=" + this.query.merchantId);
				}

				if (!this.merchantId) {
					app.globalData.openPage("product/detail/detail?id=" + id);
				}
			},

			addShopCart(e) {
				let that = this;
				let state = e.currentTarget.dataset.state;
				let skuId = e.currentTarget.dataset.skuid;
				let id = e.currentTarget.dataset.id;
				let index = e.currentTarget.dataset.index;
				let pageList = that.pageList;
				let params = {
					skuId: skuId,
					quantity: 1,
					productId: id
				}; // if(state!=1){
				//   return req.msg('您来晚了，商品已经下架')
				// }

				if (this.query.shopId) {
					params.shopId = this.query.shopId, params.merchantId = this.query.merchantId;
				} else {
					params.merchantId = this.query.merchantId;
				}

				// console.log(pageList);
				req.postRequest('/api/purchase/cart', params, res => {
					that.setData({
						isUpdate: !that.isUpdate
					});
					req.msg('加入购物车成功');
				}); //   if(that.data.showdot == true){
				//     return
				//   }
				//   //获取点击点坐标
				//   var touches = e.touches[0]
				//   //坐标修正，同上，这么做是为了让飞行点落到点击的中心
				//   let toptemp = touches.clientY - 20 / 750 * wx.getSystemInfoSync().windowWidth
				//   let lefttemp = touches.clientX - 20 / 750 * wx.getSystemInfoSync().windowWidth
				//   console.log('toptemp : ' + toptemp + ' lefttemp : ' + lefttemp)
				//   var animation1 = wx.createAnimation({
				//     duration: 1,
				//     timingFunction: 'ease'
				//   })
				//   //通过极短的时间让飞行点移动到手指点击位置，同时让飞行点显示出来
				//   animation1.left(lefttemp).top(toptemp).step()
				//   that.setData({
				//     ani: animation1.export(),
				//     showdot: true
				//   })
				// //然后让飞行点飞行到购物车坐标处，形成添加效果
				//   setTimeout(function(){
				//     const animation = wx.createAnimation({
				//       duration: 1500,
				//       timingFunction: 'ease'
				//     })
				//     //通过Animation的left和top这两个API，将飞行点移动到购物车坐标处
				//     animation.left(that.data.animationx).top(that.data.animationy).step()
				//     that.setData({
				//       ani: animation.export()
				//     })
				//     setTimeout(function () {
				//       var counttemp = that.data.count + 1
				//       that.setData({
				//         showdot: false,
				//         ani: null,
				//         count: counttemp
				//       })
				//     }.bind(this), 1520)//这里也是要稍微延后，后隐藏飞行点，然后清除动画，增加购物计数器
				//   },5)//注意这里要稍微延后，保证前面移动到手指点击处的动画完成
			},

			childCategory: function(e) {
				var id = e.currentTarget.dataset.id;
				// console.log(id);
				this.setData({
					showId: id
				});
			},

			translateshow() {
				// console.log(this.showId);
				this.setData({
					isRuleTrue: true
				});
				this.animation.translate(-310, 0).step();
				this.animationData = this.animation.export()
			},

			translate: function(type) {
				var that = this;
				req.getRequest('/api/category/list', {
					pid: that.pid
				}, data => {
					// console.log(data);

					if (data) {
						that.setData({
							categoryList: data
						});

						if (data.length > 0) {
							this.setData({ // showId: data[0].id,
								// ishow: false
							});
						} else {
							this.setData({
								showview: false // ishow: true

							});
						}
					}
				});

				if (type != 1) {
					this.setData({
						isRuleTrue: true
					});
					this.animation.translate(-310, 0).step();
					this.animationData = this.animation.export()
				}
			},
			success: function() {
				this.setData({
					isRuleTrue: false
				});
				var that = this;
				that.page = 1;
				var categoryId = that.showId;
				this.animation.translate(0, 0).step();
				this.animationData = this.animation.export()

				if (categoryId != null && categoryId != "") {
					this.setData({
						categoryId: categoryId,
						isLoad: true
					});
					that.getList();
				}
			},

			cancel() {
				this.setData({
					isRuleTrue: false
				});
				this.animation.translate(0, 0).step();
				this.animationData = this.animation.export()
			}

		},
		onShareAppMessage: function() {
			let path = '/product/list/list?isShare=' + true;
			if (req.getStorage('userInfo')) {
				path += '&userId=' + req.getStorage('userInfo').id;
			}
			if (req.getStorage('MERCHANT') && req.getStorage('MERCHANT').id != null) {
				path += '&merchantId=' + req.getStorage('MERCHANT').id;
		
				if (req.getStorage('smallShop') && req.getStorage('MERCHANT').id != null) {
					path += '&shopId=' + req.getStorage('smallShop').id;
				}
			}
			if(this.query.id){
				path += '&id=' + this.query.id
			}
			if(this.query.attr){
				path += '&attr=' + this.query.attr
			}
			if(this.query.title){
				path += '&title=' + this.query.title
			}
			if(this.query.searchTitle){
				path += '&searchTitle=' + this.query.searchTitle
			}
			let title = '';
			if (this.merchant && this.merchant.title && this.merchant.title != '默认门店') {
				title = this.merchant.title;
			} else {
				title = this.about.CONFIG_PROJECT_TITLE;
			}
			console.log(title);
			// console.log(path);
			return {
				title: (req.excludeSpecial(req.getStorage('userInfo').nickName) ? req.excludeSpecial(req.getStorage('userInfo').nickName) : '') + '为你推荐' + title,
				// imageUrl: this.data.seckill[0].pic
				// path: '/product/detail/detail?id=' + this.query.id + '&isShare=' + true + '&userId=' + req.getStorage('userInfo').id
				path: path
			};
		},
		onShareTimeline() {
			let path = 'isShare=' + true;
			if (req.getStorage('userInfo')) {
				path += '&userId=' + req.getStorage('userInfo').id;
			}
			if (req.getStorage('MERCHANT') && req.getStorage('MERCHANT').id != null) {
				path += '&merchantId=' + req.getStorage('MERCHANT').id;
		
				if (req.getStorage('smallShop') && req.getStorage('MERCHANT').id != null) {
					path += '&shopId=' + req.getStorage('smallShop').id;
				}
			}
			if(this.query.id){
				path += '&id=' + this.query.id
			}
			if(this.query.attr){
				path += '&attr=' + this.query.attr
			}
			if(this.query.title){
				path += '&title=' + this.query.title
			}
			if(this.query.searchTitle){
				path += '&searchTitle=' + this.query.searchTitle
			}
			let title = '';
			if (this.merchant && this.merchant.title && this.merchant.title != '默认门店') {
				title = this.merchant.title;
			} else {
				title = this.about.CONFIG_PROJECT_TITLE;
			}
			// console.log(path);
			return {
				title: (req.excludeSpecial(req.getStorage('userInfo').nickName) ? req.excludeSpecial(req.getStorage('userInfo').nickName) : '') + '为你推荐' + title,
				// imageUrl: this.data.seckill[0].pic
				// path: '/product/detail/detail?id=' + this.query.id + '&isShare=' + true + '&userId=' + req.getStorage('userInfo').id
				query: path
			};
		},
	};
</script>
<style>
	@import "./list.css";
</style>
