<template>
	<scroll-view scroll-y="true" class="scroll-Y">
    <wx-points-commit ref='wxPointsCommit'></wx-points-commit>

		<view class="wrap">
			<view class="form">
				<view class="form-item">
					<text class="label">车牌</text>
					<text>{{parkOrderEntity.carno}}</text>
				</view>
				<view class="form-item">
					<text class="label">入场时间</text>
					<text>{{parkOrderEntity.entertime}}</text>
				</view>
				<view class="form-item">
					<text class="label">停车时长</text>
					<text>{{parkOrderEntity.servicehour}}小时</text>
				</view>
				<view class="form-item">
					<text class="label"></text>
					<text>订单金额：¥{{parkOrderEntity.servicefee}}</text>
				</view>
			</view>
			<view class="form">
				<view class="form-item" @click="openPark" v-if="parkInfoEntity.isuseticket == 1">
					<text class="label">停车券</text>
					<view>
						<text>{{parkingCouponName}}</text>
						<uni-icons type="arrowright" size="20" class="arrowright"></uni-icons>
					</view>
				</view>
        <view class="form-item" v-if="couponfee">
        	<text class="label">停车券抵扣</text>
        	<text style="color: #ed1c24;">¥{{couponfee}}元</text>
        </view>
				<view class="form-item" @click="openIntegral" v-if="parkInfoEntity.isuseintegral == 1">
					<text class="label">积分抵扣</text>
					<view>
						<text>{{integralName}}</text>
						<uni-icons type="arrowright" size="20" class="arrowright"></uni-icons>
					</view>
				</view>
        <view class="form-item" v-if="bonusfee">
        	<text class="label">积分抵扣</text>
        	<text style="color: #ed1c24;">¥{{bonusfee}}元</text>
        </view>
			</view>
      <!-- 福州 -->
      <view class="tip" v-if="mallid === '000586'">注：每次支付最多抵扣{{parkInfoEntity.maxonetimediscount}}元</text></view>
      <!-- 天津 -->
      <view class="tip" v-if="mallid === '000719'">注：每次支付最多抵扣{{parkInfoEntity.maxonetimediscount}}元</text></view>
      <!-- 慈溪 -->
      <view class="tip" v-if="mallid === '00000914'">注：周一每次支付最多抵扣50元，周二至周日每次支付最多抵扣6元</text></view>
			<view class="tip" v-if="mallid !== '000586' && mallid !== '000719' && mallid !== '00000914'">注：卡券和积分每天累计最多抵扣<text>{{parkInfoEntity.maxonedaydiscount}}元</text>,<text>每次支付最多抵扣{{parkInfoEntity.maxonetimediscount}}元，今日已抵扣{{todayDiscountMoney}}元</text>
			</view>
		</view>
		<!-- 底部导航 -->
		<view class="submit_bar">
			<view class="submit_text">
				<view class="text_top">
					<text>实付款：</text>
					<text class="price">¥ {{total}}</text>
				</view>
				<view class="text_bottom" v-if="parkingCouponName !== '' || integralName !== ''">
					<text v-if="parkingCouponName && !integralName">已选择：{{parkingCouponName}}</text>
					<text v-if="integralName && !parkingCouponName">已选择：{{integralName}}</text>
					<text v-if="parkingCouponName && integralName">已选择：{{parkingCouponName+'/'+integralName}}</text>
				</view>
			</view>
			<uni-button class="mini-btn" type="warn" size="mini" @click="onSubmit">立即支付</uni-button>
		</view>
		<!-- 停车券弹窗 -->
		<view class="parking_pop popup">
			<uni-popup ref="parkingCoupon_popup" type="bottom" class="uni-popup" style="z-index: 1000">
				<view class="popup_wrap parkingCoupon_wrap">
					<div class="popup_title">
						<text>选择停车券</text>
						<uni-icons type="clear" size="30" color="#d4d4d4" class="clear" @click="closePark"></uni-icons>
					</div>
					<view class="popup_content">
						<scroll-view scroll-y="true" style="height: 500rpx;" class="scroll">
							<view class="radio-group">
								<view class="uni-list-cell uni-list-cell-pd" @click="parkChange(index, item)"
									v-for="(item, index) in memberTicketList" :key="index">
									<view style="color: #999; font-size: 28rpx;">{{item.ticketName}}</view>
									<image v-if="item.checked" :src="localimgPic + 'car-checked.png'" mode="widthFix" />
									<image v-else :src="localimgPic + 'pay-unchecked.png'" mode="widthFix" />
								</view>
							</view>
						</scroll-view>
						<view class="popup_button">
							<text class="cancel_btn" @click="closePark">取消</text>
							<text class="ok_btn" @click="doParkOK">确定</text>
						</view>
					</view>
					<!-- <view v-html="formText">{{formText}}</view> -->
				</view>
			</uni-popup>
		</view>
		<!-- 积分抵扣弹窗 -->
		<view class="integral_pop popup">
			<uni-popup ref="integral_popup" type="bottom" class="uni-popup" style="z-index: 1000">
				<view class="popup_wrap integral_wrap">
					<div class="popup_title">
            <view style="display: flex;align-items: center;justify-content: space-between;flex: 1;">
              <text>选择积分抵扣</text>
              <text style="color: #ed1c24;">我的积分：{{exintegral || 0}}</text>
            </view>
						<uni-icons type="clear" size="30" color="#d4d4d4" class="clear" @click="closeIntegral">
						</uni-icons>
					</div>
					<view class="popup_content">
						<scroll-view scroll-y="true" style="height: 500rpx;" class="scroll">
							<radio-group class="radio-group" @change="integralChange">
								<label class="uni-list-cell uni-list-cell-pd"
									v-for="(item, index) in parkIntegraltomoneyList" :key="index">
									<view style="color: #999; font-size: 28rpx;">{{item.name}}</view>
									<view>
										<radio :value="item.value" color="#ed1c24" />
									</view>
								</label>
							</radio-group>
						</scroll-view>
						<view class="popup_button">
							<text class="cancel_btn" @click="closeIntegral">取消</text>
							<text class="ok_btn" @click="doIntegralOK">确定</text>
						</view>
					</view>
				</view>
			</uni-popup>
		</view>
	</scroll-view>
