<template>
	<view class="tainer">
		<van-dialog v-model="dialogShow" @closed="dialogClosed" :show-confirm-button="false"
			:closeOnClickOverlay="true">
			<view class="PaymentRsults">
				<image v-if="PaymentRsults==1" style="width: 160rpx;height: 160rpx;" mode='widthFix'
					:src="ImgUrl+'StudentPayment/success-icon.png'">
				</image>
				<image v-if="PaymentRsults==2" style="width: 160rpx;height: 160rpx;" mode='widthFix'
					:src="ImgUrl+'StudentPayment/fail-icon.png'">
				</image>
				<view class="PaymentRsultsTxt" @click="dialogClosed" v-if="PaymentRsults==1">
					支付成功
				</view>
				<view class="PaymentRsultsTxt" @click="clickPay" v-if="PaymentRsults==2">
					请重新支付
				</view>
			</view>
		</van-dialog>
		<view class="headerImg">
			<view class="cardInfo">
				<view class="title">
					{{ChargeProDetail.chargeName||""}}
				</view>
				<view class="title2">
					<van-notice-bar :scrollable="ChargeProDetail.descInfo.length>20?true:false" background="#ffffff"
						color="#333333" style="padding: 0;" :text="ChargeProDetail.descInfo||''" />
				</view>
				<van-divider />
				<view class="botto">
					<view class="rowInfo">
						<text class="name">学生姓名：</text>
						<text class="value">{{ChargeProDetail.userName||""}}</text>
					</view>
					<view class="rowInfo">
						<text class="name">年级班级：</text>
						<text class="value">{{ChargeProDetail.userGrade||""}} {{ChargeProDetail.userClass||""}}班</text>
					</view>
					<view class="rowInfo" v-if="false">
						<text class="name">订单编号：</text>
						<text class="value">{{ChargeProDetail.tradeId||""}}</text>
					</view>
				</view>
			</view>
		</view>
		<!-- 收费项目 -->
		<view class="PayProject">
			<view class="tabNames">
				<view style="padding-left: 70rpx;">
					收费子项
				</view>
				<view style="padding-left: 70rpx;">
					收费类型
				</view>
				<view style="padding-left: 70rpx;">
					金额（元）
				</view>
			</view>
			<!-- Project -->
			<view class="ProjectBox">
				<view class="ProjectItem" v-for="(item,index) in ChargeProDetail.items" :key="index"
					:class="SPayProject(index)?'selectProjectItem':''" v-if="!(item.itemAmount==0&&item.mustFlag==0)">
					<view class="tabNames" @click="selectProject(item,index)">
						<view class="ProjectName">
							<image v-if="SPayProject(index)" style="width: 32rpx;height: 32rpx;"
								:src="ImgUrl+'StudentPayment/gx.png'" mode='widthFix'></image>
							<image v-else style="width: 32rpx;height: 32rpx;" :src="ImgUrl+'StudentPayment/wgx.png'"
								mode='widthFix'></image>
							<text>{{item.itemName}}</text>
						</view>
						<view class="ProjectType">
							{{['选交项目','必交项目'][item.mustFlag]}}
						</view>
						<view class="money">
							{{itemAmount(item.itemAmount)}}
						</view>
					</view>
				</view>
			</view>

		</view>
		<!-- 备注 -->
		<view class="remarks">
			<text class="remarksTxt">
				{{remarksType[ChargeProDetail.notesType-1]}}
			</text>
			<textarea :placeholder="ChargeProDetail.notesTips" :cursor="10" placeholder-class="remarksTextarea"
				:maxlength="40" :auto-height="true" v-model="remarks" />
		</view>
		<!-- 底部操作按钮 -->
		<view class="bottomOper">
			<view class="buttonContent">
				<view class="left">
					<view class="">
						<text class="zongji">总计：</text>
						<text class="money">
							{{payMoney}}
						</text>
					</view>
					<view class="xieyi">
						<text>点击交费，即表示我已阅读</text>
						<text @click="Agreement">《线上缴纳协议》</text>
					</view>
				</view>
				<view class="right" @click="clickPay">
					点击交费
				</view>
			</view>
		</view>
		<view class="masking" v-if="mask"></view>
	</view>
</template>

