<template>
	<view class="container">
		<!-- 轮播图 -->
		<top-swiper :imgList="imgList"></top-swiper>
		<!-- 标题 -->
		<product-content :goodsObjact="goodsObjact"></product-content>
		<!-- 规格信息 -->
		<fresh-detail @click='specOPne' :specSelected="specSelected"></fresh-detail>
		<!-- 图文详情 -->
		<content-text :description="description"></content-text>
		<!-- 底部高度撑开 -->
		<view class="contentBottomHeight"></view>
		<!-- 底部操作菜单 -->
		<product-bottom :systemStore='system_store' @buy="buy" :goodsObjact="goodsObjact" :goodsid="goodsid"
			@specOPne="specOPne"></product-bottom>
		<!-- 规格-模态层弹窗 -->
		<view class="popup spec" :class="specClass" @touchmove.stop.prevent="stopPrevent" @click="toggleSpec">
			<!-- 遮罩层 -->
			<view class="mask"></view>
			<view class="layer attr-content" @click.stop="stopPrevent">
				<image class="close" src="../../static/icon/goodsExit.png" mode="aspectFit" @click="toggleSpec">
				</image>

				<view class="a-t">
					<image @click="showImg(true)" :src="actionGoodsType.actionImage"></image>
					<view class="right">
						<text class="name">{{ goodsObjact.store_name }}</text>
						<text class="price">
							<text class="font-size-base margin-r-10">
								¥
							</text>
							<text>
								{{ actionGoodsType.actionPrice*goodsNumber}}
							</text>
							<text class="font-color-gray font-size-sm margin-l-10">
								库存：{{actionGoodsType.goodsStore}}
							</text>
						</text>
					</view>
				</view>
				<view v-if="many==2" v-for="(item, index) in specList" :key="index" class="attr-list">
					<text>{{ item.attr_name }}</text>
					<view class="item-list flex">
						<text v-for="(childItem, childIndex) in item.attr_value" :key="childIndex" class="tit"
							:class="{ selected: childItem.check }" @click="selectSpec(childItem, item, index)">
							{{ childItem.attr }}
						</text>
					</view>
				</view>
				<view v-if="many==1" class="attr-list">
					<text>规格</text>
					<view class="item-list flex">
						<text class="tit selected">
							默认
						</text>
					</view>
				</view>
				<view class="attr-list">
					<text>购买数量</text>
					<view class="item-list">
						<uni-number-box class="step" :isMin="true" v-model="goodsNumber"
							:max="actionGoodsType.goodsNumberMax"></uni-number-box>
					</view>
				</view>
				<button class="btn" @click.stop="buy" v-show="buys_show">完成</button>
				<button class="btn" style="background-color: #999999;" v-show="buys_shows">售罄</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		goodsDetail,
		cartAdd
	} from '@/api/product.js';
	import {
		mapState
	} from 'vuex';
	import store from '@/store/index.js';
	import {
		saveUrl
	} from '@/utils/loginUtils.js';
	// #ifdef H5
	import {
		weixindata
	} from '@/utils/wxAuthorized';
	// #endif
	// 头部轮播图
	import topSwiper from './common/topSwiper.vue';
	// 标题
	import productContent from './common/productContent.vue';
	// 规格信息
	import freshDetail from './common/freshDetail.vue';
	// 图文详情
	import contentText from './common/contentText.vue';
	// 底部按钮
	import productBottom from './common/productBottom.vue';
	export default {
		components: {
			topSwiper,
			productContent,
			freshDetail,
			contentText,
			productBottom,
		},
		data() {
			return {
				specList: [],
				buys_show: true,
				buys_shows: false,
				specSelected: [], //选中的分类
				specClass: 'none', //显示隐藏弹窗
				many: 1, //1是单规格  2是多规格
				reply: '', //评论
				list: '', //商品详情的数据
				type: 1, //默认支付方式add为
				goodsType: 0,
				goodsNumber: 1, //购买数量
				goodsid: '', //商品id
				description: '', //商品描述
				goodsObjact: {
					percent: 1
				}, //保存商品数据
				//图片循环
				imgList: [],
				// 对比对象
				good_list: '', //猜你喜欢列表
				userInfo: '',
				// 选中商品的分类
				actionGoodsType: {
					goodsNumberMax: 0, //最大可购买数量
					goodsStore: 0, //选中库存
					actionImage: '', //默认选中图片
					actionPrice: 0, //默认选中商品价格
					day_deducted: 0, //选中商品的服务费用
					deal_price_num: 0, //选中商品的扣款天数
					uniqueId: '', //选中规格商品id
				},
				system_store: {}, //商家信息
			};
		},
		async onLoad(options) {
			let obj = this;
			obj.userInfo = uni.getStorageSync('userInfo');
			//保存商品id
			this.goodsid = options.id;
			this.goodsType = options.type;

			// 判断有无人邀请
			if (options.spread) {
				// 存储邀请人
				uni.setStorageSync('spread', options.spread);
			}
			saveUrl();
			this.goodsDetail();
			// 注册邀请信息
			// #ifdef H5
			let bool = uni.getStorageSync('weichatBrowser') || '';
			if (bool) {
				weixindata();
			}
			// #endif
		},
		computed: {
			...mapState(['weichatObj', 'baseURL', 'urlFile']),
			...mapState('shop', ['shopDetail'])
		},
		// 分享
		onShareAppMessage(options) {
			// 设置菜单中的转发按钮触发转发事件时的转发内容
			let pages = getCurrentPages(); //获取加载的页面
			let currentPage = pages[pages.length - 1]; //获取当前页面的对象
			let url = currentPage.route; //当前页面url
			let item = currentPage.options; //如果要获取url中所带的参数可以查看options
			let shareObj = {
				title: this.goodsObjact.store_name + '   价格：' + this.goodsObjact.price, // 默认是小程序的名称(可以写slogan等)
				path: url + '?id=' + item.id + '&spread=' + this.userInfo.uid, // 默认是当前页面，必须是以‘/’开头的完整路径
				imageUrl: this.goodsObjact.image,
				success: function(res) {
					// 转发成功之后的回调
					if (res.errMsg == 'shareAppMessage:ok') {}
				},
				fail: function() {
					// 转发失败之后的回调
					if (res.errMsg == 'shareAppMessage:fail cancel') {
						// 用户取消转发
					} else if (res.errMsg == 'shareAppMessage:fail') {
						// 转发失败，其中 detail message 为详细失败信息
					}
				}
			};

			return shareObj;
		},
		methods: {
			showImg(bool) {
				uni.navigateTo({
					url: './showImg?imgs=' + JSON.stringify([this.actionGoodsType.actionImage]) + '&current=' + 0,
					animationType: "fade-in"

				})
			},
			//选择规格
			selectSpec(item, arr, ind) {
				arr.attr_value.forEach(function(e) {
					e.check = false;
				});
				item.check = true;
				let obj = this;
				obj.specSelected[ind] = item.attr;
				// 重置触发修改事件
				obj.specSelected = obj.specSelected.map((e) => {
					return e
				});
				let str = obj.specSelected.join(',');

				let goodItemAction = obj.actionGoodsType

				// 获取当前选中的对象
				if (obj.productValue[str]) {

					obj.buys_show = true;
					obj.buys_shows = false;
					goodItemAction.actionPrice = obj.productValue[str].price;
					goodItemAction.goodsNumberMax = obj.productValue[str].stock;
					goodItemAction.actionImage = obj.productValue[str].image;
					goodItemAction.uniqueId = obj.productValue[str].unique;
					goodItemAction.goodsStore = obj.productValue[str].stock;
					console.log(goodItemAction.goodsStore, 'kc')
					goodItemAction.day_deducted = obj.productValue[str].day_deducted; //每天扣款
					if (+obj.productValue[str].day_deducted) {
						goodItemAction.deal_price_num = Math.ceil((obj.productValue[str].deal_price - obj.productValue[str]
							.price) / obj.productValue[str].day_deducted); //每天扣款
					} else {
						goodItemAction.deal_price_num = 0
					}
					// 扣款天数
				} else {
					(obj.buys_show = false), (obj.buys_shows = true);
				}
				if (goodItemAction.goodsStore == 0) {
					obj.buys_show = false;
					obj.buys_shows = true;
				}
				// obj.specSelected[ind] = item.attr;
			},
			// 打開彈窗
			specOPne(type = 1) {
				let obj = this;
				obj.type = type;
				obj.specClass = 'show';
			},
			//规格弹窗开关
			toggleSpec(str) {
				if (this.specClass === 'show') {
					this.specClass = 'hide';
					setTimeout(() => {
						this.specClass = 'none';
					}, 250);
				} else if (this.specClass === 'none') {
					this.specClass = 'show';
				}
				// 保存当前购买类型
				this.type = str;
			},
			//领取优惠券
			Getcoupon() {
				uni.navigateTo({
					url: '/pages/coupon/getcoupon'
				});
			},
			//详情页
			navToDetailPage(item) {
				let id = item.id;
				uni.navigateTo({
					url: '/pages/product/product?id=' + id
				});
			},
			// 跳转页面
			// navTo(url) {
			// 	uni.navigateTo({
			// 		url: '/pages/product/reply?id=' + this.goodsid
			// 	});
			// },
			// 获取商品详情
			goodsDetail() {
				let obj = this;
				// 获取普通商品信息
				goodsDetail({}, this.goodsid).then(function({
					data
				}) {
					obj.list = data;
					//保存猜你喜欢列表
					obj.good_list = data.good_list;
					//保存评论列表
					obj.reply = data.reply;
					let goods = data.storeInfo;
					obj.goodsObjact = goods;
					//保存商家信息
					obj.system_store = data.system_store;
					if (obj.goodsObjact.description != null) {
						obj.description = obj.goodsObjact.description.replace(/\<img/gi, '<img class="rich-img"');
					} //小程序商品详情图超出屏幕问题
					obj.imgList = goods.slider_image; //保存轮播图
					obj.specList = data.productAttr; //保存分类列表
					if (obj.specList.length > 0) {

						obj.many = 2; //多规格
						obj.specList = data.productAttr; //保存产品属性
						obj.productValue = data.productValue; //保存属性值
						obj.specSelected = []; //初始化默认选择对象
						for (let i = 0; i < obj.specList.length; i++) {
							// 设置默认数据
							let attrValue = obj.specList[i].attr_value[0];
							attrValue.check = true;
							obj.specSelected.push(attrValue.attr);
						}
						let str = obj.specSelected.join(',');
						let goodItemAction = obj.actionGoodsType
						// 设置默认值
						goodItemAction.actionPrice = obj.productValue[str].price;
						goodItemAction.goodsNumberMax = obj.productValue[str].stock;
						goodItemAction.actionImage = obj.productValue[str].image;
						goodItemAction.uniqueId = obj.productValue[str].unique;
						goodItemAction.goodsStore = obj.productValue[str].stock;
						goodItemAction.day_deducted = obj.productValue[str].day_deducted; //每天扣款
						goodItemAction.deal_price_num = Math.ceil((obj.productValue[str].deal_price - obj
							.productValue[str].price) / obj.productValue[str].day_deducted); //每天扣款
						// 扣款天数
					} else {
						obj.many = 1; //单规格
						obj.actionGoodsType.actionPrice = goods.price; //保存默认选中商品价格
						obj.actionGoodsType.actionImage = goods.image_base; //保存默认选中商品图片
						obj.actionGoodsType.goodsNumberMax = goods.stock; //保存默认选中最大可购买商品数量
						obj.actionGoodsType.goodsStore = goods.stock;
					}
				});
			},
			// 立即购买
			buy() {
				let obj = this;
				// 创建传值对象
				let data = {
					cartNum: obj.goodsNumber, //商品数量
					productId: obj.goodsid, //商品编号
					uniqueId: obj.actionGoodsType.uniqueId,
				};
				// 判断是否需要读取非默认商家id
				// 判断是否加入购物车
				if (obj.type == 2) {
					data.new = 0;
				} else {
					data.new = 1;
				}
				uni.showLoading({
					title: '请求中',
					mask: true
				});
				cartAdd(data)
					.then(function(e) {
						uni.hideLoading()
						let da = e.data;
						// 不是购物车跳转支付页面
						if (obj.type == 1) {
							// 跳转到支付页
							let url = '/pages/order/createOrder?id=' + da.cartId
							uni.navigateTo({
								url: url,
								fail(res) {
									console.log(res, '错误')
								}
							});
						}
						// 购物车不跳转购物车页面
						if (obj.type == 2) {
							uni.showToast({
								title: '成功加入购物车',
								type: 'top',
								duration: 2000,
								icon: 'none'
							});
						}
						obj.toggleSpec()
					})
					.catch(e => {
						console.log(e);
					});
			},
			// 阻止触发上级事件
			stopPrevent() {}
		}
	};