</template>

<script>
	import uniPop from '@/components/uni-popup/uni-popup.vue'
	const app = getApp()
	export default {
		components: {
			uniPop
		},
		data() {
			return {
				parkOrderEntity: {}, // 停车信息
				parkInfoEntity: {},
				price: 0,
				parkingCouponVal: '',
				parkingCouponName: '',
				integralVal: '',
				integralName: '',
				carno: '', // 车牌号
				todayDiscountMoney: 0, // 今日抵扣金额
				memberTicketList: [{
					ticketValue: 0,
					ticketName: '不使用'
				}], //会员停车券
				parkIntegraltomoneyList: [{
					integral: 0,
					name: '不使用',
					value: 0
				}], //积分抵现
				bonus: '', // 积分
				bonusfee: 0, // 积分抵钱
				couponcode: '', // 停车券
				couponfee: 0, // 停车抵钱
				payfee: '', // 微信钱
				ind: '', // 停车券索引
				total: 0, // 实付款
				localimgPic: '',
				formText: '',
        mallid: '',
        exintegral: '' // 我的积分
			}
		},
		// 分享好友
		onShareAppMessage: function(res) {
			return {
				title: '停车缴费', // 分享标题
				// desc: this.params.shareDescribe, // 分享描述
				imageUrl: '', // 分享图标
				path: `/pages/parkingFee/parkingFeeForm?carno=${this.carno}&mallid=${app.globalData.mallid}`
			}
		},
		// 分享朋友圈
		onShareTimeline: function(res) {
			return {
				title: '停车缴费', // 分享标题
				// desc: this.params.shareDescribe, // 分享描述
				imageUrl: '', // 分享图标
				path: `/pages/parkingFee/parkingFeeForm?carno=${this.carno}&mallid=${app.globalData.mallid}`
			}
		},
		onLoad(option) {
			this.localimgPic = this.$staticPicUrl + '/wxminilocalimg/parkingFee/'
			this.carno = option.carno
      this.mallid = app.globalData.mallid
			// #ifdef H5
			app.globalData.member = JSON.parse(uni.getStorageSync('member'))
			app.globalData.userInfo = JSON.parse(uni.getStorageSync('userinfo'))
			app.globalData.openId = app.globalData.userInfo.openid
      this.getTicket()
			// #endif
			// 场景二维码记录(是否扫码进入)
			app.globalData.paramsScene = {}
			this.$saveSceneQrcodeDetail('page', 'parkingFeeForm', '停车缴费', '', '', '', '')
			this.createParkOrder()
      this.getVoterBonus()
		},
		methods: {
			// h5获取配置---公众号支付
			getTicket: function() {
				let self = this
				var datas = {
					groupId: app.globalData.groupId,
					mallid: app.globalData.mallid,
					url: window.location.href.split("#")[0]
				}
				self.$md(datas)
				uni.request({
					url: self.$baseURL + "api/1.0/login/getTicket",
					method: 'POST',
					data: datas,
					header: JSON.parse(uni.getStorageSync('handleUser')),
					success: (res) => {
						if (res.data.code == 0) {
							self.$wx.config({
								debug: false, // 开启调试模式
								appId: res.data.data.appId, // 必填，公众号的唯一标识
								timestamp: res.data.data.timestamp, // 必填，生成签名的时间戳
								nonceStr: res.data.data.nonceStr, // 必填，生成签名的随机串
								signature: res.data.data.signature, // 必填，签名
								jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表
							});
							self.$wx.ready(function() {
								self.$wx.checkJsApi({
									jsApiList: ['chooseWXPay'],
									success: res => {
										console.log('checked api:', res)
									},
									fail: err => {
										console.log('check api fail:', err)
									}
								})
							});
							self.$wx.error(function(res) {
								console.log('err', res)
							});
						} else {
							uni.showToast({
								title: res.data.msg,
								duration: 2000,
								icon: 'none'
							})
						}
					}
				});
			},
			// 获取积分
			getVoterBonus: function() {
				var params = {
					groupId: app.globalData.groupId,
					mallid: app.globalData.mallid,
					mobile: app.globalData.member.mobile
				}
				this.$md(params)
				this.$request({
					method: "POST",
					url: this.$baseURL + "api/1.0/member/getMemberInfo",
					header: JSON.parse(uni.getStorageSync('handleUser')),
					data: params,
					}).then((r) => {
						if (r.data.code == 0) {
							var result = r.data.data;
							this.exintegral = result.currnentintegral + '';
						} else {
							uni.showToast({
								title: r.data.msg,
								duration: 2000,
								icon: 'none'
							})
						}
					}).catch(err => {
						console.log(err)
				});
			},
      // 创建订单
			createParkOrder: function() {
        this.parkIntegraltomoneyList = []
        this.memberTicketList = []
				uni.showLoading({
					title: '加载中'
				});
				let params = {
					mallid: app.globalData.mallid,
					vipcode: app.globalData.member.vipcode,
					groupId: app.globalData.groupId,
					carno: this.carno,
					openId: app.globalData.openId
				}
				this.$md(params)
				this.$request({
					url: this.$baseURL + 'api/1.0/park/createParkOrder',
					data: params,
					method: 'POST',
					header: JSON.parse(uni.getStorageSync('handleUser')),
					}).then((res) => {
						uni.hideLoading();
						if (res.data.code === 0) {
							const data = res.data.data
							this.parkOrderEntity = data.parkOrderEntity
							this.parkInfoEntity = data.parkInfoEntity
              if (data.parkIntegraltomoneyList) {
                this.parkIntegraltomoneyList.push(...data.parkIntegraltomoneyList)
              }
              console.log('积分', this.parkIntegraltomoneyList)
              if (data.memberTicketList) {
                this.memberTicketList.push(...data.memberTicketList)
                this.memberTicketList.map(t => {
                	t.checked = false
                })
              }
							this.parkOrderEntity.servicefee = this.parkOrderEntity.servicefee / 100
							this.total = this.parkOrderEntity.servicefee
              this.bonus = 0
              this.payfee = 0
              this.couponfee = 0
              this.bonusfee = 0
              this.ind = 0
							setTimeout(() => {
								this.createParkOrder()
							}, 180000)
						} else {
							uni.showToast({
								title: res.data.msg,
								duration: 2000,
								icon: 'none'
							})
						}
					}).catch(err => {
						console.log(err)
				});
			},
			// 打开停车券
			openPark: function() {
				this.$refs['parkingCoupon_popup'].open()
			},
			// 关闭停车券
			closePark: function() {
				this.$refs['parkingCoupon_popup'].close()
			},
			// 停车券选择
			parkChange: function(index, item) {
				item.checked = !item.checked
				if (index === 0 && item.checked) {
					this.memberTicketList.map(t => {
						t.checked = false
					})
					this.memberTicketList[index].checked = true
				} else {
					this.memberTicketList[0].checked = false
				}
				this.ind = index
				this.$forceUpdate()
			},
			// 确定停车券
			doParkOK: function() {
				const filter_data = this.memberTicketList.filter(t => t.checked == true && t.ticketValue !== 0)
				if (this.todayDiscountMoney == this.parkInfoEntity.maxonedaydiscount) {
					uni.showToast({
						title: '今日抵扣金额上限',
						icon: 'none'
					})
				} else {
					let couponcode = ''
					let couponfee = 0
					if (filter_data.length === 0) { //不使用
						this.couponfee = 0
						this.couponcode = ''
						let price = Math.round(this.bonusfee * 100 + this.couponfee * 100) / 100
						this.total = Math.round((this.parkOrderEntity.servicefee - price) * 100) / 100
						// console.log('停车券积分', this.couponcode)
						// console.log('不使用停车券抵扣', this.couponfee)
						// console.log('不使用停车券-价钱', this.total)
						this.closePark()
					} else { // 使用
						filter_data.map(t => {
							couponcode += t.couponCode + '#'
							couponfee += t.ticketValue
						})
						this.couponfee = couponfee
						this.couponcode = couponcode
						let price = this.bonusfee + this.couponfee
						if (price > this.parkInfoEntity.maxonetimediscount) {
							uni.showToast({
								title: '每次最多抵扣'+this.parkInfoEntity.maxonetimediscount+'元',
								icon: 'none'
							})
							// 对选中不满足条件的进行删除
							this.memberTicketList[this.ind].checked = false
							this.couponfee = Math.round(this.couponfee - this.memberTicketList[this.ind].ticketValue)
							let couponcodeSplit = this.couponcode.split('#')
							couponcodeSplit.map((t, i) => {
								if (t.couponcode === this.memberTicketList[this.ind].couponcode) {
									couponcodeSplit.splice(i, 1)
								}
							})
							this.couponcode = couponcodeSplit.join("#")
							// console.log(this.couponcode)
							// console.log(this.couponfee)
						} else {
							this.price = price
							// 抵扣金额超出订单金额,实付款为0
							if (this.price > this.parkOrderEntity.servicefee) {
								this.total = 0
							} else {
								this.total = Math.round((this.parkOrderEntity.servicefee - price) * 100) / 100
							}
							// console.log('停车券积分', this.couponcode)
							// console.log('停车券抵扣', this.couponfee)
							// console.log('价钱', this.total)
							this.closePark()
						}
					}
				}
			},
			// 打开抵扣积分
			openIntegral: function() {
				this.$refs['integral_popup'].open()
			},
			// 关闭抵扣积分
			closeIntegral: function() {
				this.$refs['integral_popup'].close()
			},
			// 抵扣积分选择
			integralChange: function(e) {
				let val = e.detail.value
				this.bonusfee = Number(val)
				this.parkIntegraltomoneyList.map(t => {
					if (t.value == val) {
						this.bonus = t.integral
					}
				})
			},
			// 确定抵扣积分
			doIntegralOK: function() {
				let price = Math.round(this.bonusfee * 100 + this.couponfee * 100) / 100
				if (this.todayDiscountMoney == this.parkInfoEntity.maxonedaydiscount) {
					uni.showToast({
						title: '今日抵扣金额上限',
						icon: 'none'
					})
				} else {
					if (price > this.parkInfoEntity.maxonetimediscount) {
						uni.showToast({
							title: '每次最多抵扣'+this.parkInfoEntity.maxonetimediscount+'元',
							icon: 'none'
						})
					} else {
						this.price = price
						// 抵扣金额超出订单金额,实付款为0
						if (this.price > this.parkOrderEntity.servicefee) {
							this.total = 0
						} else {
							this.total = Math.round(this.parkOrderEntity.servicefee * 100 - price * 100) / 100
						}
						console.log('积分抵扣', this.bonusfee)
						console.log('价钱', this.total)
						this.closeIntegral()
					}
				}
			},
			// 支付
			onSubmit: function() {
				uni.showLoading({
					title: '加载中'
				});
				let params = {
					mallid: app.globalData.mallid,
					groupId: app.globalData.groupId,
					orderno: this.parkOrderEntity.orderno,
					// #ifdef MP-WEIXIN
					createuser: 'sys_miniprogram'
					// #endif
					// #ifdef H5
					createuser: 'sys_gzh'
					// #endif
				}
				let url = ''
				// 是否微信支付
				if (this.total !== 0) {
					params.payfee = this.total * 100
					url = 'api/1.0/park/weixinPay'
					// 广福路
					if (app.globalData.groupId === '1329609284362932225' && app.globalData.mallid === '000002') {
						url = 'interfaceController/park/icbcPay'
					}
				} else {
					url = 'api/1.0/park/notWeixinPay'
				}
				// 是否积分抵扣
				if (this.bonus) {
					params.bonus = this.bonus
					params.bonusfee = this.bonusfee * 100
				}
				// 是否停车券抵扣
				if (this.couponcode) {
					params.couponcode = this.couponcode
					params.couponfee = this.couponfee * 100
				}
				// 积分+卡券+微信
				if (this.bonus && this.couponcode && this.total !== 0) {
					params.paytype = 7
				}
				// 卡券+微信
				if (!this.bonus && this.couponcode && this.total !== 0) {
					params.paytype = 6
				}
				// 积分+微信
				if (this.bonus && !this.couponcode && this.total !== 0) {
					params.paytype = 5
				}
				// 积分+卡券
				if (this.bonus && this.couponcode && this.total == 0) {
					params.paytype = 4
				}
				// 微信
				if (!this.bonus && !this.couponcode && this.total !== 0) {
					params.paytype = 3
				}
				// 卡券
				if (!this.bonus && this.couponcode && this.total == 0) {
					params.paytype = 2
				}
				// 积分
				if (this.bonus && !this.couponcode && this.total == 0) {
					params.paytype = 1
				}
				console.log('支付', params)
				this.$md(params)
				const that = this
				this.$request({
					url: that.$baseURL + url,
					data: params,
					method: 'POST',
					header: JSON.parse(uni.getStorageSync('handleUser')),
					}).then((res) => {
						uni.hideLoading();
						if (res.data.code === 0) {
							// 需要微信支付传参
							if (that.total !== 0) {
								// #ifdef MP-WEIXIN
								var prepayJson = JSON.parse(res.data.data);
								uni.requestPayment({
									provider: 'wxpay',
									timeStamp: prepayJson.timeStamp,
									nonceStr: prepayJson.nonceStr,
									package: prepayJson.package1,
									signType: prepayJson.signType,
									paySign: prepayJson.paySign,
									success: function(res) {
										console.log(that.parkOrderEntity.orderno)
										uni.navigateTo({
											url: './parkingFeeDetail?orderno=' + that
												.parkOrderEntity.orderno
										})
									},
									fail: function(err) {
										uni.showToast({
											title: '支付已取消！',
											icon: 'none',
											duration: 2000
										})
									}
								});
								// #endif
								// #ifdef H5
								if (app.globalData.groupId === '1329609284362932225' && app.globalData
									.mallid === '000002') {
									that.formText = res.data.data
									that.$nextTick(() => {
										document.querySelector('body').innerHTML = that.formText;
										document.forms[0].submit()
										// document.forms['alipaysubmit'].submit()
										// console.log('idauto_submit_form', document.forms['alipaysubmit'])
										// document.getElementByName('idauto_submit_form').submit()
									})
								} else {
									var prepayJson = JSON.parse(res.data.data);
									that.$wx.chooseWXPay({
										timestamp: result.prepayId.timeStamp, // 支付签名时间戳
										nonceStr: result.prepayId.nonceStr, // 支付签名随机串，不长于 32 位
										package: result.prepayId
										.package1, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
										signType: 'MD5', // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
										paySign: result.prepayId.paySign, // 支付签名
										success(res) {
											// 支付成功后的回调函数
											console.log(that.parkOrderEntity.orderno)
											uni.navigateTo({
												url: './parkingFeeDetail?orderno=' + that
													.parkOrderEntity.orderno
											})
											// cb(res);
										},
										fail(err) {
											uni.showToast({
												title: '支付已取消！',
												icon: 'none',
												duration: 2000
											})
										}
									});
								}
								// #endif
							} else {
								uni.navigateTo({
									url: './parkingFeeDetail?orderno=' + that.parkOrderEntity
										.orderno
								})
							}
						} else {
							uni.showToast({
								title: res.data.msg,
								duration: 2000,
								icon: 'none'
							})
						}
					}).catch(err => {
						console.log(err)
				});
			}
		}
	}
