<template>
	<view class="app-container">
		
		<HomePageA :homePage="homePage" :templateInfo="templateInfo" v-if="homePage === 1" />
		<HomePageB :homePage="homePage" :templateInfo="templateInfo" v-if="homePage === 2" />
		<HomePageC :homePage="homePage" :templateInfo="templateInfo" v-if="homePage === 3" />
		
		<view v-if="isSharePyq">
			<image src="https://zfire-train.oss-cn-guangzhou.aliyuncs.com/train/pic/1657090568346be106ca9-dd33-48d2-b06b-e4a02b06f2a2.png" mode="widthFix" style="width: 100%" @tap="clickPyq"></image>
		</view>
		
		<!-- 购买弹窗 -->
		<view class="global-mask" v-show="isBuyDialog"></view>
		<view class="buyDialog" v-show="isBuyDialog">
			<view class="close"><image src="@/static/icon/close.png" @tap="isBuyDialog = false"></image></view>
			<view class="goods" v-if="orderDetail.orderDetails && orderDetail.orderDetails.length == 1">
				<image :src="orderDetail.orderDetails[0].imgUrl" mode="aspectFill"></image>
				<view class="name ellipsis-2">{{orderDetail.orderDetails[0].goodsName}}</view>
				<view class="des ellipsis">{{orderDetail.orderDetails[0].goodsSpecValue}}</view>
			</view>
			<view class="goodsList" v-if="orderDetail.orderDetails && orderDetail.orderDetails.length > 1">
				<block v-for="(item, index) in orderDetail.orderDetails" :key='index'>
					<view class="item">
						<image :src="item.imgUrl" mode="aspectFill"></image>
						<view class="right">
							<view class="name ellipsis-2">{{item.goodsName}}</view>
							<view class="des ellipsis">{{item.goodsSpecValue}}</view>
						</view>
					</view>
				</block>
			</view>
			<view class="num">共<text>{{orderDetail.totalNum}}</text>件商品</view>
			<view class="price">需支付金额：<text>¥{{orderDetail.payAmount}}</text></view>
			<view class="button" @tap="payment">立即支付</view>
		</view>
		
		<!-- 优惠券提醒 -->
		<view class="global-mask" v-show="isCouponDialog"></view>
		<view class="couponDialog" v-show="isCouponDialog">
			<image src="@/static/home/cp_dialog.png" mode="widthFix"></image>
			<view class="bottom">
				<view class="text">你有优惠券即将到期，请尽快使用！</view>
				<view class="btn-group">
					<view class="button left" @tap="isCouponDialog = false">关闭</view>
					<view class="button right" @tap="toMyCoupon">去看看</view>
				</view>
			</view>
		</view>
		
		<!-- 领取优惠券弹窗 -->
		<view class="global-mask" v-show="isReceiveDialog"></view>
		<view class="couponDialog" v-show="isReceiveDialog">
			<image src="@/static/home/cp_dialog.png" mode="widthFix"></image>
			<view class="bottom">
				<view class="text">你有一张优惠券可领取！</view>
				<view class="btn-group onlyOne">
					<view class="button right" @tap="receiveCoupon">立即领取</view>
				</view>
			</view>
		</view>
		
		<modal-dialog showTitle="提示" showText="领取成功" :isShowDialog="isReceiveCouponDialog && isReceiveSuccess" @cancel="isReceiveCouponDialog = false" @confirm="toMyCoupon()" confirmText="去看看"></modal-dialog>
		
		<modal-dialog showTitle="提示" :showText="'领取失败：'+failMessage" :isShowDialog="isReceiveCouponDialog && !isReceiveSuccess" @cancel="isReceiveCouponDialog = false" :isShowConfirm="false" cancelText="关闭"></modal-dialog>
		
		<drag-button :isDock="true" :customBar="false" ref="dragButton"></drag-button>

	</view>
</template>