</script>

<style lang="scss">
	.alertImgBox {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100%;

		.alertImg {
			width: 730rpx;
		}
	}

	/*  弹出层 */
	.popup {
		position: fixed;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
		z-index: 99;

		&.show {
			display: block;

			.mask {
				animation: showPopup 0.2s linear both;
			}

			.layer {
				animation: showLayer 0.2s linear both;
			}
		}

		&.hide {
			.mask {
				animation: hidePopup 0.2s linear both;
			}

			.layer {
				animation: hideLayer 0.2s linear both;
			}
		}

		&.none {
			display: none;
		}

		.mask {
			position: fixed;
			top: 0;
			width: 100%;
			height: 100%;
			z-index: 1;
			background-color: rgba(0, 0, 0, 0.4);
		}

		.layer {
			position: fixed;
			z-index: 99;
			bottom: 0;
			width: 100%;
			min-height: 35vh;
			border-radius: 10rpx 10rpx 0 0;
			background-color: #fff;

			.btn {
				height: 76rpx;
				line-height: 66rpx;
				border-radius: 100rpx;
				background: linear-gradient(90deg, #3C82E6, #5395F5);
				font-size: $font-base + 2rpx;
				color: #FFF;
				margin: 30rpx auto 20rpx;
			}
		}

		@keyframes showPopup {
			0% {
				opacity: 0;
			}

			100% {
				opacity: 1;
			}
		}

		@keyframes hidePopup {
			0% {
				opacity: 1;
			}

			100% {
				opacity: 0;
			}
		}

		@keyframes showLayer {
			0% {
				transform: translateY(120%);
			}

			100% {
				transform: translateY(0%);
			}
		}

		@keyframes hideLayer {
			0% {
				transform: translateY(0);
			}

			100% {
				transform: translateY(120%);
			}
		}
	}

	/* 规格选择弹窗 */
	.attr-content {
		padding: 50rpx;
		position: relative;

		.close {
			width: 36rpx;
			height: 36rpx;
			position: absolute;
			top: 50rpx;
			right: 50rpx;
		}

		.a-t {
			display: flex;

			image {
				border: 1px solid $page-color-light;
				width: 170rpx;
				height: 170rpx;
				flex-shrink: 0;
				border-radius: 8rpx;
			}

			.right {
				display: flex;
				flex-direction: column;
				padding-left: 24rpx;
				font-size: $font-sm + 2rpx;
				color: $font-color-base;
				line-height: 42rpx;
				width: 75%;

				.price {
					font-size: 44rpx;
					color: $color-red;
					margin: 10rpx 0rpx;
					flex-grow: 1;
					width: 100%;
				}

				.name {
					font-size: 32rpx;
					color: $font-color-dark;
					height: 50rpx;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
					display: block;
				}

				.selected-text {
					margin-right: 10rpx;
				}
			}
		}

		.attr-list {
			display: flex;
			flex-direction: column;
			font-size: $font-base + 2rpx;
			color: $font-color-base;
			padding-top: 30rpx;
		}

		.item-list {
			padding: 20rpx 0 0;
			display: flex;
			flex-wrap: wrap;
			justify-content: flex-start;

			.tit {
				min-width: 200rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				background: #eee;
				margin-bottom: 20rpx;
				margin-right: 16rpx;
				border-radius: 5rpx;
				height: 60rpx;
				padding: 0 20rpx;
				font-size: $font-base;
				color: $font-color-dark;
			}

			.selected {
				background: #E1F4EA;
				color: $color-green;
				border: 1px solid $color-green;
			}
		}
	}

	//默认商品底部高度
	.goodsBottom {
		height: 160rpx;
	}

	page {
		background: #f0f0f0;
	}

	//秒杀、拼团底部高度
	.contentBottomHeight {
		height: 110rpx;
	}

	//默认商品底部高度
	.goodsBottom {
		height: 160rpx;
	}

	/deep/ .iconenter {
		font-size: $font-base + 2rpx;
		color: #888;
	}

	/deep/ .con_image {
		width: 130rpx;
		height: 130rpx;
		display: inline-block;
		padding: 15rpx;

		image {
			width: 100%;
			height: 100%;
		}
	}

	/* 商品详情中限制图片大小 */
	/deep/ .rich-img {
		width: 100% !important;
		height: auto;
	}
</style>
