<template>
	<view class="pages">
		<u-navbar
			title="产品详情"
			:placeholder="true"
			:autoBack="false"
			@leftClick="leftClick"
			 :safeAreaInsetTop="true"
		>
		</u-navbar>
		<u-loading-page :loading="loadingPage" bgColor="#f1f1f1"></u-loading-page>
		 <u-swiper
			v-if="details.slideImgList.length>0"
			:list="details.slideImgList"
			height="700rpx"
			@change="e => currentNum = e.current"
			:autoplay="false"
			indicatorStyle="right: 20px"
		>
			<view
				slot="indicator"
				class="indicator-num"
			>
				<text class="indicator-num__text">{{ currentNum + 1 }}/{{ details.slideImgList.length }}</text>
			</view>
		</u-swiper>
		<view class="product-info view-wrap">
			<view class="red">
				<view class="u-flex">
					<text class="price">¥ <text class="price-num">{{details.vipPrice}}</text></text>
					<text class="price-type" style="margin-left: 20rpx;">会员价</text>
					<!-- <text class="vip-icon">VIP</text> -->
					<view class="exchangeCredit u-flex" v-if="details.isCredit==1">
						+{{details.exchangeCredit}} 
						<text style="font-size: 30rpx;">积分</text>
					</view>
				</view>
				<!-- <view class="" v-else>
					<text v-if="details.isCredit==1&&details.exchangeType==0" class="price">¥ <text class="price-num">0</text></text>
					<text v-else class="price">¥ <text class="price-num">{{details.salePrice}}</text></text>
					<text class="exchangeCredit" v-if="details.isCredit==1">+{{details.exchangeCredit}}积分</text>
				</view> -->
			</view>
			<view class="u-flex u-row-between gray">
				<text class="line-through">¥ <text class="">{{details.salePrice}}</text></text>
				<text class="">库存 {{details.stock}}</text>
			</view>
			<view class="name">{{details.goodsName}}</view>
		</view>
		<view class="specification info-line u-flex view-wrap" v-if="details.specification">
			<view class="info-til">规格</view>
			<view class="info-con u-flex">{{details.specification}}</view>
		</view>
		<view class="addr view-wrap">
			<view class="addr-line u-flex">
				<view class="info-til">提货方式</view>
				<view class="info-con u-flex">
					<text v-for="(item,index) in logisticsType" :key="index">
						{{item|filterLogisticsType}} 
						<text style="margin: 0 5px;" v-if="index<logisticsType.length-1">/</text>
					</text>
				</view>
			</view>
			<view class="addr-line u-flex" v-if="details.period">
				<view class="info-til">保质期</view>
				<view class="info-con u-flex">
					{{details.period|filterPeriod}}
				</view>
			</view>
			<!-- <view class="addr-line u-flex">
				<text class="addr-til">送至</text>
				<view class="addr-con u-flex u-flex-1">
					<view class="u-flex u-row-between u-flex-1">
						<text>贵阳市 南明区</text>
						<u-icon name="arrow-right" color="#676767" size="20"></u-icon>
					</view>
				</view>
			</view> -->
		</view>
		<view class="comment view-wrap u-flex u-row-between">
			<view class="left">
				<text class="til">评价</text>
				<text class="num">({{details.commentNum}})</text>
			</view>
			<view class="right u-flex" @click="$u.route('/shopping/comment',{id:details.id})">
				<text>查看全部</text>
				<u-icon name="arrow-right" color="#676767" size="20"></u-icon>
			</view>
		</view>
		<view class="detail view-wrap">
			<view class="til">详情</view>
			<view class="con">
				<!-- <view class="" v-html="details.detail"></view> -->
				<u-parse :content="details.detail"></u-parse>
				<!-- {{details.detail}} -->
			</view>
		</view>
		<view class="details-tool-wrap">
			<view class="details-tool u-flex u-row-between">
				<view class="left u-flex">
					<view class="icon-wrap" @click="openShare">
						<u-icon name="share" color="#676767" size="30"></u-icon>
						分享
						<!-- <button class="share-btn" data-name="shareBtn" open-type="share">
							<u-icon name="share" color="#676767" size="30"></u-icon>
							分享
						</button> -->
					</view>
					<view class="icon-wrap" v-if="details.isCredit!=1"  @click="$u.route('/shopping/cart')">
						<u-icon name="shopping-cart" color="#676767" size="30"></u-icon>
						购物车
						<u-badge class="badge" numberType="overflow" type="error " max="99" :value="cartTotal" :absolute="true" :offset="[0,0]"></u-badge>
					</view>
				</view>
				<view class="right" v-if="details.stock>0">
					<view class="u-flex" v-if="details.isCredit==1">
						<view class="btn add-btn" @click="addCreditOrder(details.id)">立即兑换</view>
					</view>
					<view class=" u-flex" v-else>
						<view class="btn add-btn" @click="addCart(details.id)">加入购物车</view>
						<view class="btn buy-btn" @click="buyNow(details.id)">立即购买</view>
					</view>
				</view>
				<view class="right" v-else>
					<view class="btn gray">暂无库存</view>
				</view>
				
			</view>
		</view>
		
		<!-- 分享选择弹出内容 -->
		<view class="share-option" :class="{shareShow:shareShow}">
			<view class="overlay" v-if="shareShow"  @click="shareShow=false"></view>
			<button class="share-option-item wx-share" data-name="shareBtn" open-type="share">
				发送给朋友
			</button>
			<view class="share-option-item" @click="getPoster">生成海报</view>
			<view class="share-option-item" @click="shareShow=false">取消</view>
		</view>
		<u-popup :show="posterShow" @close="posterShow=false" ref="uni-popup">
			<view class="poster-wrap u-flex u-col-center">
				<view class="poster-inner">
					<view class="close-wrap" @click="posterShow=false">
						<u-icon name="close-circle" color="#fff" size="56rpx"></u-icon>
					</view>
					<view class="poster" id="poster" ref="poster" >
						<u--image :showLoading="true" :src="posterSrc" width="100%" height="65vh" mode="aspectFit"></u--image>
					</view>
					<!-- savePoster -->
					<view class="poster-btn" @click="saveImage">保存图片</view>
				</view>
			</view>
		</u-popup>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	export default {
		components: {
			
		},
		data() {
			return {
				staticUrl:this.$commonConfig.staticUrl,
				loadingPage:true,
				id:'',
				cartTotal:0,
				currentNum:0,
				swiperList: [],
				details:{
					slideImgList:[]
				},
				hasAddr:false,
				shareShow:false,
				posterShow:false,
				mode:'aspectFill',
				wxml:'',
				posterStyle:{},
				posterSrc:'',
				logisticsType:[],
			}
		},
		onLoad(page) {
			this.id = page.id;
			if(page.goodsId){
				this.id = page.goodsId;
			}
			const scene = decodeURIComponent(page.scene);
			scene&&uni.setStorage({
				key:'scene',
				data:scene
			});
			// console.log('this.id',this.id);
			this.getDetails(this.id);
		},
		onShow(){
			if(this.vuex_member_info.name){
				this.getCartList();
				this.getAddrList();
				this.goodsAddView(this.id)
			}
		},
		methods: {
			leftClick(e){
				let pages = getCurrentPages();
				if(pages.length==1){
					uni.$u.route('/pages/index/index')
				}else{
					uni.navigateBack()
				};
			},
			getCartList(isAdd){
				this.$u.api.cartList().then(res=>{
					if(isAdd){
						if(res.data.total==this.cartTotal){
							this.$refs.uToast.show({
								type:"success",
								message:'已在购物车'
							});
						}						
					}
					this.cartTotal = res.data.total;
					console.log('getCartList',res);
					}).catch(err=>{
					console.log('getCartList',err.data);
				})
			},
			getDetails(id){
				this.$u.api.memberGoodDetails({id:id}).then(res=>{
					this.loadingPage = false;
					// console.log('res',res.data);
					this.details = res.data;
					this.logisticsType =  res.data.logisticsType?.split(",")||[];
					if(!res.data.slideImgList&&res.data.mainImg){
						this.details.slideImgList = [];
						this.details.slideImgList.push(res.data.mainImg)
					}
				}).catch(err=>{
					console.log('getDetails',err.data);
				})
			},
			goodsAddView(id){
				this.$u.api.goodsAddView({id:id}).then(res=>{
					// console.log('res',res.data);
				}).catch(err=>{
					console.log('goodsAddView',err.data);
				})
			},
			async addCart(id,buyNow){
				// 检测是否登录
				if (!this.checkLogin()) {
					return;
				}
				try {
					let authResult = await this.checkAuth();
					console.log('实名认证结果：', authResult);
					// 在此处可以继续执行需要进行实名认证的业务逻辑
					// 例如下单购买商品等操作
				} catch (err) {
					console.log('实名认证未通过：', err);
					return
					// 在此处可以处理用户未通过实名认证的情况
					// 例如返回上一页或者跳转到实名认证页等操作
				}
				this.checkAuth();
				this.$u.api.addCart({goodsId:id}).then(res=>{
					this.$refs.uToast.show({
						type:"success",
						message:res.msg
					});
					if(buyNow){
						uni.$u.route('/shopping/cart', {
							buyNowId: id,
							buyNowName:this.details.goodsName
						});
					}
					this.getCartList('isAdd');
					console.log('res',res.data);
					}).catch(err=>{
					console.log('addCart',err);
				})
			},
			checkLogin() {
			    if (!this.vuex_member_info.name) {
			        let that = this;
			        let pageUrl = encodeURIComponent(`shopping/productdetails?id=${that.id}`);
			        uni.showModal({
			            title: '提示',
			            content: '你需要登录后,才可使用此功能！',
			            success: res => {
			                if (res.confirm) {
			                    uni.setStorage({
			                        key: 'backUrl',
			                        data: pageUrl,
			                        success: function () {
			                            uni.$u.route('/pages/login/login')
			                        }
			                    });
			                }
			            }
			        });
			        return false;
			    }
			    return true;
			},
			openShare(){
				// 检测是否登录
				// if (!this.checkLogin()) {
				// 	return;
				// }
				this.shareShow = true;
			},
			async buyNow(id){
				// 检测是否登录
				if (!this.checkLogin()) {
				    return;
				}
				try {
					let authResult = await this.checkAuth();
					console.log('实名认证结果：', authResult);
					// 在此处可以继续执行需要进行实名认证的业务逻辑
					// 例如下单购买商品等操作
				} catch (err) {
					console.log('实名认证未通过：', err);
					return
					// 在此处可以处理用户未通过实名认证的情况
					// 例如返回上一页或者跳转到实名认证页等操作
				}
				// this.addCart(id,'buyNow')//跳购物车
				if(!this.hasAddr){
					uni.showModal({
						title: '温馨提示',
						content: '请先设置地址！',
						success: res => {
							if (res.confirm) {
								let url = encodeURIComponent(`/shopping/productdetails?id=${that.id}`) ;
								uni.$u.route('/center/addrlist', {
									from: 'productdetails',
									backUrl:url
								});
							}
						}
					})
					return
				}
				this.$u.vuex('buyNowGoods',[{goodsId:this.id,quantity:1}]);
				uni.$u.route('/shopping/submitorder', {fromPage: 'productdetails'});
			},
			async addCreditOrder(id){
				// 检测是否登录
				if (!this.checkLogin()) {
					return;
				}
				try {
					let authResult = await this.checkAuth();
					console.log('实名认证结果：', authResult);
					// 在此处可以继续执行需要进行实名认证的业务逻辑
					// 例如下单购买商品等操作
				} catch (err) {
					console.log('实名认证未通过：', err);
					return
					// 在此处可以处理用户未通过实名认证的情况
					// 例如返回上一页或者跳转到实名认证页等操作
				}
				let that = this;
				let creditGoods = [];
				creditGoods.push({id:that.details.id,quantity:1})
				// console.log('creditGoods',creditGoods);
				that.$u.vuex('cartGoods',creditGoods);
				uni.$u.route('/shopping/submitorder', {fromPage:'creditOrder'});
			},
			onShareAppMessage: function( options ){
			  var that = this;
			  // 设置菜单中的转发按钮触发转发事件时的转发内容
			  var shareObj = {
			    title: this.details.goodsName,    // 默认是小程序的名称(可以写slogan等)
			    path: '/shopping/productdetails',    // 默认是当前页面，必须是以‘/'开头的完整路径
			    imageUrl: '',   //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
			    success: function(res){
			      // 转发成功之后的回调
			      if(res.errMsg == 'shareAppMessage:ok'){
			      }
			    },
			    fail: function(){
			      // 转发失败之后的回调
			      if(res.errMsg == 'shareAppMessage:fail cancel'){
			        // 用户取消转发
			      }else if(res.errMsg == 'shareAppMessage:fail'){
			        // 转发失败，其中 detail message 为详细失败信息
			      }
			    },
				complete:function(){
					 // 转发结束之后的回调（转发成不成功都会执行）
				}
			  };
			  // 来自页面内的按钮的转发
			  if( options.from == 'button' ){
			    var eData = options.target.dataset;
				console.log('options.target.dataset',options.target.dataset);
			    console.log('id' ,this.details.id);   // shareBtn
			    // 此处可以修改 shareObj 中的内容
			    shareObj.path = '/shopping/productdetails?id='+this.details.id;
			  }
			  // 返回shareObj
			  return shareObj;
			},
			getAddrList(){
				this.$u.api.addrList().then(res=>{
					// this.dataList = res.data.rows;
					console.log('getAddrList',res);
					if( res.data.total>0){
						this.hasAddr = true;
					}else{
						this.hasAddr = false;
					}
				}).catch(err=>{
					console.log('getAddrList',err.data);
				})
			},
			checkAuth() {
				// console.log('details-----',this.details);
				let that = this;
			    return new Promise((resolve, reject) => {
			        console.log('vuex_member_info', this.vuex_member_info.isAuth);
			        if (that.details.isBuy!=1&&that.details.isAuth==1) {
			            uni.showModal({
			                title: '温馨提示',
			                content: '购买该商品需要实名认证，请先实名认证！',
			                success: res => {
			                    if (res.confirm) {
			                        let url = encodeURIComponent(`/shopping/productdetails?id=${that.id}`);
			                        uni.$u.route('/center/factorauth', {
			                            from: 'productdetails',
			                            backUrl: url
			                        });
			                        reject('needAuth'); // 实名认证未通过，使用 reject 方法返回结果
			                    }
			                }
			            });
			        } else {
			            resolve('noNeedAuth'); // 实名认证已通过，使用 resolve 方法返回结果
			        }
			    });
			},
			// 海报相关开始
			getPoster(){
				this.posterShow = true;
				this.shareShow = false;
				this.$u.api.getPoster({goodsId:this.id}).then(res=>{
					this.posterSrc = res.data.imageUrl;
					// console.log('getPoster',res.data);
				}).catch(err=>{
					console.log('getPoster',err);
				})
			},
			saveImage() {
				let that = this;
					uni.showLoading({
						title: '保存中'
					});
			      uni.downloadFile({
			        url: this.posterSrc,
			        success(res) {
			          if (res.statusCode === 200) {
			            uni.saveImageToPhotosAlbum({
			              filePath: res.tempFilePath,
			              success() {
			                uni.showToast({
			                  title: '保存到相册成功',
			                  icon: 'success'
			                });
			              },
			              fail(err) {
							  console.log('保存图片失败',err);
			                if (err.errMsg === 'saveImageToPhotosAlbum:fail auth deny') {
								uni.getSetting({
								  success(res) {
									if (!res.authSetting['scope.writePhotosAlbum']) {
									  uni.showModal({
										title: '提示',
										content: '您还没有授权访问相册，请前往设置页面打开权限。',
										confirmText: '去设置',
										success(res) {
										  if (res.confirm) {
											uni.openSetting();
										  }
										}
									  });
									} else {
									  uni.showToast({
										title: '保存图片失败',
										icon: 'none'
									  });
									}
								  }
								});
							  } else {
								uni.showToast({
								  title: '保存图片失败',
								  icon: 'none'
								});
							}
			              },
						  complete() {
						  	uni.hideLoading();
							that.posterShow = false;
						  }
			            });
			          } else {
			            uni.showToast({
			              title: '下载图片失败',
			              icon: 'none'
			            });
			          }
			        },
			        fail() {
			          uni.showToast({
			            title: '下载图片失败',
			            icon: 'none'
			          });
			        }
			      });
			    },
			// 海报相关结束
		}
	}