<script>
	/**
	 * 对象转拼接字符串
	 * @param {*} res   Object    需要转换的数据对象
	 */
	function OforS(res) {
		var resL = 0;
		var outS = "";
		for (var i in res) {
			if (resL == 0) {
				outS += "" + i + "=" + res[i];
			} else {
				outS += "&" + i + "=" + res[i];
			}
			resL++;
		}
		return outS;
	}
	let orderApi = window.location.origin
	export default {
		name: "PayOrderDetails",
		data() {
			return {
				ImgUrl: this.$ImgUrl,
				payMoney: "0.00",
				// 选择收费子项目
				selectPayProject: [],
				// 选择收费子项目
				selectPayProjectObj: {},
				selectCount: 0,
				dialogShow: false,
				PaymentRsults: -1,
				allData: {},
				// 交费项目详情信息
				ChargeProDetail: {
					descInfo: ''
				},
				// 备注信息
				remarks: "",
				remarksType: ["备注", "邮箱", "手机号码", "身份证"],
				// 费用id
				chargeItemIds: [],
				mask: false
			}
		},
		onLoad: function(options) {
			let this_ = this;
			let personalInfo = uni.getStorageSync("personalInfo")
			let PayOrderDetails = uni.getStorageSync("PayOrderDetails")
			this.allData = Object.assign(options, personalInfo, {
				chargeId: PayOrderDetails.id
			})
			if (options.PaymentRsults) {
				this_.dialogShow = true
				this.PaymentRsults = parseInt(options.PaymentRsults);
				if (this.PaymentRsults == 1) {
					// 支付成功返回交费项目列表
					setTimeout(() => {
						this_.dialogClosed()
					}, 3000)
				}
				// 上报支付结果
				this.returnPaymentResult(uni.getStorageSync("prepayId").tradeId, this.PaymentRsults)
			}
			this.queryChargeProDetail()
		},
		onShow: function() {
			// uni.showLoading({
			// 	mask: true,
			// 	title: "查询支付结果" 
			// })
			// setTimeout(function() {
			// 	uni.hideLoading()
			// 	this_.dialogShow = true
			// }, 1000)
		},
		computed: {
			itemAmount() {
				return function(Amount) {
					if (Amount) {
						return (Amount / 100).toFixed(2)
					} else {
						return "0.00"
					}
				}
			},
			SPayProject() {
				return function(index) {
					if (index == 0 || index > 0) {
						return this.selectPayProject.includes(index)
					} else {
						return false
					}
				}
			}
		},
		methods: {
			Agreement() {
				uni.navigateTo({
					url: "../../pdfPreview/pdfPreview?pdfName=xzfjfxy"
				})
			},
			// 查询交费订单明细信息
			async queryChargeProDetail() {
				try {
					let data = await this.$http.post({
						url: orderApi + '/order-charge/app/charge/project/queryChargeProDetail'
					}, {
						"chargeId": this.allData.chargeId,
						"schoolId": this.allData.schoolId,
						"userId": this.allData.userId
					})
					if (data.code != 200 || !data.data) {
						uni.showToast({
							icon: "none",
							mask: true,
							title: data.msg
						})
						return
					}
					this.ChargeProDetail = data.data;
					// 收费类型必缴项目默认选择
					for (let i = 0; i < data.data.items.length; i++) {
						if (data.data.items[i].mustFlag == 1) {
							this.selectProject(data.data.items[i], i)
						}
					}
				} catch (e) {
					//TODO handle the exception
					console.log(e);
					uni.showToast({
						icon: "none",
						mask: true,
						title: e.message
					})
				}
			},
			// 支付结果页面关闭
			async dialogClosed() {
				try {
					console.log("dialogClosed");
					this.dialogShow = false
					if (this.PaymentRsults == 1) {
						// 支付成功返回交费项目列表
						uni.redirectTo({
							url: "../PayProject/PayProject"
						})
						return
					}
				} catch (e) {
					//TODO handle the exception
					console.log(e);
				}
			},
			// 选择支付的项目
			async selectProject(data, index) {
				try {
					if (!this.selectPayProject.includes(index)) {
						this.selectPayProject.push(index)
						this.selectPayProjectObj[index + ''] = data
					} else {
						let indexOf = this.selectPayProject.indexOf(index)
						this.selectPayProject.splice(indexOf, 1)
						delete this.selectPayProjectObj[index + '']
					}
					// 计算金额
					let payMoney = 0,
						// 选择的项目数
						selectCount = 0,
						// 费用id
						chargeItemIds = [];
					for (let key in this.selectPayProjectObj) {
						selectCount++
						payMoney += this.selectPayProjectObj[key].itemAmount;
						chargeItemIds.push(this.selectPayProjectObj[key].id)
					}
					this.selectCount = selectCount;
					this.payMoney = (payMoney / 100).toFixed(2);
					this.chargeItemIds = chargeItemIds;
				} catch (e) {
					//TODO handle the exception
					console.log(e);
				}
			},
			// 微信公众号H5支付
			async getBrandWCPayRequest() {
				try {
					if (this.JSBridge) {
						WeixinJSBridge.invoke(
							'getBrandWCPayRequest', {
								"appId": "wx2421b1c4370ec43b", //公众号ID，由商户传入     
								"timeStamp": "1395712654", //时间戳，自1970年以来的秒数     
								"nonceStr": "e61463f8efa94090b1f366cccfbbb444", //随机串     
								"package": "prepay_id=u802345jgfjsdfgsdg888",
								"signType": "MD5", //微信签名方式：     
								"paySign": "70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信签名 
							},
							function(res) {
								if (res.err_msg == "get_brand_wcpay_request:ok") {
									// 使用以上方式判断前端返回,微信团队郑重提示：
									//res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
								} else {
									uni.showToast({
										icon: "none",
										mask: true,
										title: "支付异常"
									})
								}
							});
						return
					}
					uni.showToast({
						icon: "none",
						mask: true,
						title: "支付环境异常"
					})
				} catch (e) {
					//TODO handle the exception
					console.log(e);
					uni.showToast({
						icon: "none",
						mask: true,
						title: e.message
					})
				}
			},
			// 倒计时5秒
			culDown() {
				const self = this;
				let second = 5;
				const timer = setInterval(() => {
				  second--;
				  if (second) {
					self.mask = true;
					uni.showLoading({
						title: '加载中'
					});
				  } else {
				    clearInterval(timer);
				    uni.hideLoading();
					self.mask = false;
				  }
				}, 1000);
			},
			// 点击缴费下单接口
			async clickPay() {
				try {
					console.log(this.JSBridge);
					this.dialogShow = false
					if (this.selectCount == 0) {
						uni.showToast({
							icon: "none",
							mask: true,
							title: "请选择缴费项目"
						})
						return
					}
					if (this.ChargeProDetail.notesFlag == 1) {
						if (!this.remarks) {
							uni.showToast({
								icon: "none",
								mask: true,
								title: "请填写备注信息"
							})
							return
						}
					}
					this.culDown();
					let data = await this.$http.post({
						url: orderApi + '/order-charge/app/charge/project/createOrder'
					}, {
						amount: this.payMoney * 100, //	金额		false	
						chargeItemIds: this.chargeItemIds.join(","), //	交费用项id集合多个交费项之间使用逗号分隔		false	
						mchId: this.ChargeProDetail.mchid, //	微信商户号		false	
						openId: this.allData.openId, //	用户标识		false	
						payPeopleType: 1, //	交费人类型1家长、2教师、3运营人员		false	
						payway: 1, //	交费方式1.小程序交费、2.现金交费		false	
						tradeId: this.ChargeProDetail.tradeId, //	订单号		false	
						userName: this.ChargeProDetail.userName, //	用户姓名		false	
						remark: this.remarks || '', //	备注		false
						wechatChannel: 1, //微信交费渠道1.小程序交费 2.微信公众号交费
						chargeId: this.allData.chargeId,
						schoolId: this.allData.schoolId,
						userId: this.allData.userId
					})
					
					if (data.code != 200) {
						uni.showToast({
							icon: "none",
							mask: true,
							title: data.msg || "缴费下单失败"
						})
						return
					}
					// 获取支付参数
					await this.getPayParams(data.data)
					uni.setStorageSync("prepayId", data.data)
				} catch (e) {
					//TODO handle the exception
					console.log(e);
					this.mask = false;
					uni.hideLoading()
					uni.showToast({
						icon: "none",
						mask: true,
						title: e.message
					})
				}
			},
			// 获取支付参数
			async getPayParams(prepayId) {
				try {
					let data = await this.$http.post({
						url: orderApi + '/order-charge/app/charge/project/getPayParams'
					}, prepayId)
					if (data.code != 200 || !data.data) {
						uni.showToast({
							icon: "none",
							mask: true,
							title: data.msg || "获取支付参数失败"
						})
						return
					}
					data.data.package = encodeURIComponent(data.data.package)
					data.data.paySign = encodeURIComponent(data.data.paySign)
					console.warn(`/pages/toPayAuth/main?` + OforS(data.data))
					jWeixin.miniProgram.redirectTo({
						url: `/pages/toPayAuth/main?` + OforS(data.data)
					});
				} catch (e) {
					//TODO handle the exception
					this.mask = false;
					uni.hideLoading();
					console.log(e);
					uni.showToast({
						icon: "none",
						mask: true,
						title: e.message
					})
				}
			},
			// 返回支付结果
			async returnPaymentResult(tradeId, payStatus) {
				try {
					if (!tradeId && !payStatus) {
						return
					}
					let data = await this.$http.get({
						url: orderApi + '/order-charge/app/charge/project/returnPaymentResult'
					}, {
						tradeId,
						payStatus
					})
					console.log(data)
					if (data.code != 200) {
						uni.showToast({
							icon: "none",
							mask: true,
							title: data.msg || "返回支付结果失败"
						})
						return
					}
				} catch (e) {
					//TODO handle the exception
					console.log(e);
					uni.showToast({
						icon: "none",
						mask: true,
						title: e.message
					})
				}
			}
		}
	}
