<template>
	<view class="goods-detail">
		<navbarTransparent :title="page.title" />
		<!-- swiper -->
		<view class="home-swiper">
			<uni-swiper-dot :mode="mode" :info="info" :current="current1" :dots-styles="dotsStyles">
				<swiper class="swiper-box" @change="change1" circular>
					<swiper-item v-for="(item ,index) in info" :key="index" v-if="resource_type == 1 ">
						<view class="swiper-item">
							<image style="width: 100vw;height:100vw;" :src="item.img" mode="aspectFill"></image>
						</view>
					</swiper-item>
					<swiper-item v-if="resource_type == 2 ">
						<view class="swiper-item">
							<video class="baner-video" id="myVideo" ref="myVideo" style="width: 100%; height: 564rpx;"
								:src="video_url" controls :enable-progress-gesture="false">
							</video>
						</view>
					</swiper-item>
				</swiper>
			</uni-swiper-dot>
		</view>

		<view style="background-color: #f9f9f9;">
			<!-- 价格 -->
			<view class="price">
				<view class="price-top" v-if="produceType == 1 &&  productDetail.price !=0 ">
					<text>￥</text>
					<text>{{productDetail.price}}</text>
				</view>
				<view class="price-top" v-if="produceType == 2">
					<text>{{productDetail.integral}}</text>
					<text>积分</text>
				</view>
				<text class="price-text">{{productDetail.name}}</text>
				<view @click="goOther" class="price-banner" :style="{backgroundImage:'url('+backImageUrl+')'}" v-if="produceType == 1">
					<text>加入IHG优悦会会员享受更多福利</text>
					<image style="width: 12rpx;height: 20rpx;" src="/static/icon/right02.png" mode=""></image>
				</view>
				
				<view @click="goOtherIntegral" class="price-banner" :style="{backgroundImage:'url('+backImageUrl+')'}"  v-if="produceType == 2">
					<text>加入IHG优悦会会员享受更多福利</text>
					<image style="width: 12rpx;height: 20rpx;" src="/static/icon/right02.png" mode=""></image>
				</view>
				
				<!--规格-->
				<view class="price-specs" @click="Recipientopen()">
					<view class="price-specs-left">
						<text>选择</text>
					</view>
					<view class="price-specs-main" @click="Recipientopen()">
						<text>{{showAttr||'请选择规格'}}</text>
					</view>
					<view @click="Recipientopen()">
						<image style="width: 12rpx;height: 20rpx;" src="/static/icon/right03.png" mode=""></image>
					</view>
				</view>
			</view>

			<!--酒店信息  -->
			<view class="about">
				<text class="about-title">可购买酒店信息</text>
				<text class="about-name">{{hotelDetail.name}}</text>
				<view class="about-address">
					<text style="margin-right:20rpx ;">地址:</text>
					<text>{{hotelDetail.address?hotelDetail.address:""}}</text>
				</view>
				<view class="about-phone">
					<text style="margin-right:20rpx ;">电话:</text>
					<text>{{hotelDetail.phone?hotelDetail.phone:""}}</text>
				</view>
				<view class="about-all">
					<text @click="goGoodsHotel(product_id)" style="margin-right: 16rpx;">全部酒店</text>
					<image @click="goGoodsHotel(product_id)" style="width: 12rpx;height: 20rpx;"
						src="/static/icon/right04.png" mode=""></image>
				</view>

			</view>

			<!-- 产品介绍 -->
			<view class="produce">
				<view class="produce-title">
					<text>产品简介</text>
				</view>
				<view class="produce-text">
					<u-parse :content="productDetail.details"></u-parse>
				</view>

			</view>
		</view>

		<view class="buy-btn">
			<view class="buy-btn-left" @click="goHome">
				<image style="width: 40rpx;height: 42rpx;" src="/static/icon/home01.png" mode=""></image>
				<text>首页</text>
			</view>
			<view class="buy-btn-right" @click="goIntegralOrder" v-if="produceType==1">
				<text>立即购买</text>
			</view>
			<view v-if="produceType==2" class="buy-btn-right" @click="goProductChange(product_id,flavorIsActive)">
				<text>立即兑换</text>
			</view>
		</view>
		<view style="height: 90px;background-color: #f9f9f9;"></view>

		<!-- 选择规格 -->
		<uni-popup ref="Recipient" type="bottom" mask-background-color=" rgba(0,0,0,0.3);">
			<view class="pop">
				<view class="pop-price">
					<view class="pop-price-left">
						<image style="width: 180rpx;height: 136rpx; border-radius:12rpx ;"
							:src="productDetail.cover_img" mode=""></image>
						<view class="pop-price-left-money"  v-if="produceType == 1 &&  productDetail.price !=0 ">
							<text>￥</text>
							<text>{{productDetail.price}}</text>
						</view>
						<view class="pop-price-left-money" v-if="produceType == 2">
							<text>{{productDetail.integral}}</text>
							<text>积分</text>
						</view>
					</view>
					<image style="width: 52rpx;height: 52rpx;" src="/static/icon/close01.png" mode=""
						@click="Recipientclose"></image>
				</view>
				<view class="pop-flavor" v-for="i in attr_groups" :key="i.attr_group_id" style="margin-top: 44rpx;">
					<text>{{i.attr_group_name}}</text>
					<view class="tab_flavor">
						<view class="flavorTitle-item"
							:class="{'flavorTitle-item-active':flavorIsActive[i.attr_group_name] === item.attr_name}"
							v-for="(item,index) in i.attr_list" :key="item.attr_id"
							@click="flavorchecked(item.attr_name,i.attr_group_name)">
							<view :class="{'active-flavor':flavorIsActive[i.attr_group_name] === item.attr_name}">
								{{item.attr_name}}
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="purchase" v-if="produceType == 1" @click="goIntegralOrder">
				<view class="purchase-btn">立即购买</view>
			</view>
			<view class="purchase" v-if="produceType == 2" @click="selectSpecs(product_id,flavorIsActive)">
				<view class="purchase-btn">立即兑换</view>
				<!-- <view class="purchase-btn">确认</view> -->
			</view>
		</uni-popup>
		<!-- 二维码购买 -->
		<!-- <uni-popup ref="codePurchase" type="center">
			<view class="code-purchase">
				<view class="title"><text>识别下方二维码即可购买</text></view>
				<view style="margin-left:30rpx;width: 580rpx;height: 2rpx;background: #F0F0F0;"></view>
				<view class="img">
					<image src="http://t9.9026.com/imgs/Kudosbg.png"></image>
				</view>
				<view class="btn">
					<view class="cancel" @click="dialogClose"><text>取消</text></view>
					<view class="download" @click="dialogConfirm"><text>保存图片</text></view>
				</view>
			</view>
		</uni-popup> -->
		<!-- 弹出层/核销码 -->
		<dialogPanel ref="dialogPanel"/>
	</view>
