<template>
	<view class="content">
		<!-- 支付剩余时间 -->
		<view style="display: block ruby;">
			<view class="break_time">
				交易剩余时间
			</view>
			<uv-count-down style="margin-top: 10px;margin-left: 10px;" :time="new Date(allTime).getTime() + 2 * 60 * 1000 - new Date().getTime()" format="mm:ss" @change="change" @finish="finish(countDownTime,allTime)"></uv-count-down>
			
		</view>
		
		<!-- <uv-count-down :time="56687" format="mm:ss" @finish="finish(countDownTime)"></uv-count-down> -->
		<!-- <view class="break_time">交易剩余时间15:00</view> -->
		<view class="break_money">¥{{countMoney}}</view>
		<!-- 住房信息 -->
		<view class="zhufang">住房信息</view>
		<view class="two_all">
			<view class="select-time">
				<view class="select-time-one">
				  <text class="select-list-time">{{startTime}}
					<text class="select-list">{{startWeek}}</text>
				  </text>
				</view>
				<view class="select-center">
					<view class="select-line1"></view>
					<view class="select-circle">{{ruzhu_num}}晚</view>
					<view class="select-line2"></view>
				</view>
				<view class="select-time-one">
				  <text class="select-list-time">{{endTime}}
					<text class="select-list">{{endWeek}}</text>
				  </text>
				</view>
			</view>
			<!-- 房型信息 -->
			<view class="select_name">
			<!-- {{roomName}} -->
			</view>
			<view class="select_type" v-if="roomType==1">全日房</view>
			<view class="select_type" v-else-if="roomType==2">钟点房</view>
			<view class="select_detail">
				{{roomArea}}㎡
				<text style="margin-left: 20px;">{{roomConfiguration}}</text>
				<!-- <text style="margin-left: 20px;">窗户位于走廊/窗户较小</text> -->
			</view>
		</view>
		<!-- 支付方式 -->
		<view class="pay-way">支付方式</view>
		<view class="pay-list">
			<view class="iconweixin"></view>
			<view class="item">微信支付</view>
			<label class="radio">
				<radio value="" color="rgba(0, 97, 255, 1)" :checked="pay_way == '微信支付'" :disabled="money > 0" />
				</radio>
			</label>
		</view>
		<!-- 确认支付 -->
		<view class="quwer" @click="queZhifu1">确认支付</view>
	</view>
</template>