<script>
	import HomePageA from "@/pages/index/components/home-page-a";
	import HomePageB from "@/pages/index/components/home-page-b";
	import HomePageC from "@/pages/index/components/home-page-c";
	import {mapState} from 'vuex';
	import { appId } from '@/utils/config.js';
	import modalDialog from '@/components/modalDialog.vue';
	import dragButton from '@/components/drag-button.vue';
	
	export default {
		components:{
			HomePageA, HomePageB, HomePageC,
			modalDialog,
			dragButton
		},
		data() {
			return {
				configInfo: uni.getStorageSync('configInfo'),
				templateInfo: uni.getStorageSync('templateInfo'),
				isBuyDialog: false, // 是否显示购买弹窗（业务员代客下单时产生）
				orderDetail: {}, // 订单详情（购买弹窗需要）
				scene: { // 页面参数（扫码进入小程序时产生）
					type: '',
					goodsId: '',
					orderId: '',
					serviceId: '',
					couponId: '',
				},
				isCouponDialog: false, // 是否显示过期优惠券弹窗
				isReceiveCouponDialog: false,
				isReceiveSuccess: true,
				failMessage: '',
				isReceiveDialog: false,
				isSmsReceive: false,
				
				homePage: 0,
				
				isSharePyq: false,
			}
		},
		computed:{
			...mapState(['userInfo', 'isLogin', 'userId'])
		},
		watch: {
			nowDate() {
				let hh = this.nowDate.getHours(),
					mm = this.nowDate.getMinutes(),
					ss = this.nowDate.getSeconds();
				let hs = [10, 12, 15, 18, 20];
				if(mm == 0 && ss == 0 && hs.indexOf(hh) >= 0) {
					setTimeout(() => {
						this.getSeckillTimeList();
					}, 1000)
				}
			}
		},
		
		// 页面滚动
		onPageScroll(res) {
			uni.$emit('onPageScroll', res.scrollTop);
		},
		
		// 下拉刷新
		onPullDownRefresh() {
			
			if(this.isSharePyq) {
				return false;
			}
			
			uni.$emit('onPullDownRefresh');
			
			this.getHomePage();
		},
		
		// 上拉加载
		onReachBottom() {
			uni.$emit('onReachBottom');
		},
		
		// 页面隐藏
		onHide() {
			uni.$emit('onHide');
		},
		
		// 页面显示
		async onShow() {
			var obj = wx.getLaunchOptionsSync()
			console.log(obj);
			if(obj.scene == 1154) {
				return this.isSharePyq = true;
			}
			
			await this.$onLaunched;
			
			await this.getHomePage();
			
			let timer = setInterval(() =>{
				if(this.homePage) {
					clearInterval(timer);
					setTimeout(()=> {
						uni.$emit('onShow');
					}, 200)
				}
			}, 100)
			
			this.$refs.dragButton.init();
		},
		
		// 页面加载
		async onLoad({scene, goodsId, serviceId, mobile, smsServiceId, otherType, appOrderId}) {
			await this.$onLaunched;
			
			uni.showLoading({
			    title: '加载中'
			});
			
			this.getConfig();
			
			this.checkCoupon();
			
			// 点击短信链接进入小程序
			if(smsServiceId) {
				this.bindUser(smsServiceId);
				if(this.userInfo.type !== "SERVICE") {
					this.isSmsReceive = true;
					this.isReceiveDialog = true;
				}
			}
			
			// 从师傅端app跳转进入小程序
			if(appOrderId) {
				this.appOrderPay(appOrderId);
			}
			
			// 点击商品链接进入小程序
			if(serviceId) {
				this.bindUser(serviceId);
			}
			if(goodsId) {
				this.toGoodsDetail(goodsId);
			}
			if(otherType) {
				if(otherType === 'groupbuyList') {
					uni.navigateTo({
						url: '/pages/mine/groupbuy/list'
					})
				}
			}
			
			// 扫码进入小程序
			if(scene) {
				console.log(scene);
				// 拿scene的id去获取
				this.$axios({
					url: '/common/scene',
					method: 'get',
					params: {
						scene: scene,
					}
				}).then(res => {
					let newScene = res.data.split("&");
					this.scene.type = newScene[0];
					this.scene.serviceId = newScene[2];
					// 如果是商品
					if(newScene[0] == 'goods') {
						this.scene.goodsId = newScene[1];
						this.toGoodsDetail(this.scene.goodsId);
					}
					// 如果是订单
					else if(newScene[0] == 'order') {
						this.scene.orderId = newScene[1];
						this.getOrderInfo();
					}
					// 如果是优惠券
					else if(newScene[0] == 'coupon') {
						this.scene.couponId = newScene[1];
						this.isReceiveDialog = true;
						// this.receiveCoupon(this.scene.couponId);
					}
					// 如果是商城分享码
					else if(newScene[0] == 'bind') {
						
					}
					// 如果是团购分享码
					else if(newScene[0] == 'promotion_group') {
						uni.navigateTo({
							url: '/pages/mine/groupbuy/list'
						})
					}
					console.log(this.scene);
					this.bindUser(this.scene.serviceId);
				})
			}
			
		},
		
		// 分享
		onShareAppMessage(options) {
			if (options && options.from == 'button') {
				// 来自页面内的转发按钮
			} else {
				// 点击微信右上角的分享按钮
			}
			return {
				title: `${this.userInfo.nickName}向你推荐了「${this.configInfo.minAppName}」小程序`,
				// imageUrl: this.detail.imgUrl,
				path: '/pages/index/index?serviceId=' + this.userId,
				query: {
					// id: this.goodsId,
				},
				success: function(res) {
					if(res.errMsg == 'shareAppMessage:ok'){
						this.$successToast('分享完成');
					}
				}
			}
		},
		
		onShareTimeline() {
			return {
				title: `${this.userInfo.nickName}向你推荐了「${this.configInfo.minAppName}」小程序`,
				// imageUrl: this.detail.imgUrl,
				// path: '/pages/index/index?serviceId=' + this.userId,
				query: 'serviceId=' + this.userId,
				success: function(res) {
					if(res.errMsg == 'shareAppMessage:ok'){
						this.$successToast('分享完成');
					}
				}
			}
		},
		
		methods: {
			// 获取页面模版
			async getHomePage() {
				const result = await new Promise((resolve, reject)=>{
					this.$axios({
						url: '/renovation/detail',
						method: 'get',
					}).then(res => {
						if(res.data) {
							uni.setStorageSync('templateInfo', res.data);
							this.templateInfo = res.data;
							// res.data.templateType = 3;
							this.homePage = res.data.templateType;
							resolve(res.data.templateType);
						}
					}).catch(res => {
						this.homePage = 1;
						resolve(1);
					})
				})
				return result;
			},
			
			// 获取配置信息
			getConfig() {
				this.$axios({
					url: '/common/config/get',
					method: 'get',
				}).then(res => {
					if(res.data) {
						uni.setStorageSync('configInfo', res.data);
					}
				})
			},
			
			// 绑定用户关系
			bindUser(serviceId) {
				this.$axios({
					url: '/user/bind',
					params: {
						serviceId: serviceId,
						userId: this.userId,
					}
				}).then(res => {
					console.log('绑定成功：' + res.message);
				})
			},
			
			// 点击分享朋友圈的图
			clickPyq() {
				this.$toast('请前往小程序使用完整服务');
			},
			
			// app订单支付
			appOrderPay(appOrderId){
				let that = this;
				this.$axios({
					url: '/common/online/pay',
					method: 'post',
					params: {
						key: appOrderId,
						openId: uni.getStorageSync('userInfo').openId,
					}
				}).then(res => {
					if(!res.data) return false;
					let data = JSON.parse(res.data.codeUrl);
					wx.requestPayment({
						timeStamp: data.timeStamp,
						nonceStr: data.nonceStr,
						package: data.package,
						signType: 'RSA',
						paySign: data.paySign,
						success: (res) => {
							that.$successToast('支付成功');
						},
						fail: (err) => {
							that.$toast('支付失败');
						}
					})
				})
			},
			
			// 进入商品详情
			toGoodsDetail(id) {
				if(!id) {
					return false;
				}
				uni.navigateTo({
					url: '/packageGoods/pages/detail?id=' + id
				})
			},
			
			// 检查是否有优惠券过期
			checkCoupon() {
				this.$axios({
					url: '/coupon/timeout',
					method: 'get',
					params: {},
				}).then(res => {
					if(res.data) {
						this.isCouponDialog = true;
					}
				})
			},
			
			// 进入我的优惠券
			toMyCoupon() {
				this.isCouponDialog = false;
				this.isReceiveCouponDialog = false;
				uni.navigateTo({
					url:'/pages/mine/coupon/list'
				})
			},
			
			// 领取优惠券
			receiveCoupon(id) {
				if(!this.isLogin) {
					return uni.navigateTo({
						url: '/pages/login/index'
					})
				}
				if(this.isSmsReceive) {
					this.$axios({
						url: '/coupon/obtain',
						method: 'get',
						params: {
							userId: '',
							couponId: ''
						}
					}).then(res => {
						this.isReceiveDialog = false;
						this.isReceiveSuccess = true;
						this.isReceiveCouponDialog = true;
					}).catch(res => {
						this.failMessage = res.message;
						this.isReceiveDialog = false;
						this.isReceiveSuccess = false;
						this.isReceiveCouponDialog = true;
					})
				}else {
					this.$axios({
						url: '/coupon/transfer/coupon',
						method: 'get',
						params: {
							userCouponId: this.scene.couponId
						}
					}).then(res => {
						this.isReceiveDialog = false;
						this.isReceiveSuccess = true;
						this.isReceiveCouponDialog = true;
					}).catch(res => {
						this.failMessage = res.message;
						this.isReceiveDialog = false;
						this.isReceiveSuccess = false;
						this.isReceiveCouponDialog = true;
					})
				}
			},
			
			// 获取订单信息
			getOrderInfo() {
				this.$axios({
					url: '/order/detail',
					method: 'get',
					params: {
						orderId: this.scene.orderId
					}
				}).then(res => {
					if(res.data && res.data.orderStatus === 'NOPAY') {
						this.orderDetail = res.data;
						this.isBuyDialog = true;
					}else {
						return this.$toast('二维码已失效，请重新生成');
					}
				})
			},
			
			// 支付
			payment() {
				let that = this;
				if(!this.isLogin) {
					uni.navigateTo({
						url: '/pages/login/index'
					})
				}else {
					this.$axios({
						url: '/order/wait/pay',
						params: {
							userId: this.userId,
							orderId: this.scene.orderId,
						},
						isLoading: 1,
					}).then(res => {
						uni.getProvider({
							service: 'payment',
							success: (e) => {
								uni.requestPayment({
									provider: e.provider[0],
									orderInfo: res.data,
									timeStamp: res.data.timeStamp,
									nonceStr: res.data.nonceStr,
									package: res.data.payPackage,
									signType: 'MD5',
									paySign: res.data.paySign,
									success: (res) => {
										that.$successToast('支付成功');
										that.isBuyDialog = false;
										that.requestMessage();
									},
									fail: (err) => {
										that.$toast('支付失败');
									}
								})
							}
						})
					})
				}
			},
			
			// 消息推送
			requestMessage() {
				let that = this;
				uni.showModal({
					title: '温馨提示',
					content: '为更好的促进您与买家的交流，需要在您的订单成交时向您发送消息',
					confirmText: "同意",
					cancelText: "拒绝",
					success: function (res) {
						if (res.confirm) {
							let tmplIds = [that.configInfo.template];
							uni.requestSubscribeMessage({
								tmplIds: tmplIds,
								success (res) {
									let status = null;
									tmplIds.map((item, index) => {
										if(res[item] == 'accept') {
											status = 'accept';
										}
									})
									if(status == 'accept') {
										that.$successToast('订阅成功');
									}else {
										that.$toast('订阅取消');
									}
								},
								fail (res) {
									console.log(res);
									that.$toast('订阅失败');
								}
							})
						} else if (res.cancel) {
							uni.showModal({
								title: '温馨提示',
								content: '拒绝后您将无法获取实时的与卖家（买家）的交易消息',
								confirmText: "知道了",
								showCancel: false,
								success: function (res) {
									
								}
							});
						}
					}
				});
			},
			
			
		}
	}