</template>

<script>
	import navbarTransparent from "@/components/extra/navbarTransparent.vue"
	export default {
		components: {
			navbarTransparent
		},
		data() {
			return {
	
				//积分跳转h5,小程序,其他页面
				jump_type_integral: '',
				jump_config_integral: {},
				//产品跳转h5,小程序,其他页面
				jump_type_vip: '',
				jump_config_vip: {},
				//加入会员广告配置
				advise: '',
				
				jump_type: '',
				jump_config: '',
				resource_type: '',
				//1:第三方产品2:积分兑换产品
				produceType: '',
				// 规格
				specsText: '',
				specs: {
					pack: '',
					weight: '',
					flavor: '',
				},
				// 产品详情
				productDetail: '',
				// 酒店详情
				hotelDetail: '',
				// 产品id
				product_id: '',
				//激活指定table菜单
				isActive: 0,
				flavorIsActive: {},
				weightIsActive: 0,
				packIsActive: 0,
				backImageUrl: require('../../../static/icon/add01.png'),
				//轮播图
				info: [{
					img: 'http://t9.9026.com/imgs/swiper01.png',
					name: '酒店预订'
				}, ],
				dotsStyles: {
					backgroundColor: 'rgba(255, 255, 255, .3)',
					border: '1px rgba(255, 255, 255, .3) solid',
					color: '#fff',
					selectedBackgroundColor: 'rgba(255, 255, 255, 1)',
					selectedBorder: '1px rgba(255, 255, 255, 1) solid'
				},
				//指示点显示位置
				current1: 0,
				//指示点模式
				mode: 'dot',
				attr_groups: [],
				page: {
					title: '详情'
				},
				sku: {
					keys: [],
				}
			}
		},
		onReady: function() {
			this.videoContext = uni.createVideoContext('myVideo')
		},
		onLoad(op) {
			const {
				id,
				type
			} = op;
			this.admin = this.$store.getters.userInfo
			this.product_id = id
			this.produceType = type
			this.getProductDetail(this.product_id, true)
			
			//vip跳转
			this.advise = this.$store.getters.allset.add_member
			//产品购买vip图标
			this.productVipImg= this.advise.value.product
			//积分购买vip图标
			this.integralVopImg = this.advise.value.integral
			
			this.jump_type_vip = this.advise.value.product_jump_type
			if (this.jump_type_vip == 1) {
				this.jump_config_vip = this.advise.value.product_h5_url
			} else if (this.jump_type_vip == 2) {
				this.jump_config_vip.appid = this.advise.value.product_appid
				this.jump_config_vip.path = this.advise.value.product_path
			} else if (this.jump_type_vip == 3) {
				this.jump_config_vip = this.advise.value.product_other_path
			}

			this.jump_type_integral = this.advise.value.integral_jump_type
			if (this.jump_type_integral == 1) {
				this.jump_config_integral = this.advise.value.integral_h5_url
			} else if (this.jump_type_integral == 2) {
				this.jump_config_integral.appid = this.advise.value.integral_appid
				this.jump_config_integral.path = this.advise.value.integral_path
			} else if (this.jump_type_integral == 3) {
				this.jump_config_integral = this.advise.value.integral_other_path
			}
			
			if(this.produceType == 1){
				this.backImageUrl = this.productVipImg
			}else if(this.produceType == 2){
				this.backImageUrl = this.integralVopImg
			}

		},
		computed: {
			showAttr: function() {
				if (this.flavorIsActive.length <= 0) return false;
				let text = '';
				for (const k in this.flavorIsActive) {
					text += `${k}-${this.flavorIsActive[k]}，`
				}
				return text.substr(0, text.length - 1);
			},
			selectedHotelId: function() {
				return this.$store.state.tab.selectedHotelId;
			},
			showProductAttr: function() {
				if (this.flavorIsActive.length <= 0) return false;
				let text = '';
				for (const k in this.flavorIsActive) {
					text += `${this.flavorIsActive[k]}-`
				}
				return text.substr(0, text.length - 1);
			},
		},
		methods: {
			//显示所选规格

			//获取当前页面路径
			getPageUrl() {
				const pages = getCurrentPages();
				if (pages.length == 1) {
					const currentPage = pages[0];
					console.log(currentPage.options, '--------->currentPage.options')
					let pageUrl = `/${currentPage.route}?type=${currentPage.options.type}`;
					return pageUrl
					console.log('当前页面url：', pageUrl);
				} else {
					const currentPage = pages[pages.length - 1];
					console.log(currentPage.options, '--------->currentPage.options')
					let pageUrl = `/${currentPage.route}?type=${currentPage.options.type}`;
					return pageUrl
					console.log('当前页面url：', pageUrl);
				}
			},
			
			
			// 跳转其他小程序
			jumpHAppID(id, urls) {
				if (id == 1) {
					const url = urls; // 跳转的外链
					const navtitle = 'H5'; // 这个标题是你自己可以设置的
					uni.navigateTo({
						// 跳转到webview页面
						url: `/pages/webview/webview?url=${url}&nav=${navtitle}`,
						success: () => {
							console.log('成功')
						},
						fail: (e) => {
							console.log(e, "失败")
						}
					});
				} else if (id == 2) {
					let _this = this
					let obj = urls;
					console.log(obj, '----->obj');
					wx.navigateToMiniProgram({
						appId: `${obj.appid}`, //appid
						path: `${obj.path}`, //path
						extraData: { //参数
							foo: 'bar'
						},
						// envVersion: 'develop', //开发版develop 开发版 trial   体验版 release 正式版 
						success(res) {
							let page = _this.getPageUrl()
							let user_id = ''
							if (_this.admin != null) {
								user_id = _this.admin.id
							} else {
								user_id = 0
							}
							_this.$api.my.userMemberAdd({
								user_id,
								page,
							}).then(res => {
								console.log(res.data);
							})
							// 打开成功
						},
						fail(e) {
							console.log(e, '失败')
						}
					})
				} else if (id == 3) {
					uni.redirectTo({
						url: urls,
						fail: (err) => {
							uni.reLaunch({
								url: urls
							})
						}
					})
				}
			},
			
			// 跳转其他小程序
			goOther() {
				let _this = this
				this.jumpHAppID(this.jump_type_vip, this.jump_config_vip)
			},
			
			goOtherIntegral(){
				let _this = this
				this.jumpHAppID(this.jump_type_integral, this.jump_config_integral)
			},
			//视频自动播放
			openVideoPlay() {
				this.videoContext && this.videoContext.play()
			},
			// 获取商品详情
			getProductDetail(product_id, init = false) {
				this.$store.commit("tab/SET_SELECTEDHOTELId", 0)
				this.$api.product.getProductDetail({
					product_id: product_id
				}).then(res => {
					if (res.code == 0 && res.data) {
						this.productDetail = res.data
						this.info = JSON.parse(res.data.img_urls).map(item => {
							return {
								img: item
							}
						})
						//规格对接
						this.attr_groups = JSON.parse(res.data.attr_group)
						//获取默认酒店
						const hotel_ids = JSON.parse(res.data.hotel_ids);
						if ((hotel_ids.constructor == Array) && (hotel_ids.length > 0)) {
							this.$store.commit("tab/SET_SELECTEDHOTELId", hotel_ids[0])
						}
						//
						const sku = JSON.parse(res.data.sku);
						this.sku.keys = Object.keys(sku.attrs);
						this.sku.sku = sku.sku;

						//首次默认选中第一个规格
						if (init) {
							this.attr_groups.forEach(item => {
								this.flavorchecked(item.attr_list[0]?.attr_name, item.attr_group_name)
							})
						}
						
						//跳转h5和小程序
						this.jump_type = res.data.jump_type,
						this.jump_config = res.data.jump_config
						//banner展示视频或者图片
						this.resource_type = res.data.resource_type
						this.video_url = res.data.video_url
						//视频自动播放
						new Promise((resolve,reject)=>{
							try{
								this.openVideoPlay()
							}catch(err){
								reject(false)
							}
							resolve(true)
						}) 
						
					}else{
						uni.showToast({
							icon: 'error',
							title: res.msg?res.msg:"网络繁忙",
						})
					}
				}).catch(err => {
					uni.showToast({
						icon: 'none',
						title: err.msg?err.msg:"服务器繁忙",
					})
				})
			},
			// 获取酒店详情
			getHotelDetail(id) {
				this.$api.hotel.getHotelDetail({
					hotel_id: id
				}).then(res => {
					this.hotelDetail = res.data
				})
			},
			//跳转酒店列表
			goGoodsHotel(id) {
				uni.navigateTo({
					url: '/pages/goods/goods-hotel/index?product_id=' + id
				})
			},
			//首页
			goHome() {
				uni.switchTab({
					url: '/pages/index/index'
				})
			},
			//二维码购买确认按钮
			dialogConfirm() {
				console.log('确认');
				this.codePurchaseClose()
			},
			//二维码购买取消按钮
			dialogClose() {
				console.log('取消');
				this.codePurchaseClose()
			},
			//菜单index切换
			checked(index) {
				this.isActive = index
			},
			getAttrListId(name){
				for(let k in this.attr_groups){
					for(let k1 in this.attr_groups[k].attr_list){
						const v = this.attr_groups[k].attr_list[k1];
						if(v.attr_name == name){
							return v.attr_id;
							break;
						}
					}
				}
			},
			// 口味切换
			flavorchecked(index, name) {
				this.$set(this.flavorIsActive, name, index)
				this.specs.flavor = name
				
				let resTemp = []
				for(let k in this.flavorIsActive){
					resTemp.push(this.getAttrListId(this.flavorIsActive[k]));
				}
				const attr = resTemp.join(":");
				for(let k in this.productDetail.product_attr){
					if(this.productDetail.product_attr[k].attr == attr){
						const price = this.productDetail.product_attr[k].price;
						const integral = this.productDetail.product_attr[k].integral;
						const stock = this.productDetail.product_attr[k].stock;
						this.productDetail.price = price;
						this.productDetail.integral = integral;
						this.productDetail.stock = stock
						break;
					}
				}

			},
			// // 重量切换
			// weightchecked(index,name) {
			// 	this.weightIsActive = index
			// 	this.specs.weight=name
			// 	console.log(this.specs.weight);
			// },
			// // 包装切换
			// packchecked(index,name) {
			// 	this.packIsActive = index
			// 	this.specs.pack=name
			// 	console.log(this.specs.pack);
			// },
			// 立即兑换
			selectSpecs(id, flavorIsActive) {
				const resArr = [];
				outer: for (const k in this.flavorIsActive) {
					inner: for (const i in this.attr_groups) {
						if (this.attr_groups[i].attr_group_name == k) {
							laster: for (const l in this.attr_groups[i].attr_list) {
								if (this.attr_groups[i].attr_list[l].attr_name == this.flavorIsActive[k]) {
									resArr.push(this.attr_groups[i].attr_list[l].attr_id);
									break inner;
								}
							}
						}
					}
				}
				const selectedIds = resArr.join(':');
				console.log(this.productDetail.integral);
				console.log(this.productDetail.stock);
				if(this.productDetail.stock >=1 ){
					uni.navigateTo({
						url: `/pages/my/integral/integralOrder?product_id=${this.productDetail.id}&attr=${selectedIds}&integral=${this.productDetail.integral}&attrName=${this.showProductAttr}`
					})
					this.Recipientclose()
				}else{
					uni.showToast({
						icon:'none',
						title:'库存不足'
					})
				}
			},
			
			Recipientopen() {
				this.$refs.Recipient.open('bottom')
			},
			Recipientclose() {
				this.$refs.Recipient.close()
			},
			codePurchaseClose() {
				this.$refs.codePurchase.close()
			},
			// 切换轮播图指示点
			change1(e) {
				this.current1 = e.detail.current;
			},
			//积分兑换
			goProductChange(id, flavorIsActive) {
				this.Recipientopen()
				// const resArr = [];
				// outer: for (const k in this.flavorIsActive) {
				// 	inner: for (const i in this.attr_groups) {
				// 		if (this.attr_groups[i].attr_group_name == k) {
				// 			laster: for (const l in this.attr_groups[i].attr_list) {
				// 				if (this.attr_groups[i].attr_list[l].attr_name == this.flavorIsActive[k]) {
				// 					resArr.push(this.attr_groups[i].attr_list[l].attr_id);
				// 					break inner;
				// 				}
				// 			}
				// 		}
				// 	}
				// }
				// const selectedIds = resArr.join(':');
				// uni.navigateTo({
				// 	url: `/pages/my/integral/integralOrder?product_id=${this.productDetail.id}&attr=${selectedIds}&integral=${this.productDetail.integral}&attrName=${this.showAttr}`
				// })

			},
			// 跳转积分兑换
			goIntegralOrder() {
				if(this.hotelDetail.buy_jump_type == 3){
					this.$refs.dialogPanel.show(this.hotelDetail.buy_jump_config);
					return;
				}
				
				this.$utils.jump({
					jump_type: this.hotelDetail.buy_jump_type,
					jump_config: this.hotelDetail.buy_jump_config,
					attr: JSON.stringify(this.flavorIsActive)
				})
			},
		},
		watch: {
			selectedHotelId(newValue) {
				newValue && this.getHotelDetail(newValue);
			}
		}
	}
</script>

<style lang="scss" scoped src="./index.scss"></style>
<style lang="scss">
	.produce-text img {
		width: 100%;
		object-fit: fill;
	}
</style>
