<template>
	<view>
		<!-- 顶部按钮 -->
		<view class="search-wrap" :style="{'top': `${statusBarHeight + 10}px`}"><u-icon name="search" color="#FFFFFF" size="44"  @click="onClickSearch"></u-icon></view>
		<!-- 优选内容 -->
		<swiper class="swiper" @change="change" :style="'height:' + swiperHeight + 'px' " v-if="goodsList && goodsList.length" vertical>
			<block v-for="(goodsItem, index) in goodsList">
				<swiper-item :key="goodsItem.goods.goods_id" :item-id="(goodsItem.goods.video_list && goodsItem.goods.video_list[0] && goodsItem.goods.video_list[0].playUrl ? 'video' : 'img') + '&&' + goodsItem.goods.goods_id">
					<block v-if="loadLazyData.filter((v)=>{return v== index}).length > 0">
					<!-- 视频 -->
					<!-- <videoPlayer  :ref="'player' + goodsItem.goods.goods_id" v-if="goodsItem.goods.video_list && goodsItem.goods.video_list[0] && goodsItem.goods.video_list[0].playUrl" :video_info="goodsItem.goods.video_list[0]" :goods_id="goodsItem.goods.goods_id" :imgSwiperGoodsId="imgSwiperGoodsId"></videoPlayer> -->
					<view class="video-wrap" v-if="goodsItem.goods.video_list && goodsItem.goods.video_list[0] && goodsItem.goods.video_list[0].playUrl">
						<image class="filterBgImg" :src="goodsItem.goods.video_list[0].imageUrl"></image>
						<video class="myVideo" :style="{height: `${100 * goodsItem.goods.video_list[0].high / goodsItem.goods.video_list[0].width}vw`}" @click="clickVideo" @play="changePlay" :id="'myVideo'+ goodsItem.goods.goods_id" :poster="goodsItem.goods.video_list[0].imageUrl" :src="goodsItem.goods.video_list[0].playUrl" :loop="true"></video>
					</view>

					<swiper :key="goodsItem.goods.goods_id + 'img_swiper'"  class="goods-item-img-swiper" v-else circular :autoplay="imgSwiperGoodsId == goodsItem.goods.goods_id ? true : false">
						<swiper-item v-for="(img, idx_img) in goodsItem.goods.img_list" :key="idx_img + '&' + goodsItem.goods.goods_id">
							<image class="filterBgImg" :src="img.url"></image>
							<image class="img" :src="img.url" mode="widthFix"></image>
						</swiper-item>
					</swiper>
					<!-- S 商品信息 -->
					<view class="info-wrap">
						<view @click="onClickGoodsItem(goodsItem.goods)">
						  <view class="tp-wrap">
							<view class="lt-wrap">
							  <text class="price-title">{{goodsItem.goods.is_coupon == 1 && goodsItem.goods.coupon_price > 0 ? '券后价' : '' }} ¥</text>
							  <text class="price">{{ goodsItem.goods.discount_price }}</text>
							  <text class="price-old">￥{{ goodsItem.goods.price }}</text>
							</view>
							<view class="rt-wrap">
								<view class="salesVolume" v-if="goodsItem.goods.volume > 100">
									月销:{{ $NumberHandle({value:goodsItem.goods.volume,comma:true}) }}+
								</view>
							</view>
						  </view>
						  <view class="bm-wrap">
							<image class="shop-icon" v-if="goodsItem.goods.shop_type == 0" src="https://ld.726p.com/ldyx_static/imgs/icon-tb.png" />
							<image class="shop-icon" v-else-if="goodsItem.goods.shop_type == 1" src="https://ld.726p.com/ldyx_static/imgs/icon-tmall.png" />
							<image class="shop-icon" v-else-if="goodsItem.goods.shop_type == 4" src="https://ld.726p.com/ldyx_static/imgs/jd-icon.png" />
							{{ goodsItem.goods.title }}
						  </view>
						  <view class="btm-wrap">
							  <view class="flex">
								<view v-if="goodsItem.goods.coupon_price > 0" class="coupon-wrap">
								  <text class="label">券</text>
								  <text class="value">¥{{ goodsItem.goods.coupon_price }}</text>
								</view>
								<view v-if="user_level > 1 && goodsItem.goods.commission_price > 0" class="coupon-wrap commission-wrap">
								  <text class="label">返</text>
								  <text class="value">¥{{ goodsItem.goods.commission_price }}</text>
								</view>
							  </view>
							<view class="goDetail">
								<text>详情</text>
								<u-icon name="arrow-right" color="#FB3F3C" size="26"></u-icon>
							</view>
						  </view>
					  </view>
					  <!-- 底部按钮 -->
						<view class="footer-wrap" :style="{ 'padding-bottom': isIphoneX ? '66rpx' : '22rpx' }">
							<view class="btn-collect-wrap" v-if="goodsItem.goods.is_favorites == 1" @click="onClickSetFavorites({index: index, goodsItem: goodsItem.goods})">
							  <image class="btn-collect-img" src="https://ld.726p.com/ldyx_static/imgs/icon-collect-on.png" />
							  <text class="btn-collect-text">已收藏</text>
							</view>
							<view class="btn-collect-wrap" v-else @click="onClickSetFavorites({index: index, goodsItem: goodsItem.goods})">
							  <image class="btn-collect-img" src="https://ld.726p.com/ldyx_static/imgs/icon-collect.png" />
							  <text class="btn-collect-text">收藏</text>
							</view>
						  <!-- 已登录按钮 -->
						  <view v-if="isLogin" class="btn-wrap">
							<view class="btn-item lt-btn" @click="onClickFXZQ(goodsItem.goods)">
							  <text class="btn-text">{{ user_level == 1 ? '分享' : '分享赚钱' }}</text>
							</view>
							<view class="btn-item rt-btn" @click="onClickGWSQ({index: index, goods_id: goodsItem.goods.goods_id})">
							  <text class="btn-text">购物省钱</text>
							</view>
						  </view>
						  <!-- 未登录按钮 -->
						  <view v-else class="btn-wrap">
							<view class="btn-item lt-btn" @click="onClickGWSQ({index: index, goods_id: goodsItem.goods.goods_id})">
							  <text class="btn-text">直接购买</text>
							</view>
						    <view class="btn-item rt-btn" @click="onClickFYJGM({index: index, goods_id: goodsItem.goods.goods_id})">
						      <text class="btn-text">返佣金购买</text>
						    </view>
						  </view>
						</view>
					</view>
					<!-- E 商品信息 -->
					</block>
				</swiper-item>
			</block>
		</swiper>