<script>
	import {
		getorderdetail,
		quxiaoorder,
		getorderpay,
		getchapay
	} from '../../utils/api_hotel.js'
	export default {
		data() {
			return {
				orderId:'',//订单id
				startTime:'',//到店日期
				endTime:'',//离店日期
				startWeek:'',// 默认入店日
				endWeek:'',// 默认离店
				ruzhu_num:1,//入住夜晚
				pay_way: '微信支付',
				roomName:'',
				roomType:1,
				roomArea:'',
				roomConfiguration:'',//房间配置
				countMoney:'',
				countDownTime:null,
				allTime:'',
				orderNumber:'', //订单号
				houseNumberId:'', //房间号id
				money:'',
				
				appId: "",     //公众号ID，由商户传入
				timeStamp: "",     //时间戳，自1970年以来的秒数     
				nonceStr: "",      //随机串     
				package: "",
				signType: "",     //微信签名方式：     
				paySign:'',
				flag: true //是否弹出返回提示框
			}
		},
		onLoad(option) {
			this.orderId=option.houseOrderId
		},
		onShow() {
			this.getorderXiang()
		},
		onBackPress() {
			if (this.flag) {
				uni.showModal({
					title: "提示",
					content: "您确定要放弃付款吗？",
					duration: 1500,
					success: (res) => {
						if (res.confirm) {
							this.flag = false
							uni.navigateBack({
								delta: 1, //返回层数，2则上上页
							})
							return true
						} else {
							this.flag = true
							return true
						}
					}
				})
				return true
			} else {
				return false
			}
		},
		methods: {
			// 截取 url中的code方法
			handleUrlCode() {
				var url = location.href; //获取打开的公众号的路径
				var theRequest = new Object();
				if (url.indexOf('?') != -1) {
					var str = url.substr(url.indexOf('?') + 1);
					var strs = str.split('&');
					for (var i = 0; i < strs.length; i++) {
						var items = strs[i].split('=');
						if(strs[i].split('=')[0]=='code'){
							var code=strs[i].split('=')[1]
						
						}
						theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
						theRequest[i] = strs[i].split('=')[1];
						localStorage.setItem('code',code)
					}
				// alert(code+'p')
				
				}
			},
			// 订单详情
			getorderXiang() {
				this.payMount=0
				  let _self = this
				  var data="?houseOrderId="+this.orderId
				  getorderdetail(data).then((res) => {
					if (res.success) {
						this.roomName=res.data.roomNumber
						this.roomType=res.data.house.roomType
						this.roomArea=res.data.house.roomArea
						this.roomConfiguration=res.data.house.roomConfiguration
						this.countMoney=res.data.houseOrder.payPrice
						this.ruzhu_num=res.data.houseOrder.liveDay
						this.startTime=(res.data.houseOrder.reserveLiveTime).substring(5,10)
						this.endTime=(res.data.houseOrder.reserveLeaveTime).substring(5,10)
						this.startWeek=this.getweekday(res.data.houseOrder.reserveLiveTime)
						this.endWeek=this.getweekday(res.data.houseOrder.reserveLeaveTime)
						
						this.orderNumber=res.data.houseOrder.orderNumber //订单号
						this.houseNumberId=res.data.houseOrder.houseNumberId //房间号id
						// 兼容ios部分系统转换时间格式
						this.allTime = res.data.houseOrder.createTime.replace(/-/g, '/')
						this.countDownTime = new Date(this.allTime).getTime() + 15 * 60 * 1000 - new Date().getTime()
						return;
					} else {
						console.log('订单详情获取失败')
					}
					}).catch((err) => {
						this.$message.error(err.message)
					});
			},
			// 计算指定时间是周几
			getweekday(date){
			   // date例如:'2022-03-05'
				var weekArray = new Array("周日","周一", "周二", "周三", "周四", "周五", "周六")
				var weeka  = weekArray[new Date(date).getDay()]
				return weeka
			},
			//确认支付
			queZhifu1(){
				let _self = this 
				var data={
					"usersId": localStorage.getItem('usersId'),
					"houseOrderId": this.orderId,//订单号idlocalStorage.getItem('orderId')
					"totalPrice":this.countMoney  //支付金额
				}
				getorderpay(data).then((res) => {
					if (res.success) {
						if(res.data){
							_self.appId=res.data.appId
							_self.timeStamp=res.data.timeStamp
							_self.nonceStr=res.data.nonceStr
							_self.package=res.data.packageVal
							_self.signType=res.data.signType
							_self.paySign=res.data.paySign
							_self.onBridgeReady();
						}else{
							//免费
							uni.showModal({
								content:'若需取消预订，应在入住当日 13 点之前进行操作；若不取消，则需在 18 点前携带身份证或电子身份证至前台办理入住手续，否则可能被加入黑名单。退房时间为次日 13 点之前。另外，公寓提醒你注意节约水电，一旦超出正常使用额度，将会产生额外费用。',
								success: (res) => {
									uni.reLaunch({
										url:'/pages/zhifuchenggong/zhifuchenggong'
									})
								},
								fail: (e) => {
									uni.reLaunch({
										url:'/pages/zhifuchenggong/zhifuchenggong'
									})
								},
							})
						}
						
					} else if(res.code=='500'){
						// uni.showModal({
						// 	content:res.message
						// })
					}
				}).catch((err) => {
				});
			},
			onBridgeReady() {
			    WeixinJSBridge.invoke('getBrandWCPayRequest', {
			        "appId": this.appId,     //公众号ID，由商户传入     
			        "timeStamp": this.timeStamp,     //时间戳，自1970年以来的秒数     
			        "nonceStr": this.nonceStr,      //随机串     
			        "package": this.package,
			        "signType": this.signType,     //微信签名方式：     
			        "paySign": this.paySign //微信签名 
			    },
			    function(res) {
					// alert('p1'+res.err_msg)
			        if (res.err_msg == "get_brand_wcpay_request:ok") {
						// alert('pp')
						uni.showModal({
							content:'若需取消预订，应在入住当日 13 点之前进行操作；若不取消，则需在 18 点前携带身份证或电子身份证至前台办理入住手续，否则可能被加入黑名单。退房时间为次日 13 点之前。',
							success: (res) => {
								uni.reLaunch({
									url:'/pages/my_orderlist/my_orderlist?Inv=3'
								})
							},
							fail: (e) => {
								uni.reLaunch({
									url:'/pages/my_orderlist/my_orderlist?Inv=3'
								})
							},
						})
			            // 使用以上方式判断前端返回,微信团队郑重提示：
			            //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
			        }else{
						this.chapayIf()
					}
			    });
			},
			//查询是否支付成功
			chapayIf(){
				var data={
					"outTradeNo": this.orderNumber,//订单号id
				}
				getchapay(data).then((res) => {
					if (res.success) {
						if(res.data.tradeState=="SUCCESS"){
							uni.showModal({
								content:'支付成功',
								success: (res) => {
									uni.reLaunch({
										url:'/pages/my_orderlist/my_orderlist?Inv=3'
									})
								},
							})
						}else{
							uni.showModal({
								content:res.data.tradeStateDesc
							})
						}
						
						// return;
					} else {
					}
				}).catch((err) => {
					uni.showModal({
						content:err.message
					})
				});
			},
			// 倒计时结束回调
			finish(countDownTime,item) {
				// alert('倒计时结束'+item)
				// if(item==)
				this.quxiaoorder()
			},
			// 取消订单
			quxiaoorder(){
				let _self = this
				// this.$axios.defaults.headers.common['token'] = localStorage.getItem('token');
				// this.$axios.defaults.headers.common['user_head'] = localStorage.getItem('user_head');
				// this.$axios.defaults.headers.common['Content-Type'] ='application/json'
				var data={
					"usersId": localStorage.getItem('usersId'),
					"orderNumber": this.orderNumber, //订单号
					"houseNumberId": this.houseNumberId, //房间号id
				}
				quxiaoorder(data).then((res) => {
					if (res.success) {
						uni.showModal({
							content:'支付超时，请重新订房',
							success: (res) => {
								uni.switchTab({
									url:'/pages/index/index'
								})
							},
							fail: (e) => {
								// uni.switchTab({
								// 	url:'/pages/index/index'
								// })
							},
						})
						// return;
					} else {
					}
				}).catch((err) => {
					uni.showModal({
						content:err.message
					})
				});
			}
		}
	}
</script>

<style>
	@import url("./css/submit_order.css");
</style>
