<template>
	<view class="content">
		<!-- 第一层表单 -->
		<view class="two_all">
			 <!-- @click="openCalendar" -->
			<view class="select-time" v-if="roomType==1">
				<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-time" v-if="roomType==2">
				<view class="select-time-one">
				  <text class="select-list-time">{{startTime}}
					<text class="select-list">{{startWeek}}</text>
				  </text>
				</view>
				<view class="select-time-one">
				  <!-- <text class="select-list-time" style="font-size: 12px;">{{zhongTime}} -->
				  <text class="select-list">{{zhongshi}}小时</text>
				  </text>
				</view>
			</view>
			<!-- 房型信息 -->
			<view class="select_name">{{typeName}}</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>
			<uni-popup ref="popup_picker" :mask-click="true">
				<!-- <view class=popup_bg_picker> -->
				<uni-calendar :selected="info.selected" class="uni-calendar--hook" :clear-date="true" :date="info.date" :insert="info.insert" :lunar="info.lunar" :startDate="info.startDate"
				:endDate="info.endDate" :range="info.range" @change="change"/>
				<view style="height: 60px; background-color: #fff;">
					<view class="riliQueren" @click="popup_pickerClose">确定{{ruzhu_num}}晚</view>
				</view>
				<!-- </view> -->
			</uni-popup>
		</view>
		<!-- 第二层基本信息 -->
		<view class="second_basic">
			<view class="form_title">入住信息</view>
			<view class="form-line1"></view>
			<view class="form-num">房间数量：
			<text class="list-text">1间</text></view>
			<view class="form-line2"></view>
			<view class="form-name">住客姓名：
			<text class="list-text">{{cardName}}</text></view>
			<view class="form-line"></view>
			<view class="form-phone">联系电话：
			<text class="list-text">{{cardPhone}}</text></view>
			<view class="form-line"></view>
			<!-- <view class="uni-list-cell-db" v-if="roomType==1">预计到店：
				<picker style="margin-left: 70px;margin-top: -22px;"
				 @change="bindPickerChange" :value="index" :range="array">
					<view class="uni-input" style="color: rgba(0, 0, 0, 1);">{{array[index]}}</view>
					<text class="jiantou">〉</text>
				</picker>
			</view> -->
			<view class="uni-list-cell-db" v-if="roomType==2">入住时段：
				<picker style="margin-left: 70px;margin-top: -22px;"
				 @change="bindPickerChange2" :value="index2" :range="array2">
					<view class="uni-input" style="color: rgba(0, 0, 0, 1);">{{array2[index2]}}</view>
					<text class="jiantou">〉</text>
				</picker>
			</view>
			
			<view class="uni-list-cell-db" v-if="payMount>0">请选择身份:
				<picker style="float: right;" @change="bindPickerChangeShen" :value="indexS" :range="arrayShen">
					<view class="uni-input" style="color: rgba(0, 0, 0, 1);" v-if="indexS==0||indexS==1||indexS==2||indexS==3">{{arrayShen[indexS]}}</view>
					<text class="jiantou" style="margin-top: 0px;" v-else>〉</text>
				</picker>
			</view>
			<view class="uni-list-cell-db" v-if="payMount>0">申请理由:
				<picker style="float: right;" @change="bindPickerChangeLi" :value="indexL" :range="arrayLi">
					<view class="uni-input" style="color: rgba(0, 0, 0, 1);" v-if="indexL==0||indexL==1">{{arrayLi[indexL]}}</view>
					<text class="jiantou" style="margin-top: 0px;" v-else>〉</text>
				</picker>
			</view>
			<view style="height: 20rpx;"></view>
		</view>
		<!-- 第三层表单 -->
		<view class="third_basic">
			<view class="third_title">费用明细</view>
			<view class="third-line1"></view>
			<view class="third-num">在线支付：
				<text class="third-text">
					1间
					<template v-if="roomType==1">{{ruzhu_num}}晚</template>
				</text>
				<text style="margin-left: 10rpx;">共
					<text class="third-text2">¥{{payMount}}</text>
				</text>
			</view>
		</view>
		<!-- 第四层房费 -->
		<view class="four_basic">
			<view class="four_title">房费
				<text style="margin-left: 533rpx;">¥{{payMount}}</text>
			</view>
			<view class="four-line1"></view>
			<view v-if="roomType==1">
				<view v-for="(item,index) in wanPrice" :key="index">
					<view class="four-num">
						{{item.date}}
						<text style="margin-left: 30rpx;">1晚共{{item.price}}</text>
					</view>
				</view>
				<view class="four-all">1间 x {{ruzhu_num}}晚</view>
			</view>
			
			<view v-if="roomType==2">
				<view>
					<view class="four-num">{{startDate}}</view>
					<view class="four-num2">{{endDate}}</view>
				</view>
				<view class="four-all">{{ruzhu_num}} x ¥{{roomPrice}}</view>
			</view>
		</view>
		<!-- 支付框 -->
		<view class="fukuan">
			<view class="fu-price">¥{{payMount}}</view>
			<view class="fu-zhifu" :class="{'room-button2': freeRoom == 0}">
				<!-- <text v-if="freeRoom==0">房间已满</text> -->
				<!--  v-else<text v-else @click="getOrderSubmit('warn')">立即支付</text> -->
				<text @click="postOrder('warn')">立即支付</text>
			</view>
		</view>
		<!-- 提交订单时弹框 -->
		<uni-popup ref="popup_order" type="dialog">
			<uni-popup-dialog :type="msgType" cancelText="关闭" confirmText="确定" :content="order_txt" @confirm="dialogConfirm"
				@close="dialogClose"></uni-popup-dialog>
		</uni-popup>
		
	</view>