</script>

<style lang="less" scoped>
	.scroll-Y {
		width: 100%;
		display: flex;
		flex-direction: column;
		height: 100vh;
		background: #f2f2f2;
	}

	.wrap {
		display: flex;
		flex-direction: column;
		width: 100%;

		.form {
			margin-top: 10rpx;
			display: flex;
			flex-direction: column;
			background: #fff;

			.form-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 25rpx 35rpx;
				box-sizing: border-box;
				border-bottom: 1px solid #f2f2f2;

				text {
					font-size: 28rpx;
					color: #999;
				}

				.label {
					color: #000;
				}

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

		.tip {
			padding: 17rpx 38rpx;
			color: #999;
			font-size: 28rpx;

			text {
				color: #999;
				font-size: 28rpx;
			}
		}
	}

	// 底部导航
	.submit_bar {
		position: fixed;
		bottom: 0;
		left: 0;
		z-index: 99;
		width: 100%;
		padding-bottom: env(safe-area-inset-bottom);
		background-color: #fff;
		user-select: none;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.submit_text {
			padding: 0 40rpx;
			box-sizing: border-box;
			display: flex;
			flex-direction: column;
			flex: 1;

			text {
				font-size: 28rpx;
				color: #999;
			}

			.text_top {
				display: flex;
				align-items: center;

				text {
					color: #000;
				}

				.price {
					color: #ed1c24;
					font-size: 30rpx;
				}
			}

			.text_bottom {}
		}

		button {
			margin: 0;
			padding: 0;
			height: 100rpx;
			background: linear-gradient(to right, #ff6034, #ee0a24);
			width: 220rpx;
			font-weight: 500;
			border: none;
			border-radius: 0;
			line-height: 100rpx;
			text-align: center;
			transition: opacity .2s;
		}
	}

	// 弹窗
	.popup {
		.popup_wrap {
			width: 100%;
			display: flex;
			flex-direction: column;
			background: #fff;
			border-radius: 20rpx 20rpx 0 0;

			text {
				color: #999;
				font-size: 28rpx;
			}
		}

		.popup_title {
			width: 100%;
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 30rpx 42rpx;
			box-sizing: border-box;
			border-bottom: 1px solid #f2f2f2;
		}

		.popup_content {
			width: 100%;
			display: flex;
			flex-direction: column;
			flex: 1;

			.radio-group {
				display: flex;
				flex-direction: column;
				width: 100%;
				padding: 0 42rpx;
				box-sizing: border-box;

				image {
					width: 48rpx;
					height: 48rpx;
				}

				.uni-list-cell-pd {
					display: flex;
					justify-content: space-between;
					padding: 42rpx 0;
					box-sizing: border-box;
					align-items: center;
					border-bottom: 1px solid #f2f2f2;
					margin: 0;

					.radio {
						display: flex;
						justify-content: space-between;
						align-items: center;
						width: 100%;
					}
				}
			}
		}

		.popup_button {
			width: 100%;
			display: flex;
			align-items: center;

			text {
				width: 50%;
				height: 110rpx;
				line-height: 110rpx;
				text-align: center;
			}

			.cancel_btn {
				background: #fff;
				color: #ed1c24;
			}

			.ok_btn {
				background: #ed1c24;
				color: #fff;
			}
		}
	}
</style>