</script>

<style lang="scss">
	.app-container {
		background: #F4F2F2;
		box-sizing: border-box;
	}
	.couponDialog {
		position: fixed;
		top: 30%;
		left: 75rpx;
		z-index: 999;
		width: 600rpx;
		background: #FFFFFF;
		border-radius: 20rpx;
		image {
			width: 600rpx;
		}
		.bottom {
			padding: 0 40rpx 50rpx;
			.text {
				font-size: 32rpx;
				line-height: 48rpx;
				text-align: center;
			}
			.btn-group {
				display: flex;
				justify-content: space-between;
				margin-top: 50rpx;
				.button {
					width: 240rpx;
					height: 72rpx;
					border-radius: 72rpx;
					border: 1px solid #FF3F42;
					font-size: 32rpx;
					line-height: 72rpx;
					text-align: center;
					&.left {
						color: #FF3F42;
					}
					&.right {
						color: #FFFFFF;
						background: #FF3F42;
					}
				}
				&.onlyOne {
					justify-content: center;
					.button {
						width: 300rpx;
					}
				}
			}
		}
	}
	.buyDialog {
		position: fixed;
		top: 30%;
		left: 100rpx;
		z-index: 999;
		width: 550rpx;
		background: #FFFFFF;
		border-radius: 10rpx;
		box-sizing: border-box;
		padding: 20rpx 20rpx 30rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		.close {
			width: 100%;
			display: flex;
			justify-content: flex-end;
			image {
				width: 32rpx;
				height: 32rpx;
				display: block;
			}
		}
		.goods {
			margin-top: 10rpx;
			image {
				width: 410rpx;
				height: 300rpx;
				display: block;
			}
			.name {
				font-size: 28rpx;
				line-height: 34rpx;
				margin-top: 16rpx;
			}
			.des {
				font-size: 26rpx;
				color: #666666;
				line-height: 30rpx;
				margin-top: 10rpx;
			}
		}
		.goodsList {
			max-height: 400rpx;
			overflow-y: scroll;
			margin-top: 10rpx;
			.item {
				display: flex;
				padding: 10rpx 20rpx;
				image {
					width: 120rpx;
					height: 120rpx;
					display: block;
					flex-shrink: 0;
				}
				.right {
					width: 334rpx;
					margin-left: 16rpx;
					.name {
						font-size: 28rpx;
						line-height: 34rpx;
						margin-top: 8rpx;
					}
					.des {
						font-size: 26rpx;
						color: #666666;
						line-height: 30rpx;
						margin-top: 10rpx;
					}
				}
			}
		}
		.num {
			margin-top: 10rpx;
			line-height: 40rpx;
			text {
				color: #FF3F42;
				font-size: 32rpx;
				font-weight: 600;
				margin: 0 10rpx;
			}
		}
		.price {
			margin-top: 8rpx;
			line-height: 40rpx;
			text {
				color: #FF3F42;
				font-size: 32rpx;
				font-weight: 600;
			}
		}
		.button {
			width: 300rpx;
			height: 64rpx;
			line-height: 64rpx;
			text-align: center;
			background: #FF3F42;
			border-radius: 64rpx;
			font-size: 28rpx;
			color: #FFFFFF;
			margin-top: 20rpx;
		}
	}
</style>