</script>
<style lang="scss" scoped>
.indicator-num {
	padding: 2px 0;
	background-color: rgba(0, 0, 0, 0.35);
	border-radius: 100px;
	width: 35px;
	@include flex;
	justify-content: center;

	&__text {
		 color: #FFFFFF;
		 font-size: 12px;
	 }
}
.product-info{
	.price-num{
		font-size: 60rpx;
		font-family: PingFangSC-Semibold, PingFang SC;
	}
	.exchangeCredit{
		font-size: 60rpx;
	}
	.name{
		margin-top: 30rpx;
		font-size: 36rpx;
		font-weight: 600;
		color: #333;
		line-height: 50rpx;
	}
}
.info-line{
	margin-bottom: 20rpx;
}
.info-til{
	color: #999;
	margin-right: 40rpx;
}
.info-con{
	color: #666;
}
.addr{
	font-size: 30rpx;
	.addr-line:not(:last-child){
		margin-bottom: 20rpx;
	}
	
}
.comment{
	color: #999;
	.til{
		font-size: 30rpx;
		font-weight: 600;
		margin-right: 20rpx;
		color: #333;
	}
}
.detail{
	.til{
		font-size: 30rpx;
		color: #333;
		font-weight: 600;
		margin-bottom: 20rpx;
	}
	.con{
		// background-color: #F5F5F5;
		img{max-width: 100%;}
	}
}
.details-tool-wrap{
	height: 98rpx;
	.details-tool{
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		height: 98rpx;
		background-color: #fff;
	}
	.left{
		text-align: center;
		color: #666;
		font-size: 24rpx;
		.icon-wrap{
			position: relative;
			margin-left: 20rpx;
		}
	}
	.right{
		.btn{
			padding: 19rpx 40rpx;
			border-radius: 40rpx;
			color: #fff;
			margin-right: 20rpx;
		}
		.add-btn{
			background-color: #FFB100;
		}
		.buy-btn{
			background-color: #FF3C3F;
		}
		.gray{
			background-color: #ddd;
			color: #999;
		}
	}
	.share-btn{
		padding: 0;
		margin: 0;
		border: 0;
		font-size: 24rpx;
		color: #666;
		line-height: 1;
		background-color: transparent;
		outline: none;
		&::after{
		  border: none;
		}
	}
}
.share-option{
	transform: translateY(100%);
	.overlay{
		position: fixed;
		left: 0;
		top: 0;
		width: 100vw;
		height: 100vh;
		background-color: rgba(0, 0, 0, 0.35);
		transform: translateY(-100%);
	}
	&.shareShow{
		transform: translateY(0);
	}
	position: fixed;
	width: 100%;
	left: 0;
	bottom: 0;
	z-index: 50;
	background-color: #fff;
	.share-option-item{
		position: relative;
		height: 46px;
		line-height: 46px;
		border: 0;
		background-color: #fff;
		text-align: center;
		border-radius: 0;
		border-bottom: 1px solid #eee;
		font-size: 30rpx;
	}
	.wx-share{
		border-bottom: 0;
	}
}
.poster-wrap{
	position: fixed;
	left: 0;
	top: 0;
	width: 100%;
	height: 100vh;
	.poster-inner{
		flex: 1;
		margin: 0 75rpx;
		.close-wrap{
			display: flex;
			justify-content: flex-end;
			margin-bottom: 16rpx;
		}
	}
	.poster{
		position: relative;
		// padding-bottom: 90rpx;
		background-color: transparent;
		.posterBg{
			position: absolute;
			left: 0;
			bottom: 0;
			right: 0;
			width: 100%;
			z-index: 1;
		}
		.placard{
			position: relative;
			z-index: 10;
		}
		.bottom{
			position: relative;
			z-index: 20;
			margin: 33rpx 40rpx 0;
			.left{
				margin-right: 58rpx;
				.price{
					font-size: 22rpx;
					font-weight: 600;
					color: #FF3538;
					line-height: 30rpx;
					margin-bottom: 10rpx;
					.num{
						font-size: 40rpx;
						font-weight: 600;
						margin-left: 5rpx;
					}
				}
				.goodsName{
					font-size: 30rpx;
					font-weight: 400;
					color: #333333;
					line-height: 38rpx;
					margin-bottom: 16rpx;
				}
				.slogan{
					font-size: 26rpx;
					font-weight: 600;
					line-height: 37rpx;
				}
			}
			.right{
				text-align: center;
				.imgTip{
					margin-top: 12rpx;
					font-size: 20rpx;
					font-weight: 400;
					color: #333333;
					line-height: 28rpx;
				}
				.qrcode{
					width: 108rpx;
					height:108rpx;
				}
			}
		}
	}
	.poster-btn{
		height: 88rpx;
		line-height: 88rpx;
		border-radius: 44rpx;
		text-align: center;
		color: #fff;
		margin-top: 40rpx;
		font-size: 32rpx;
		font-weight: 600;
		background: linear-gradient(90deg, #00DC84 0%, #00A447 100%);
	}
}
</style>