</view>
</template>
<script>
	const app = getApp()
	export default {
		data() {
			return {
				statusBarHeight: app.globalData.statusBarHeight,
				navbarBackground: {
					backgroundColor: 'transparent'
				},
				user_level: uni.getStorageSync('userInfo') ? uni.getStorageSync('userInfo').user_level : '', // 当前用户等级
				filter: {
					page: 1,
					page_size: 20,
					nowTotal: 0,
					hasNext: true,
				},
				goodsList: [], // 商品列表数据
				swiperHeight: '800', // swiper的高度
				imgSwiperGoodsId: '', //图片轮播ID，判断是否自动轮播
				play: false,
				loadLazyData: [-1,0,1], //懒加载数据ID，显示3张数据，上中下
				elite_id: 2,
				isLogin:false
			}
		},
		onShow(){
			const userInfo = uni.getStorageSync('userInfo') || ''
			const user_id = uni.getStorageSync('user_id') || ''
			this.user_level = uni.getStorageSync('userInfo') ? uni.getStorageSync('userInfo').user_level : ''; // 当前用户等级
			if (userInfo && user_id) {
			  this.isLogin = true
			} else {
			  this.isLogin = false
			}

			if (uni.getStorageSync('loginPageBack')){
				// 获取商品详情数据
				this.handleGetGoodsList()
				uni.setStorageSync('loginPageBack',false)
			}
		},
		onLoad() {
			this.swiperHeight = `${uni.getSystemInfoSync().windowHeight}`;
			this.handleGetGoodsList()
		},
		methods: {
      onClickSearch() {
        uni.navigateTo({
          url: '/pages/subPackages/home/search',
        })
      },
			// 监听点击“返佣金购买” => 跳登录页面
			onClickFYJGM() {
			  uni.navigateTo({
			    url: '/pages/subPackages/login/loginPhone'
			  })
			},
			// 监听点击“分享赚钱” => 判断是否授权(京东商品不需要授权) => 生成图片 => 分享图片
			onClickFXZQ(goodsItem) {
			  uni.navigateTo({
			    url: `/pages/subPackages/home/shareDetail?shop_type=${goodsItem.shop_type}&goods_id=${encodeURIComponent(goodsItem.goods_id)}`
			  })
			},
			// 监听点击“购物省钱” => 判断是否授权(京东商品不需要授权) => 获取口令 => 复制口令
			onClickGWSQ({index, goods_id}) {
				if (this.goodsList[index].goods.weChatShortLink) { // 列表中存在weChatShortLink 从列表中取
					wx.navigateToMiniProgram({
						'shortLink': this.goodsList[index].goods.weChatShortLink
					})
				} else {// 列表中不存在weChatShortLink，调详情接口，并负值给列表
					this.handleGetgoodsItem(goods_id).then((data)=>{
						if (data.url_info && data.url_info.weChatShortLink) {
							wx.navigateToMiniProgram({
								'shortLink': data.url_info.weChatShortLink
							})
							this.goodsList[index].goods.goods_id == goods_id ? this.goodsList[index].goods.weChatShortLink = data.url_info.weChatShortLink : '';
						} else {
							uni.showToast({ title: '购买失败！', icon: 'none' })
						}
					}).catch(()=>{
						uni.showToast({ title: '购买失败！', icon: 'none' })
					})
				}
			 },
			// 获取商品详情数据
			handleGetgoodsItem(goods_id) {
				return new Promise(async (resolve,reject)=>{
					try {
					  uni.showLoading({ title: '加载中...', mask: true })
					  const url = this.$api_jd.goods_detail
					  const params = { goods_id: goods_id.toString() }
					  const { data: res = {} } = await this.$postJSON(url, params)
					  if (res && res.errno == 0 && res.rst.data) {
						resolve(res.rst.data)
					  } else {
						reject(false)
					    uni.showToast({ title: res.err || '操作失败', icon: 'none' })
					  }
					} catch (error) {
						reject(false)
					} finally {
					  uni.hideLoading()
					}
				})
			},
			// 监听点击收藏
			onClickSetFavorites({goodsItem,index}) {
			  if (!this.isLogin) { // 未登录 => 去登录
			    uni.navigateTo({
			      url: '/pages/subPackages/login/loginPhone'
			    })
			  } else {
			    this.handleSetFavorites({goodsItem,index})
			  }
			},
			async handleSetFavorites({goodsItem,index}) {
			  const { goods_id, is_coupon, discount_price, price, coupon_price, commission_rate, coupon_end_time, coupon_start_time, shop_type } = goodsItem
			  try {
			    uni.showLoading({ title: '加载中...', mask: true })
			    const url = this.$api.goodsItem_addFavorites
			    const params = { goods_id, is_coupon, discount_price, price, coupon_price, commission_rate, coupon_end_time, coupon_start_time, shop_type }
			    const { data: res } = await this.$postJSON(url, params)
			    if (res && res.errno == 0) {
			      // 设置成功 => 更新状态
				  this.goodsList[index].goods.is_favorites = this.goodsList[index].goods.is_favorites == 1 ? 0 : 1;
			    } else {
			      uni.showToast({ title: res.err || '操作失败', icon: 'none' })
			    }
			  } catch (error) {
			    console.log('error => ', error)
			  } finally {
			    uni.hideLoading()
			  }
			},
			onClickGoodsItem(goodsItem) {
				try{ app.categoryNew_countBuy({shop_type: goodsItem.shop_type, type:0,path:'jd_optimization',category_id:this.elite_id}) }catch(e){} ; // 数据上报
				uni.navigateTo({
				  url: `/pages/subPackages/home/jdGoodsDetail?goods_id=${encodeURIComponent(goodsItem.goods_id)}`
				})
			},
			change(res) {
				let currentItemId = res.detail.currentItemId;
				// 懒加载数据改变
				let current = res.detail.current;
				this.loadLazyData = [current - 1, current, current + 1];
				// 判断是否加载到倒数第二个数据，如果是，则分页加载下一页
				if (this.loadLazyData[2] == this.filter.nowTotal - 1) {
					if (!this.filter.hasNext) {
						uni.showToast({
							title: '没有更多了',
							icon: 'none'
						})
						return false;
					}
					this.filter.page++;
					this.handleGetGoodsList()
				}
				// 关闭之前的视频
				let oldVideoContext = uni.createVideoContext("myVideo" + this.imgSwiperGoodsId, this);
				oldVideoContext && oldVideoContext.pause ? oldVideoContext.pause() : '';
				this.play = false;
				// 滑动到的商品ID
				this.imgSwiperGoodsId = currentItemId.split('&&')[1];
				// 页面是视频，则播放视频
				if (currentItemId.split('&&')[0] == 'video') {
					this.playVideo()
				}
			},
			clickVideo() {
				if (!this.play) {
					this.playthis()
				} else {
					this.pauseVideo()
				}
			},
			playVideo() {
				let nowVideoContext = uni.createVideoContext("myVideo" + this.imgSwiperGoodsId, this);
				if (this.play === false) {
					nowVideoContext.seek(0)
					nowVideoContext.play()
					this.play = true
				}
			},
			pauseVideo() {
				let nowVideoContext = uni.createVideoContext("myVideo" + this.imgSwiperGoodsId, this);
				if (this.play === true) {
					nowVideoContext.pause()
					this.play = false
				}
			},
			playthis() {
				let nowVideoContext = uni.createVideoContext("myVideo" + this.imgSwiperGoodsId, this);
				if (this.play === false) {
					nowVideoContext.play()
					this.play = true
				}
			},
			changePlay() {
				this.play = true
			},
			// 获取商品获取商品列表数据列表
			async handleGetGoodsList() {
				if (!this.filter.hasNext) return false
				try {
					if (this.filter.page == 1) {
						uni.showLoading({ title: '加载中...', mask: true })
					}
					const url = this.$api_jd.jd_goodsListByEliteId
					const params = {
						elite_id: this.elite_id,
						page: this.filter.page,
						page_size: this.filter.page_size
					}
					const { data: res = {} } = await this.$postJSON(url, params)
					if (res && res.errno == 0 && Array.isArray(res.rst.data)) {
						if (!res.rst.data.length) { // 当前页无数据 => 更改下一页标识
							this.filter.hasNext = false
						}
						if (!Array.isArray(res.rst.data)) return;
						let res_data = res.rst.data;
						res_data = res_data.filter((v) => { // 排除不可用数据
							return v.goods
						})
						this.goodsList = [...this.goodsList, ...res_data];
						this.filter.nowTotal = this.goodsList.length;
						this.$nextTick(()=>{ // 初始化时，如果第一个数据是视频，则播放视频
							if (!Array.isArray(this.goodsList) || this.goodsList.length <= 0) return;
							if (this.filter.page == 1) {
								let good = this.goodsList[0].goods;
								this.imgSwiperGoodsId = good.goods_id;
								if (good && good.video_list && good.video_list[0] && good.video_list[0].playUrl) {
									this.playthis()
								}
							}
						})
					} else {
						uni.showToast({
							title: res.err || '操作失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.log('error => ', error)
				} finally {
					uni.hideLoading()
				}
			},
		}
	}
</script>
<style scoped lang="scss">
	.search-wrap{
		position: fixed;
		left: 38rpx;
		top: 80rpx;
		z-index: 9;
	}
	.goods-item-img-swiper{
		width: 100%;
		height: 100%;
		position: relative;
		z-index: -1;
		.img{
			width: 100%;
			position: absolute;
			top:0;
			bottom:0;
			margin:auto;
		}
	}
	.filterBgImg{
		width: 100%;
		height: 100%;
		position: absolute;
		top: 0;
		left: 0;
		filter: blur(45px)
	}
	.video-wrap{
		width:100%;
		height:100%;
		position: relative;
		z-index: -1;
		.myVideo{
			width:100vw;
			height: 100vw;
			position: absolute;
			top:0;
			bottom:0;
			margin:auto;
		}
	}
	.swiper {
		width: 100%;
		height: 1180rpx;
		margin: auto;
	}
	.info-wrap {
		width: 90vw;
		position: absolute;
		bottom: 20rpx;
		left: 0;
		right: 0;
		margin:auto;
		background-color: #FFFFFF;
		padding: 10rpx 20rpx 0;
		border-radius: 20rpx;
		z-index: 9999;
	  .tp-wrap {
	    display: flex;
	    align-items: center;
	    justify-content: space-between;
	    .lt-wrap {
	      display: flex;
	      align-items: baseline;
			.price-title{
				color: #FF4040;
				font-size: 28rpx;
				line-height: 40rpx;
			}
	      .price {
	        font-size: 38rpx;
	        color: #FF4040;
			  font-weight: bold;
			  line-height: 40rpx;
			  margin-left: 10rpx;
	      }
	      .price-old {
	        margin-left: 10rpx;
	        font-size: 24rpx;
			line-height: 30rpx;
	        text-decoration: line-through;
	        color: #999999;
	      }

	    }
	    .rt-wrap {
	      display: flex;
	      align-items: center;
	      .btn-wrap {
	        display: flex;
	        align-items: center;
	        .btn-img {
	          width: 32rpx;
	          height: 32rpx;
	        }
	        .btn-text {
	          font-size: 25rpx;
	          color: #999;
	        }
	      }
	    }
	  }
	  .bm-wrap {
	    margin-top: 3rpx;
	    font-size: 28rpx;
		font-weight: bold;
		line-height: 36rpx;
	    color: #333333;
	    .shop-icon {
	      margin-right: 6rpx;
	      width: 30rpx;
	      height: 30rpx;
			margin-top: -4rpx;
	      border-radius: 4rpx;
	      vertical-align: middle; // 解决图片下边框缝隙问题
	    }
	  }
		.btm-wrap {
		    display: flex;
		    align-items: center;
			justify-content: space-between;
		    margin-top: 9rpx;
		    .coupon-wrap {
		      display: flex;
		      align-items: center;
		      width: 130rpx;
		      height: 34rpx;
		      background-image: url("https://ld.726p.com/ldyx_static/imgs/bg-quan-small.png");
		      background-repeat: no-repeat;
		      background-size: 100% 100%;
		      color: #FF4040;
		      font-size: 22rpx;
		  	 line-height: 34rpx;
		      .label {
		        width: 40rpx;
		        text-align: center;
		      }
		      .value {
		        flex: 1;
		        text-align: center;
		      }
		    }
			.goDetail{
				color: #FF4040;
				font-size: 26rpx;
				font-weight: bold;
			}
			.commission-wrap {
				background-image: url("https://ld.726p.com/ldyx_static/imgs/fan.png");
				color: #AE4300;
				margin-left: 12rpx;
			}
		}
	}
	.footer-wrap {
		// background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 86rpx;
		padding: 20rpx;
		border-top: 1rpx solid #eee;
		margin-top: 10rpx;
	  .btn-wrap {
		  flex:1;
	    background-color: #FFBB93;
	    display: flex;
	    align-items: center;
		height: 64rpx;
	    border-radius: 64rpx;
	    overflow: hidden;
	    .btn-item {
	      height: 100%;
	      flex: 1;
	      display: flex;
	      justify-content: center;
	      align-items: center;
	      .btn-icon {
	        margin-right: 10rpx;
	      }
	      .btn-text {
	        color: #fff;
	        font-size: 28rpx;
			  font-weight: bold;
			  line-height: 64rpx;
	      }
	      &.lt-btn {
	        .btn-icon {
	          width: 42rpx;
	          height: 38rpx;
	        }
	      }
	      &.rt-btn {
				background: linear-gradient(90deg, #FF9048 0%, #FB3F3C 100%);
				border-radius: 42rpx;
	        .btn-icon {
	          width: 42rpx;
	          height: 44rpx;
	        }
	      }
	    }
	  }
	}
	.btn-collect-wrap{
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-right: 28rpx;
		.btn-collect-img{
			width: 34rpx;
			height: 34rpx;
		}
		.btn-collect-text{
			color: #666666;
			font-size: 22rpx;
			line-height: 28rpx;
		}
	}
	.salesVolume{
		background: url('https://ld.726p.com/ldyx_static/imgs/huo-bg.png') no-repeat;
		background-size: 100%;
		width: 200rpx;
		line-height: 28rpx;
		color: #FF4040;
		font-size: 24rpx;
		line-height: 54rpx;
		text-align: center;
		padding-left: 16rpx;
	}
	.swiper-list {
		margin-top: 40rpx;
		margin-bottom: 0;
	}
	.uni-common-mt {
		margin-top: 60rpx;
		position: relative;
	}
	.info {
		position: absolute;
		right: 20rpx;
	}
	.uni-padding-wrap {
		width: 550rpx;
		padding: 0 100rpx;
	}
	.flex{
		display: flex;
		align-items: center;
	}
</style>
