<template>
	<view class="container">
		<view style="flex: 1;">
			<!-- 课程详情 -->
					<template v-if="courseInfoItem">
						<view class="courseItemBox" style="padding-top:80rpx">
							<view class="iconfont icon-youjiantou zuojiantou" @click="goBack()" style="top:18rpx">
							</view>
							<course-item :thumbnailPath="courseInfoItem.displayImage" :title="courseInfoItem.fileTitle"
								:summaryBox="courseInfoItem.fileSynopsis"
								:dataList="{coursePrice:courseInfoItem.coursePrice,salesNumber:courseInfoItem.salesNumber}"
								:fileLecturerId="courseInfoItem.fileLecturerId" :fileId="fileId"></course-item>
						</view>
					</template>
					<!-- 价格明细 -->
					<view class="priceInfoContent">
						<h4>价格明细</h4>
						<view ><text class="txtFont">现价</text><text>￥{{Number(courseInfoItem.coursePrice).toFixed(2)}}</text></view>
						<view>
							<text class="txtFont" @click="toggle(1,'bottom')">积分抵扣<i class="iconfont icon-31tishi txtFont"></i></text>
							<text class="integralBox" @click="toggle(2,'bottom')"
								v-if="intergralInfo.preFortune">{{isDeduction != 'true' ? '未选' : '已选'}}积分，可抵扣{{deductionCore}}<i
									class="iconfont icon-youjiantou iconStyle"></i></text>
							<text style="color: #666666;font-size: 30rpx;" v-else>暂无积分</text>
						</view>
						<view><text class="txtFont">合计</text>
							<text v-if="isRedirect == 1">{{calculatedPrice}}</text>
							<text v-else>￥{{Number(totalPrice).toFixed(2)}}</text>
						</view>
					</view>
					<!-- 支付方式 -->
					<view class="paymentMethodContent">
						<h4>选择支付方式</h4>
						<view class="paymentItem" @click="selectPaymentMethod(2)">
							<view>
								<i class="iconfont icon-zhifubao"></i>
								<text class="txtFont">支付宝支付</text>
							</view>
							<view class="selectRadio" :class="{'actived':paymentMethod===2}">
								<i class="iconfont icon-duihao txtFont"></i>
							</view>
						</view>
						<view class="paymentItem" @click="selectPaymentMethod(1)" v-if="deviceType==3">
							<view>
								<i class="iconfont icon-py_weixinzhifu txtFont"></i>
								<text>微信支付</text>
							</view>
							<view class="selectRadio" :class="{'actived':paymentMethod===1}">
								<i class="iconfont icon-duihao txtFont"></i>
							</view>
						</view>
						<!-- #ifdef APP-PLUS -->
			<!-- 			<view class="paymentItem" @click="selectPaymentMethod(1)">
							<view>
								<i class="iconfont icon-py_weixinzhifu"></i>
								<text>微信支付</text>
							</view>
							<view class="selectRadio" :class="{'actived':paymentMethod===1}">
								<i class="iconfont icon-duihao"></i>
							</view>
						</view> -->
						<!-- #endif -->
					</view>
		</view>
		
		<!-- 底部 -->
		<view class="totalContent">
			<view class="priceInfoBox">
				<view>合计：
					<strong v-if="isRedirect == 1">{{calculatedPrice}}</strong>
					<strong v-else style="font-size: 36rpx;">￥{{totalPrice}}</strong>
				</view>

				<view class="" v-if="isRedirect == 1">
					<view>共优惠：<strong style="color:#F15A1F">￥
							<text v-if="isDeduction == 'true'">{{deductionCore}}</text>
							<text style="color:#F15A1F" v-else>0</text>
						</strong>
					</view>
				</view>
				<view class="" v-else>
					<view>共优惠：<strong style="color:#F15A1F"
							v-if="isDeduction == 'true'">￥{{Number(deductionCore * intergralInfo.preFortune).toFixed(2)}}</strong>
						<text style="color:#F15A1F" v-else>0</text>
					</view>
				</view>
			</view>
			<view class="confirmOrder" :class="{'gray':paymentBtnDisabled}" @click="pay()">提交订单</view>
		</view>
		<view v-html="payForm">

		</view>
		<!-- 普通弹窗 -->
		<uni-popup ref="popup" background-color="#fff">
			<view class="popup-content">
				<view class="title">
					<text></text>
					<h3>{{popupTitle}}</h3>
					<i class="iconfont icon-guanbi iconStyle" @click="closePopup(1)"></i>
				</view>
				<view v-if="popupType===1"><text>1积分=1元,积分抵扣如同现金,所有产品均可使用</text></view>
				<view v-if="popupType===2">
					<view class="deductionInfoItem" :class="{'actived':isDeduction == 'true'}" @click="selectDeduction(true)">
						<view style="display: flex;">
							<text>可抵扣</text>
							<view class="integralInfoBox">
								<text class="deductionCount">￥{{deductionCore * intergralInfo.preFortune || '0'}}</text>
								<text>需{{deductionCore}}积分兑换</text>
							</view>
						</view>
						<view class="selectRadio">
							<i class="iconfont icon-duihao " style="font-size: 28rpx;"></i>
						</view>
					</view>
					<view class="deductionInfoItem" :class="{'actived':isDeduction == 'false'}" @click="selectDeduction(false)">
						<view>
							<text>不使用积分抵扣</text>
						</view>
						<view class="selectRadio">
							<i class="iconfont icon-duihao" style="font-size: 28rpx;"></i>
						</view>
					</view>
					<view class="confirmBtn" @click="closePopup(1);">
						确认
					</view>
				</view>
			</view>
		</uni-popup>
		<view class="popupContainer">
			<uni-popup ref="popup1" background-color="#fff">
				<view class="popup1-content">
					<view class="title">
						<text></text>
						<h3>{{popupTitle}}</h3>
						<i class="iconfont icon-guanbi" style="font-size: 28rpx;" @click="closePopup(2)"></i>
					</view>
					<view class="integralDeductionContent">
						<view class="intergralItem">
							<text>可兑换积分:</text>
							<text>{{intergralInfo.yesExchangeFortune}}积分</text>
						</view>
						<view class="intergralItem">
							<text>本次兑换消耗积分:</text>
							<text>{{deductionCore}}积分</text>
						</view>
						<view class="intergralItem">
							<text>剩余可兑换积分:</text>
							<text>{{(intergralInfo.yesExchangeFortune - deductionCore).toFixed(2)}}积分</text>
						</view>
						<view class="confirmBtn" @click="closePopup(2)">
							确认兑换
						</view>
					</view>
				</view>
			</uni-popup>
		</view>
		<view class="markBox" @click="tipsFlag=false" v-if="tipsFlag">
			<view class="guideImgBox">
				<image src="../../static/Group132.png" mode="widthFix"></image>
				<view class="tips">
					<!-- <view class="text-center">请点击右上角菜单</view> -->
					<view style="line-height: 60rpx;">戳这里，点击<text class="iconfont icon-liulanqi"></text>
					按钮，使用系统浏览器打开页面完成支付，完成后请返回微信，到【我的->成交订单】下，查看购买订单。</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import api from "@/api/api";
	import courseItem from "@/components/courseItem/courseItem.vue";
	import {apiURL,companyInfo} from "@/environments/environment";
	import {nextTick} from "vue";
	import common from '../../common/common';
	export default {
		components: {
			courseItem
		},
		data() {
			return {
				courseInfoItem: {},
				fileId: null,
				paymentMethod: 2,
				popupTitle: '积分抵扣规则',
				popupType: 1,
				isDeduction: 'false',
				userId: uni.getStorageSync('cffp_userId'),
				intergralInfo: {},
				orderId: '',
				paymentBtnDisabled: false,
				action: '',
				params: '',
				actionType: '',
				charset: '',
				contentType: '',
				payForm: '',
				deviceType: '',
				tipsFlag: false,
				isRedirect: null,
				amount: 0,
				calculatedPrice: 0
			}
		},
		computed: {
			totalPrice() {
				if (this.isDeduction == "true") {
					return (this.courseInfoItem.coursePrice - (this.deductionCore * this.intergralInfo.preFortune))
						.toFixed(2)
				} else {
					return this.courseInfoItem.coursePrice;
				}
			},
			deductionCore() {
				if (this.courseInfoItem.coursePrice / this.intergralInfo.preFortune < this.intergralInfo
					.yesExchangeFortune) {
					return parseFloat((this.courseInfoItem.coursePrice / this.intergralInfo.preFortune)).toFixed(2)
				} else {
					return this.intergralInfo.yesExchangeFortune
				}
			}
		},

		methods: {
			goBack() {
				uni.navigateBack({
					delta: 1  
				});
			},
			// 支付
			pay() {
				if (this.paymentBtnDisabled) {
					return false;
				}
				this.paymentBtnDisabled = true;
				let param = {
					orderId: this.orderId,
					amount: this.isRedirect == 1 ? this.calculatedPrice : this.totalPrice,
					paymentMethod: this.paymentMethod,
					userId: this.userId,
					integralExchange: this.isDeduction == "true" ? this.deductionCore : 0,
					paymentType: '',
					isPayOrAuth: '',
					fileId: this.fileId,
					companyType: companyInfo.companyType
				}
				if (this.paymentMethod == 1) {
					// APP：微信app支付
					// #ifdef APP-PLUS
					param.paymentType = 1;
					api.unifiedPay(param).then(res => {
						this.paymentBtnDisabled = false;
						if (res['success']) {
							const prepayId = res['data']['prepayId'];//统一下单订单号 如果为空，代表0元订单支付成功
							if(prepayId){
								const orderInfoParam = {
									"appid": res['data']['appid'], 		   // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
									"noncestr": res['data']['noncestr'],   // 随机字符串
									"package": res['data']['packAge'],     // 固定值
									"partnerid": res['data']['partnerid'], // 微信支付商户号
									"prepayid": prepayId,  				   // 统一下单订单号 
									"timestamp": res['data']['timeStamp'], // 时间戳（单位：秒）
									"sign": res['data']['sign'] 		   // 签名，这里用的 MD5/RSA 签名
								}
								let _this = this
								uni.requestPayment({
									provider: 'wxpay',
									orderInfo: orderInfoParam,
									success: function(resp) {
										uni.navigateTo({
											url: `/pages/orderStatus/orderStatus?orderId=${_this.orderId}&fileId=${_this.fileId}&orderStatus=2&userId=${_this.userId}&isRedirect=1`
										})
									},
									fail: function(err) {
										uni.navigateTo({
											url: `/pages/orderStatus/orderStatus?orderId=${_this.orderId}&fileId=${_this.fileId}&orderStatus=1&userId=${_this.userId}&isRedirect=1`
										})
									}
								});
							}else {
								uni.navigateTo({
									url: `/pages/orderStatus/orderStatus?orderId=${this.orderId}&fileId=${this.fileId}&orderStatus=2&userId=${this.userId}&isRedirect=1`
								})
							}
						} else {
							uni.showModal({
								content: res['message'],
								success: function(res) {
									if (res.confirm) {
										console.log('用户点击确定');
									} else if (res.cancel) {
										console.log('用户点击取消');
									}
								}
							});
						}
					})
					// #endif
					// #ifdef H5
					param.paymentType = 2;
					//deviceType:PC为1,移动端为2,微信为3
					if (this.deviceType == 3) {
						let _this = this
						param.isPayOrAuth = 1;
						api.wxAuthorize(param).then((res) => {
							_this.paymentBtnDisabled = false;
							if (res['success']) {
								if (param.amount == '0.00') {
									uni.navigateTo({
										url: `/pages/orderStatus/orderStatus?orderId=${_this.orderId}&fileId=${_this.fileId}&orderStatus=2&userId=${_this.userId}`
									})
									return false
								} else {
									window.location.href = res['data']['paymentForm']['action'];
								}
							}
						})
					} else {
						//微信二维码支付或者微信H5支付
					}
					// #endif
				} else if (this.paymentMethod == 2) {
					// APP：支付宝app支付
					// #ifdef APP-PLUS
					param.paymentType = 1;
					api.unifiedPay(param).then(res => {
						this.paymentBtnDisabled = false;
						if (res['success']) {
							const aliOrderString = res['data']['aliOrderString'];
							let _this = this
							if (aliOrderString) {
								uni.requestPayment({
									provider: 'alipay',
									orderInfo: aliOrderString,
									success: function(resp) {
										uni.navigateTo({
											url: `/pages/orderStatus/orderStatus?orderId=${_this.orderId}&fileId=${_this.fileId}&orderStatus=2&userId=${_this.userId}&isRedirect=1`
										})
									},
									fail: function(err) {
										console.log('fail:' + JSON.stringify(err));
										uni.navigateTo({
											url: `/pages/orderStatus/orderStatus?orderId=${_this.orderId}&fileId=${_this.fileId}&orderStatus=1&userId=${_this.userId}&isRedirect=1`
										})
									}
								});
							} else {
								uni.navigateTo({
									url: `/pages/orderStatus/orderStatus?orderId=${this.orderId}&fileId=${this.fileId}&orderStatus=2&userId=${this.userId}&isRedirect=1`
								})
							}
						} else {
							uni.showModal({
								content: res['message'],
								success: function(res) {
									if (res.confirm) {
										console.log('用户点击确定');
									} else if (res.cancel) {
										console.log('用户点击取消');
									}
								}
							});
						}
					})
					// #endif

					//#ifdef H5
					//支付宝h5支付
					param.paymentType = 2;
					this.amount = this.totalPrice;
					if (this.deviceType == 3) {
						if (param.amount == '0.00') {
							this.getunifiedPay(param)
							return false
						} else {
							this.tipsFlag = true;
							this.amount = this.totalPrice;
							this.paymentBtnDisabled = false;
							let deductionCore = this.isDeduction == "true" ? parseFloat(this.deductionCore) : 0;
							let url = window.location.href +
								`&isRedirect=1&amount=${this.amount}&isDeduction=${this.isDeduction}&deductionCore=${deductionCore}&jumptime=${new Date()}`;
							window.history.replaceState(null, '', url);
							return;
						}
					}
					this.getunifiedPay(param)
					//#endif
				}

			},
			getunifiedPay(param){
				api.unifiedPay(param).then((res) => {
					const data = res['data'];
					this.paymentBtnDisabled = false;
					if (res['success']) {
						if (data.orderStatus != null && data.orderStatus != '') {
							uni.navigateTo({
								url: `/pages/orderStatus/orderStatus?orderId=${this.orderId}&fileId=${this.fileId}&orderStatus=2&userId=${this.userId}`
							})
							return false
						}
						this.payForm = res['data']['aliOrderString'];
						this.$nextTick(() => {
							document.forms['punchout_form'].submit();
						})
					} else {
						uni.showModal({
							content: res['message'],
							success: function(res) {
								if (res.confirm) {
									console.log('用户点击确定');
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						});
					}
				})
			},
			// 积分查询
			queryByUserIdFortuneStatistic() {
				api.queryByUserIdFortuneStatistic({
					userId: this.userId
				}).then(res => {
					if (res['success']) {
						this.intergralInfo = res['data'];
						this.intergralInfo.preFortune = 1.0;
					}
				})
			},
			// 课程详情页面
			courseDetail() {
				api.courseDetail({
					fileId: this.fileId,
					userId: this.userId
				}).then(res => {
					if (res['success']) {
						this.courseInfoItem = res['data']['data'];
					}
				})
			},
			// 选择支付方式
			selectPaymentMethod(value) {
				this.paymentMethod = value;
			},
			// 从下往上弹出
			toggle(val, type) {
				// type 1为积分抵扣规则，2为优惠详情
				this.popupType = val;
				// open 方法传入参数 等同在 uni-popup 组件上绑定 type属性
				if (this.popupType === 3) {
					if (this.isDeduction) {
						this.$refs.popup1.open(type);
					}
				} else {
					this.$refs.popup.open(type);
				}
				if (this.popupType === 1) {
					this.popupTitle = '积分抵扣规则'
				} else if (this.popupType === 2) {
					this.popupTitle = '优惠详情'
				} else if (this.popupType === 3) {
					this.popupTitle = '积分兑换'
				}
			},
			// 关闭弹出层
			closePopup(val) {
				if (val === 1) {
					
					this.$refs.popup.close()
					if(this.isDeduction == 'true'){
						this.toggle(3,'center')
					}
				} else {
					this.$refs.popup1.close()
				}
			},
			// 选择是否抵扣
			selectDeduction(type) {
				this.isDeduction = String(type);
			},
			// 确认积分兑换
			confirmIntergralDeduction() {

			},
			courseDetailLoad(option) {
				this.courseDetail();
				this.queryByUserIdFortuneStatistic()
				this.deviceType = common.checkDeviceType();
				if (this.deviceType == 3) {
					this.paymentMethod = 1;
				}
				if (this.isRedirect == 1) {
					this.deductionCore = option.deductionCore;
					this.amount = Number(option.amount);
					this.isDeduction = String(option.isDeduction);
					this.calculatedPrice = Number(this.amount);
					setTimeout(() => {
						this.pay();
					}, 500)
				}
			},
		},
		onLoad(option) {
			this.fileId = option.fileId;
			this.orderId = option.orderId;
			if (option.userId) {
				this.userId = option.userId;
			}
			this.isRedirect = option.isRedirect;
			 if (this.isRedirect == 1 && option.userId) {
			 	uni.request({
			 		url: `${apiURL}/authorize/obtainToken`,
			 		method: 'POST',
			 		data: {ticket:'uni-app', loginId:option.userId},
			 		success: (res) => {
			 			if (res.statusCode === 200) {
			 				uni.setStorageSync('uni-token', res.data['data']['token']);
							uni.setStorageSync('cffp_userId', option.userId);
							uni.setStorageSync('isLogin','1');
							uni.setStorageSync('isH5', 1);
							this.courseDetailLoad(option);
			 			}
			 		}
			 	});
			 }else{
				 this.courseDetailLoad(option);
			 }
		},
		mounted() {}
	}
</script>

<style lang="scss" scoped>
	::v-deep .uni-popup .uni-popup__wrapper{
	    margin: 0 !important;
		
	}
	.container {
		// position: relative;
		width: 100%;
		box-sizing: border-box;
		display: flex;
		
		flex-direction: column;
		.txtFont{
			font-size: 27rpx;
		}
		.courseItemBox {
			padding: 20rpx 30rpx;
			background-color: #fff;
		}

		.popup-content {
			border-radius: 15rpx 15rpx 0 0;
			padding: 20rpx;
			box-sizing: border-box;
			width: 100%;
			.title {
				display: flex;
				justify-content: space-between;
				align-items: baseline;

				h3 {
					text-align: center;
					color: #333;
					font-size: 32rpx;
					margin-bottom: 30rpx;
				}

				.iconfont {
					color: #999;
				}
			}

			text {
				color: #666;
				font-size: 30rpx;
			}

			.deductionInfoItem {
				display: flex;
				justify-content: space-between;
				align-items: center;
				color: #333;
				font-size: 30rpx;
				padding: 10rpx 30rpx;
				background-color: #F5f5f5;
				border-radius: 20rpx;
				min-height: 90rpx;
				margin-top: 30rpx;

				.integralInfoBox {
					display: flex;
					flex-direction: column;
					margin-left: 10rpx;

					text {
						font-size: 30rpx;
						color: #333333;
					}

					.deductionCount {
						font-size: 36rpx;
						color: #F15A1F;
					}
				}

				.selectRadio {
					color: #D8D8D8;
					width: 40rpx;
					height: 40rpx;
					border: 1px solid #D8D8D8;
					border-radius: 50%;
					display: flex;
					justify-content: center;
					align-items: center;
				}

				&.actived {
					border: 3rpx solid #20269B;
					background-color: #fff;

					.selectRadio {
						background-color: #20269B;
						color: #fff;
					}
				}

			}

			.integralDeductionContent {
				.intergralItem {
					display: flex;
					justify-content: space-between;
					margin-bottom: 10rpx;
				}
			}

			.confirmBtn {
				border-radius: 80rpx;
				height: 80rpx;
				width: 60%;
				background-color: #20269B;
				color: #fff;
				margin: 64rpx auto 0;
				display: flex;
				justify-content: center;
				align-items: center;
				font-size: 28rpx;
			}
		}

		.popup1-content {
			padding: 30rpx 34rpx 20rpx 42rpx;
			border-radius: 20rpx;

			.title {
				display: flex;
				justify-content: space-between;
				align-items: baseline;

				h3 {
					text-align: center;
					color: #333;
					font-size: 32rpx;
					margin-bottom: 30rpx;
				}

				.iconfont {
					color: #999;
				}
			}

			.integralDeductionContent {
				.intergralItem {
					display: flex;
					justify-content: space-between;
					color: #333;
					font-size: 30rpx;
					margin-bottom: 10rpx;
				}
			}

			.confirmBtn {
				border-radius: 80rpx;
				height: 80rpx;
				width: 60%;
				background-color: #20269B;
				color: #fff;
				margin: 64rpx auto 0;
				display: flex;
				justify-content: center;
				align-items: center;
				font-size: 28rpx;
			}
		}

		.priceInfoContent,
		.paymentMethodContent,
		.totalContent {
			background-color: #fff;
			margin: 0 10rpx;
			padding: 20rpx;
			border-radius: 10rpx;
		}

		.priceInfoContent {
			view {
				display: flex;
				justify-content: space-between;
				
				text {
					&:last-child {
						font-weight: bold;
						font-size: 27rpx;
					}

					&.integralBox {
						color: #FA6900;
						font-weight: normal;

						.iconfont {
							color: #999;
						}
					}
				}

				.iconfont {
					margin-left: 10rpx;
				}

			}
		}

		.priceInfoContent,
		.paymentMethodContent {
			border-bottom: 5px solid #fbfbfb;
			color: #333;

			h4 {
				font-size: 32rpx;
				margin-bottom: 20rpx;
			}

			view {
				margin-bottom: 10rpx;
			}
		}

		.paymentMethodContent {
			margin-top: 20rpx;
			
			
			.paymentItem {
				display: flex;
				align-items: center;
				justify-content: space-between;

				view {
					display: flex;
					align-items: center;
				}

				.icon-zhifubao {
					color: #5A9EF7;
					font-size: 60rpx;
					margin-right: 20rpx;
				}

				.icon-py_weixinzhifu {
					color: #09BB07;
					font-size: 60rpx;
					margin-right: 20rpx;
				}

				.selectRadio {
					width: 40rpx;
					height: 40rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					border-radius: 50%;
					border: 1px solid #D8D8D8;
					color: transparent;

					&.actived {
						background-color: #0A2F99;
						color: #fff;
					}
				}

			}
		}

		.totalContent {
			// position: absolute;
			// bottom: 0;
			// left: 0;
			// width: 100%;
			padding: 40rpx 28rpx;
			margin-bottom: 20rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			box-sizing: border-box;

			.priceInfoBox {
				font-size: 30rpx;
				color: #333;

				view:first-child {
					margin-bottom: 10rpx;
				}
			}

			.confirmOrder {
				background-color: #20269B;
				color: #fff;
				padding: 14rpx 38rpx;
				border-radius: 80rpx;
				font-size: 28rpx;
			}

			.gray {
				background: #666;
			}
		}

	}

	.markBox {
		position: fixed;
		left: 0;
		top: 0;
		bottom: 0;
		right: 0;
		width: 100%;
		height: 100%;
		color: #fff;
		display: flex;
		justify-content: flex-end;
		z-index: 100000;
		background: rgba(0, 0, 0, 0.8);
		.icon-liulanqi{
			margin: 0px 10rpx;
			color: #3b43d5;
			background: #fff;
			padding: 6rpx;
			border-radius: 8rpx;
			font-size: 36rpx;
		}
		.guideImgBox {
			margin: 20px auto;
		
			uni-image {
				width: 25% !important;
				position: absolute;
				right: 0;
				top: 0;
			}
		}
		
		.tips {
			margin-top: 20%;
			padding: 0 30px;
		}
	}

	// .iconfont {
	//   position: absolute;
	//   right: 8%;
	//   font-size: 40px;
	//   top: 2px;
	//   font-weight: bold;
	// }
	.tips p {
		font-size: 18px;
		margin-top: 10px;
		text-align: justify;
		letter-spacing: 1px;
	}
</style>