</template>

<script>
	import {
		getuserinfo,
		getprice,
		getMeiprice,
		postOrder,
		getZhongTime
	} from '../../utils/api_hotel.js'
	/**
	 * 获取任意时间
	 */
	function getDate(date, AddDayCount = 0) {
		if (!date) {
			date = new Date()
		}
		if (typeof date !== 'object') {
			date = date.replace(/-/g, '/')
		}
		const dd = new Date(date)
	
		dd.setDate(dd.getDate() + AddDayCount) // 获取AddDayCount天后的日期
	
		var a = new Array("日", "一", "二", "三", "四", "五", "六");  
		var week = new Date().getDay();    
		var week2 = new Date().getDay()+1;    
		const y = dd.getFullYear()
		const m = dd.getMonth() + 1 < 10 ? '0' + (dd.getMonth() + 1) : dd.getMonth() + 1 // 获取当前月份的日期，不足10补0
		const d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate() // 获取当前几号，不足10补0
		const h = dd.getHours() < 10 ? '0' + dd.getHours() : dd.getHours()
		const f = dd.getMinutes() < 10 ? '0' + dd.getMinutes() : dd.getMinutes()
		const s = dd.getSeconds() < 10 ? '0' + dd.getSeconds() : dd.getSeconds()
		return {
			fullDate: y + '-' + m + '-' + d,
			fullDate2: y + '-' + m + '-' + d+' '+h+':'+f+':'+s,
			fullTime: m + '月' + d + '日',
			year: y,
			month: m,
			date: d,
			day: dd.getDay(),
			sWeek:"周"+ a[week],
			eWeek:"周"+ a[week2]
		}
	}
	export default {
		data() {
			return {
				showCalendar: false,
				info: {
					lunar: true,
					range: true,
					insert: true,
					selected: [],
					startDate:'',
					date:'',
					endDate:''
				},
				startTime:'',//到店日期
				endTime:'',//离店日期
				startDate:'',//默认到店日期接口数据
				endDate:'',//默认离店日期接口数据
				startWeek:'',// 默认入店日
				endWeek:'',// 默认离店
				array: ['18:00前到店', '19:00前到店', '20:00前到店', '21:00前到店'],
				index: 0,
				
				array2: [''],//钟点房
				index2: 0,
				//选择身份
				arrayShen:['学生','学生家长','朋友','老师'],
				indexS:5,
				//选择理由
				arrayLi:['探视','交流'],
				indexL:5,
				mayTime:'',// 预计到店时间
				typeName:'',//户型名
				textNum:0,//输入框当前字数
				cardName:'',//用户名
				cardPhone:'',//用户电话
				cardIdentity:'',//身份
				roomTypeId:'',//房间类型id
				remark:'',//备注要求
				payMount:0,//应付金额
				freeRoom:0,//剩余房间可预订的房间数
				ruzhu_num:1,//入住夜晚
				roomArea:'0',//房间面积
				roomType:1,//房间类型
				roomPrice:"",//房间单价
				roomConfiguration:'',//房间配置
				order_txt:'',//提交订单时信息
				msgType:'warn',
				zhongTime:'',//钟点房订的时间段
				zhongshi:'',//钟点房时间
				startDateZ:'',//钟点房默认到店日期接口数据
				endDateZ:'',//钟点房默认离店日期接口数据
				wanPrice:[],
				source:'',
				sourceId:'',
				data:{},
			}
		},
		onLoad(option) {
			this.data=JSON.parse(decodeURIComponent(option.data))
			console.log(JSON.parse(decodeURIComponent(option.data)))
			// this.payMount=Number(this.data.payMount)
			this.ruzhu_num=this.data.ruzhu_num
			this.roomArea=this.data.roomArea
			this.roomType=this.data.roomType
			this.roomConfiguration=this.data.roomConfiguration
			this.roomPrice=this.data.roomPrice
			this.freeRoom=this.data.surplusCount
			this.zhongTime=this.data.zhongTime
			this.zhongshi=this.data.zhongshi
			localStorage.setItem('roomTypeId',this.data.roomTypeId)
			localStorage.setItem('typeName',this.data.typeName)
			localStorage.setItem('startTime',this.data.startTime)
			localStorage.setItem('endTime',this.data.endTime)
			localStorage.setItem('enableStartTime',this.data.enableStartTime)
			localStorage.setItem('enableEndTime',this.data.enableEndTime)
			localStorage.setItem('zhongTime',this.data.zhongTime)
			localStorage.setItem('source',this.data.source)
			localStorage.setItem('sourceId',this.data.sourceId)
			
		},
		mounted() {
			this.source=localStorage.getItem('source')
			this.sourceId=localStorage.getItem('sourceId')
			this.roomTypeId=localStorage.getItem('roomTypeId')
			this.typeName=localStorage.getItem('typeName')
			this.startTime=localStorage.getItem('startTime')
			this.endTime=localStorage.getItem('endTime')
			this.zhongTime=localStorage.getItem('zhongTime')
			this.startDate=localStorage.getItem('enableStartTime')
			this.endDate=localStorage.getItem('enableEndTime')
			
			this.startWeek=this.getweekday(this.startDate)
			this.endWeek=this.getweekday(this.endDate)
			this.mayTime=this.startDate.substring(0,11)+"18:00:00"
			// console.log(this.getweekday(this.startDate))
			if(this.roomType==2){
				this.getZhongTime()
			}
			// window.location.href ='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxa46ef222053a1047&redirect_uri=https://chtech.ncjti.edu.cn/hotel/ihotel-api/ihotel/hotelUser/weixinAuth&response_type=code&scope=snsapi_base&state=pages/order_room/order_room#wechat_redirect';
			this.getUserInfo()
		},
		onReady() {
			this.$nextTick(() => {
				this.showCalendar = true
			})
			// TODO 模拟请求异步同步数据
			setTimeout(() => {
				this.info.date = getDate(new Date()).fullDate
				this.info.startDate = getDate(new Date()).fullDate
				this.info.endDate =  getDate(new Date(),8).fullDate
				// this.startTime = getDate(new Date()).fullTime
				// this.endTime = getDate(new Date(),1).fullTime
				// this.startWeek = getDate(new Date()).sWeek
				// this.endWeek = getDate(new Date(),1).eWeek
				// this.ruzhu_num=1
			}, 20)
		},
		methods: {
			// 获取用户信息
			getUserInfo() {
				  let _self = this
				  var data="?userId="+localStorage.getItem('usersId')
				  getuserinfo(data).then((res) => {
					if (res.success) {
						_self.cardName=res.data.userName
						_self.cardPhone=res.data.phone
						_self.cardIdentity=res.data.idCardInformation
						this.getjisuanprice()
						this.getWanPrice()
						return;
					} else {
						console.log('获取用户信息失败')
					}
					}).catch((err) => {
						this.$message.error(err.message)
					});
			},
			//获取钟点房可住时间段
			getZhongTime(){
				this.array2=[]
				  let _self = this
				  var data="?houseNumberId="+_self.roomTypeId+"&startTime="+_self.startDate
				  +"&liveTime="+this.zhongshi
				  getZhongTime(data).then((res) => {
					if (res.success) {
						res.data.forEach(data => {
							if(data.status=="可用"){
								_self.array2.push(data.hourDate)
								this.startDateZ=localStorage.getItem('enableStartTime').substring(0,11)+this.array2[0].substring(0,8)
								this.endDateZ=localStorage.getItem('enableEndTime').substring(0,11)+this.array2[0].substring(9,17)
							}
						})
						return;
					} else {
						console.log('失败')
					}
					}).catch((err) => {
						uni.showModal({
							content:err.message
						})
					});
			},
			// 计算每晚价格
			getWanPrice(){
				  let _self = this
				  var data="?houseId="+_self.roomTypeId+"&startTime="+_self.startDate
				  +"&endTime="+_self.endDate
				  getMeiprice(data).then((res) => {
					if (res.success) {
						_self.wanPrice=res.data
						return;
					} else {
						uni.showModal({
							content:res.message
						})
					}
					}).catch((err) => {
						uni.showModal({
							content:err.message
						})
					});
			},
			// 计算订单金额
			getjisuanprice() {
				this.payMount=0
				  let _self = this
				  var data="?userId="+localStorage.getItem('usersId') 
				  +
				  "&houseId="+_self.roomTypeId+"&liveTime="+_self.startDate
				  +"&leaveTime="+_self.endDate+"&houseOrderNumber=1"+"&source="+this.source
				  getprice(data).then((res) => {
					if (res.success) {
						_self.payMount=res.data
						return;
					} else {
						uni.showModal({
							content:res.message
						})
					}
					}).catch((err) => {
						uni.showModal({
							content:err.message
						})
					});
			},
			// onBridgeReady () {
			//       console.log('调用微信支付WeixinJSBridge')
			//       var vm = this
			//       WeixinJSBridge.invoke(
			//         'getBrandWCPayRequest', { // 下面参数内容都是后台返回的
			//           "appId": "wxd87cbe1db0437303",     //公众号ID，由商户传入
			//           "timeStamp": "1720083271",//时间戳，自1970年以来的秒数     
			//           "nonceStr": "ORsH3qtW9wauQQ7iV5ovSm6n58s6Z2Nu",      //随机串     
			//           "package": "prepay_id=wx041654316576072897ded7969912130000",
			//           "signType": "RSA",     //微信签名方式：     
			//           "paySign": "ZbyL2qiE9QScgwEHhObRn5/9VQgJQxLo0zKc7VxUK+Emeb3Eas/rzePUp89rHnUVYDCRJcbNsmuR2b1LHY4mydBZVnPy1vwHE/EOrCmdgALZ4J8GcQK0wTLNu9kMx97WR0f9TItPN/sR604df9ca5CKA4P40vNaUIEdK45mkqo3MR2IAdvyn+L8DhW49cL7jlsqIRiohVwwRsS4n06mX/yx1kuA339l7hbwnHaq7D4elvEqFYoMSHD8CR3XnoZ0HFE7Klu1RChMzgO4WUgVIMUxhsF6bhy5TkSea25OG/QWGZW/EHOl58bTCg3PorhZeJ/7fDkIC6pNRtKndrdsd+Q==" //微信签名 
			//         },
			//         function(res){
			//         	if(res.err_msg == "get_brand_wcpay_request:ok" ) {}     // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。 
			//         }
			//       )
			//     },
			//创建订单
			postOrder(type){
				// var vm = this
				// if (typeof WeixinJSBridge === 'undefined') { // 微信浏览器内置对象。参考微信官方文档
				//           if (document.addEventListener) {
				//             document.addEventListener('WeixinJSBridgeReady', vm.onBridgeReady(), false)
				//           } else if (document.attachEvent) {
				//             document.attachEvent('WeixinJSBridgeReady', vm.onBridgeReady())
				//             document.attachEvent('onWeixinJSBridgeReady', vm.onBridgeReady())
				//           }
				//         } else {
				//           console.log('准备调用微信支付')
				//           vm.onBridgeReady()
				//         }
				if(this.roomType=='1'){
					var startDate=this.startDate
					var endDate=this.endDate
				}else {
					var startDate=this.startDateZ
					var endDate=this.endDateZ
				}
				if(this.indexS==5){
					uni.showModal({
						content:"请选择身份！"
					})
					return
				}
				if(this.indexL==5){
					uni.showModal({
						content:"请选择申请理由！"
					})
					return
				}
				this.payUrl=''
				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={
					"userId": localStorage.getItem('usersId'),
					"houseId": this.roomTypeId,
					"payPrice": this.payMount,
					"houseOrderNumber": 1,
					"liveDay": this.ruzhu_num,
					"reserveLiveTime": startDate,
					"reserveLeaveTime": endDate,
					"reservePhone": this.cardPhone,
					"reserveName": this.cardName,
					"source":this.source,
					"sourceId":this.sourceId,
					"identityType":this.indexS,
					"reason":this.indexL,
				}
				postOrder(data).then((res) => {
					if (res.success) {
						uni.navigateTo({
							url:'/pages/submit_order/submit_order?houseOrderId='+res.data.id
						})
						// if(res.data.payAmount==0) {
						// 	uni.navigateTo({
						// 		url:'../zhifuchenggong/zhifuchenggong?orderId='+res.data.orderId
						// 	})
						// } else {
						// 	window.location.href = res.data.payUrl;
						// }
						// return;
					} else {
						this.msgType = type
						this.order_txt=res.message
						this.$refs.popup_order.open()
					}
				}).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
			},
			//日历选择器
			openCalendar() {
				this.$refs.popup_picker.open()
			},
			// 关闭全日房日历
			popup_pickerClose(){
				this.$refs.popup_picker.close()
				this.getjisuanprice()
				this.getWanPrice()
			},
			change(e) {
				// 模拟动态打卡
				// if (this.info.selected.length > 5) return
				this.info.selected=[
					{
						date: e.range.before,
						info: '到店'
					},
					{
						date: e.range.after,
						info: '离店'
					}
				]
				if(e.range.before!=''&&e.range.after=='') {
					this.startWeek='周'+e.lunar.ncWeek.substring(2,3)
				} else if(e.range.before!=''&&e.range.after!=''){
					if((new Date(e.range.after).getTime())<(new Date(e.range.before).getTime())) {
						this.order_txt='离店日期不能小于到店日期'
						this.$refs.popup_order.open()
						this.info.selected=[]
					}else if(parseInt(((new Date(e.range.after).getTime())-(new Date(e.range.before).getTime()))/1000/60/60/24)>2){
						this.order_txt='预订时间不能超过两晚'
						this.$refs.popup_order.open()
						this.info.selected=[]
					}else if(parseInt(((new Date(e.range.after).getTime())-(new Date(e.range.before).getTime()))/1000/60/60/24)==2){
						this.order_txt='您此次申请了两晚，请注意若只住一晚可能会导致流程管理次数失效。'
						this.$refs.popup_order.open()
						this.endWeek='周'+e.lunar.ncWeek.substring(2,3)
						this.startTime=e.range.before.substring(5,7)+'月'+e.range.before.substring(8,10)+'日'
						this.endTime=e.range.after.substring(5,7)+'月'+e.range.after.substring(8,10)+'日'
						this.startDate = e.range.before +' '+localStorage.getItem('liveTime')
						this.endDate =  e.range.after +' '+localStorage.getItem('leaveTime')
						this.ruzhu_num=parseInt(((new Date(e.range.after).getTime())-(new Date(e.range.before).getTime()))/1000/60/60/24)
					}else{
						this.endWeek='周'+e.lunar.ncWeek.substring(2,3)
						this.startTime=e.range.before.substring(5,7)+'月'+e.range.before.substring(8,10)+'日'
						this.endTime=e.range.after.substring(5,7)+'月'+e.range.after.substring(8,10)+'日'
						this.startDate = e.range.before +' '+localStorage.getItem('liveTime')
						this.endDate =  e.range.after +' '+localStorage.getItem('leaveTime')
						this.ruzhu_num=parseInt(((new Date(e.range.after).getTime())-(new Date(e.range.before).getTime()))/1000/60/60/24)
					}
				}
			},
			//选择器
			bindPickerChange: function(e) {
				console.log('picker发送选择改变，携带值为', e.detail.value)
				this.index = e.detail.value
				this.mayTime = this.startDate.substring(0,11)+this.array[this.index].substring(0,5)+":00"
				// console.log(this.mayTime)
			},
			//钟点房选择器
			bindPickerChange2: function(e) {
				console.log('picker发送选择改变，携带值为', e.detail.value)
				this.index2 = e.detail.value
				console.log(this.array2[this.index2].substring(0,8),this.array2[this.index2])
				if(this.array2.length<=0){
					
				}else{
					this.startDateZ=localStorage.getItem('enableStartTime').substring(0,11)+this.array2[this.index2].substring(0,8)
					this.endDateZ=localStorage.getItem('enableEndTime').substring(0,11)+this.array2[this.index2].substring(9,17)
				}
				this.mayTime = this.startDate.substring(0,11)+this.array[this.index].substring(0,5)+":00"
				// console.log(this.mayTime)
			},
			//选择身份
			bindPickerChangeShen: function(e) {
				console.log('picker发送选择改变，携带值为', e.detail.value)
				this.indexS = e.detail.value
			},
			//申请理由
			bindPickerChangeLi: function(e) {
				this.indexL = e.detail.value
			},
			// 输入框
			bindTextAreaBlur: function (e) {
				this.textNum=e.detail.cursor
				this.remark=e.detail.value
			}
		}
	}
</script>

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