</script>

<style lang="scss">
	page {
		background: #F3F5F6;
	}
	.masking {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0,0,0,0.4);
		z-index: 10;
	}
	.PaymentRsults {
		width: 580rpx;
		height: 480rpx;
		background: #FFFFFF;
		border-radius: 16rpx;
		text-align: center;
		text-align: center;
		margin: 0 auto;
		font-family: PingFang SC;

		image {
			top: 115rpx;
		}

		.PaymentRsultsTxt {
			height: 34rpx;
			font-size: 36rpx;
			font-weight: bold;
			color: #333333;
			text-align: center;
			margin: 0 auto;
			margin-top: 115rpx;
		}
	}

	.PayProject,
	.remarks {
		width: 686rpx;
		background: #FFFFFF;
		border-radius: 16rpx;
		margin: 0 auto;
	}

	.PayProject {
		height: 460rpx;
		margin-top: 20rpx;

		.ProjectBox {
			height: 350rpx;
			overflow: auto;

			.tabNames {
				justify-content: flex-start;
				height: 100%;
			}

			.ProjectItem {
				width: 628rpx;
				height: 100rpx;
				margin: 0 auto;
				border: 2rpx solid #E6E6E6;
				border-radius: 16rpx;
				margin-top: 19rpx;
			}

			.selectProjectItem {
				border: 2rpx solid #01CB88 !important;
				background-color: rgba(1, 203, 136, 0.1);
			}

			.ProjectName {
				margin-left: 25rpx;
				display: flex;
				justify-content: flex-start;
				align-items: center;

				image {
					display: inline-block;
				}

				text {
					display: inline-block;
					width: 176rpx;
					overflow: hidden;
					word-break: break-all;
					margin-left: 16rpx;
					white-space: nowrap;
					text-overflow: ellipsis;
				}
			}

			.ProjectName,
			.ProjectType {
				font-size: 30rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #333333;
			}

			.ProjectType {
				width: 120rpx;
				margin-left: 40rpx;
			}

			.money {
				font-size: 32rpx;
				font-family: DIN;
				font-weight: bold;
				color: #01CB88;
				width: 32%;
				text-align: right;
			}

			.money::before {
				content: "￥";
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: bold;
				color: #01CB88;
			}

		}

		.tabNames {
			font-size: 28rpx;
			font-family: PingFang SC;
			font-weight: 500;
			color: #999999;
			justify-content: space-around;
			display: flex;
			align-items: center;

			height: 87rpx;
			line-height: 87rpx;
		}
	}

	.remarks {
		height: 220rpx;
		margin-top: 20rpx;

		textarea {
			width: 100%;
			height: 100%;
			padding-left: 30rpx;
		}

		.remarksTxt {
			height: 80rpx;
			line-height: 80rpx;
			font-size: 32rpx;
			font-family: PingFang SC;
			font-weight: bold;
			color: #333333;
			margin-left: 66rpx;
			position: relative;
		}

		.remarksTxt:before {
			content: " ";
			width: 25rpx;
			height: 25rpx;
			background: #01CB88;
			border-radius: 50%;
			position: absolute;
			z-index: 100;
			top: 10rpx;
			left: -40rpx;
		}

		.remarksTxt:after {
			content: " ";
			width: 25rpx;
			height: 25rpx;
			background: #FFB62D;
			border-radius: 50%;
			position: absolute;
			z-index: 99;
			left: -32rpx;
			top: 10rpx;
		}


		.remarksTextarea {
			width: 222rpx;
			font-size: 32rpx;
			font-family: PingFang SC;
			font-weight: 500;
			color: #CCCCCC;
			// padding-left: 30rpx;
		}
	}


	@media (min-height: 650px) {
		.bottomOper {
			position: fixed;
			left: 0;
			right: 0;
			bottom: 30rpx;
		}
	}


	.bottomOper {
		height: 128rpx;
		background: #FFFFFF;
		width: 100%;
		margin-top: 20rpx;
		margin-bottom: 30rpx;


		.buttonContent {
			display: flex;
			align-items: center;
			height: 100%;
			justify-content: space-around;
			width: 689rpx;
			margin: 0 auto;

			.left {
				.zongji {
					width: 65rpx;
					font-size: 28rpx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #333333;
				}

				.money {
					width: 125rpx;
					font-size: 36rpx;
					font-family: DIN;
					font-weight: bold;
					color: #01CB88;
					line-height: 36rpx;
				}

				.money::before {
					content: "￥";
					font-size: 28rpx;
					font-family: PingFang SC;
					font-weight: bold;
					color: #01CB88;
				}

				.xieyi {
					font-size: 20rpx;
					font-family: PingFang SC;
					font-weight: 500;
				}

				.xieyi text:nth-child(1) {
					color: #999999;
				}

				.xieyi text:nth-child(2) {
					color: #01CB88;
				}



			}

			.right {
				width: 240rpx;
				height: 72rpx;
				background: rgba(1, 203, 136, 1);
				border-radius: 36rpx;

				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #FFFFFF;
				text-align: center;
				line-height: 72rpx;

				// margin-right: 32rpx;


			}

		}
	}

	.headerImg {
		width: 750rpx;
		height: 480rpx;
		background-image: url(https://xiaopay2020.oss-cn-shenzhen.aliyuncs.com/static/weapp/StudentPayment/bg.png);
		background-repeat: no-repeat;
		background-size: 100% 100%;
	}

	.cardInfo {
		width: 686rpx;
		height: 444rpx;
		background: #FFFFFF;
		border-radius: 16rpx;
		position: relative;
		margin: 0 auto;
		top: 37rpx;
		overflow: hidden;
		font-family: PingFang SC;

		.title {
			width: 370rpx;
			// height: 34rpx;
			font-size: 36rpx;
			font-weight: 800;
			color: #333333;
			margin: 0 auto;
			margin-top: 60rpx;
			text-align: center;
		}

		.title2 {
			width: 599rpx;
			height: 55rpx;
			font-size: 24rpx;
			font-weight: 500;
			color: #999999;
			margin: 0 auto;
			text-align: center;
			margin-top: 24rpx;
		}

		.botto {
			.rowInfo {
				font-size: 30rpx;
				font-family: PingFang SC;
				font-weight: 500;
				margin-left: 30rpx;
				line-height: 60rpx;
			}

			.name {
				width: 128rpx;
				color: #999999;
			}

			.value {
				width: 58rpx;
				color: #333333;
			}
		}
	}


	.cardInfo:before,
	.cardInfo:after {
		content: " ";
		width: 100%;
		height: 0px;
		position: absolute;
	}

	.cardInfo:before {
		border-top: 16rpx dotted #01CB88;
		left: 16rpx;
		top: -6rpx;

	}
</style>
