<template>
	<view>
		<u-toast ref="uToast"></u-toast>
		<view class="card" >
			<view class="form">
				<view class="flex">
					<view class="need" >*</view>
					<view>访问区域</view>
				</view>
				<view class="bg-gray padding-20 "  >
					<input disabled type="text" v-model="data.guestPosition" />
				</view>
			</view>
			<view class="form">
				<view class="flex">
					<view class="need" >*</view>
					<view>访问日期</view>
				</view>
				<view class="bg-gray padding-20 "  >
					<u-input  type="select" :select-open="timeShow" v-model="data.guestTime"  placeholder="请选择访问日期" @click="timeShow=true"></u-input>
				</view>
			</view>
			<view class="form">
				<view class="flex">
					<view class="need" >*</view>
					<view>接待人</view>
				</view>
				<view class="bg-gray padding-20 "  >
					<input :disabled="isDisabled" type="text" placeholder="请填写接待人"  v-model="data.userName" />
				</view>
			</view>
			<view class="form">
				<view class="flex">
					<view class="need" >*</view>
					<view>您的姓名:</view>
				</view>
				<view class="bg-gray padding-20 "  >
					<input :disabled="isDisabled" type="text" placeholder="请填写您的姓名" v-model="data.guestName" />
				</view>
			</view>
			<view class="form ">
				<view class="flex">
					<view class="need" >*</view>
					<view>您的联系方式</view>
				</view>
				<view class="bg-gray padding-20  flex justify-between " style="box-sizing: border-box;" >
					<input disabled maxlength="11" type="number" placeholder="请获取您的联系方式" v-model="data.guestTel" />
					<button :disabled="isDisabled" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" class="light sm cu-btn bg-blue radius">
						获取手机号
					</button>
				</view>
			</view>
			<view class="form ">
				<view class="flex">
					<view class="need" >*</view>
					<view>您的身份证号</view>
				</view>
				<view class="bg-gray padding-20 " >
					<input :disabled="isDisabled" placeholder="请输入您的身份证号" v-model="data.guestIdcard" />
				</view>
			</view>
		</view>
		<view class="card ">
			<view class="form" style="height: 320rpx;">
				<view class="flex">
					<view class="need" >*</view>
					<view>来访目的</view>
				</view>
				<view  class="bg-gray padding-10">
					<textarea :disabled="isDisabled"   v-model="data.guestReason" maxlength="100" style="width: 100%;height: 270rpx;line-height: 50rpx;"  placeholder="请填写来访原因"></textarea>
					<view  class="text-right text-df text-gray padding-top-10">
						{{data.guestReason.length}} / 100
					</view>
				</view>
			</view>
		</view>
		<view class="bg-white" style="height: 160rpx;"></view>
		
		<view v-if="!islock&&auditStatus==null"  style="z-index: 999;" class=" footer-fixed" @click="submit">
			<view class="cu-btn  flex  text-lg bg-red-btn" style="padding: 46rpx 0;">
				确定提交
			</view>
		</view>
		<button open-type="share" v-if="!islock&&auditStatus==0"  style="z-index: 999;" class=" footer-fixed" >
			<view class="cu-btn  flex  text-lg bg-orange light" style="padding: 46rpx 0;">
				待审核,通知被访者审核
			</view>
		</button>
		<view @click="auditStatus=null;operaType=1;oldData=$u.deepClone(data)" v-if="!islock&&auditStatus==2"  style="z-index: 999;" class=" footer-fixed" >
			<view class="cu-btn  flex  text-lg bg-red" style="padding: 46rpx 0;">
				审核不通过，点击重新填表
			</view>
		</view>
		<view v-if="islock" style="z-index: 999;" class=" footer-fixed" >
			<view class="cu-btn  flex  text-lg bg-gray" style="padding: 46rpx 0;">
				已锁定
			</view>
		</view>
		<u-mask z-index="99999" :show="maskShow" @click="hideMask">
			<view style="margin: 20rpx;" @click.stop="">
				<textarea  @keyboardheightchange="keyboardheightchange" v-model="data.visitReason"  value="" style="background-color: #FFFFFF;width: 100%;padding: 20rpx;box-sizing: border-box;" placeholder="请填写来访原因" />
				<view  class="bg-white text-right text-df text-gray padding-10">
					{{data.visitReason.length}} / 100
				</view>
			</view>
		</u-mask>
		<!--弹窗-->
		<view class="modal-mask"   v-if="showModal"></view>
		<view class="modal-dialog" v-if="showModal">
		  <view class="modal-title">提示</view>
		    <view class="modal-content">
		      <view class="modal-input">
		        <text class="password">填写成功，请转发给好友审核</text>
		      </view>
		    </view>
		    <view class="modal-footer">
		      <button class="btn-confirm" @click="showModal=false;getAuthRecords()" data-status="confirm">暂不转发</button>
			  <button class="btn-cancel" open-type="share"  data-status="cancel">立即转发</button>
		    </view>
		</view>
		
		<view v-if="auditStatus==0" @click="getAuthRecords" class="cuIcon cu-btn" style="width: 88rpx;height: 88rpx;background-color: rgba(0,0,0,.2);color: #FFFFFF;position: fixed;bottom: 40%;right: 20rpx;">
			<text class="cuIcon-refresh" style="font-size: 50rpx;"></text>
		</view>
		
		<u-picker @confirm="timeConfirm" :params="params" v-model="timeShow" mode="time"></u-picker>
	</view>
</template>

<script>
	var app=getApp()
	var that;
	export default {
		components:{
			
		},
		data() {
			return {
				//0新增表单操作，1修改表单操作
				operaType:0,
				
				id:'',//授权记录的id
				doorNeedAudit:0,//该授权开门是否需要审核
				memberId:'',//业主的 memberId，用来获取设备列表
				residentialId:'',//小区id，用来获取设备列表
				openId:'',
				sessionKey:'',
				
				showModal:false,
				
				//查询出来的审核状态
				auditStatus:null,
				islock:false,
				
				//时间选择器
				timeShow:false,
				params: {
					year: true,
					month: true,
					day: true,
					hour: true,
					minute: true,
					second: true
				},
				//审核不通过重新修改时的旧数据
				oldData:{},
				//提交的数据
				data:{
					//授权记录的表id
					guestAuthId:'',
					//被访者区域
					guestPosition:'',
					//来访日期
					guestTime:this.$u.timeFormat(new Date(),'yyyy-mm-dd hh:MM:ss'),
					//接待人
					userName:'',
					//来访者姓名
					guestName:'',
					//来访者联系方式
					guestTel:'',
					//来访者身份证号
					guestIdcard:'',
					//来访原因
					guestReason:'',
					//审核状态
					auditStatus:0
				},
				//添加访客记录后，将访客记录id分享给好友审核
				shareId:'',
			}
		},
		computed:{
			isDisabled:{
				get(){
					if (this.auditStatus==null) {
						if (this.islock) {
							return true
						}else{
							return false
						}
					}else{
						return true
					}
				}
			}
		},
		onShareAppMessage: function (ops) {
		  this.showModal=false
		  this.getAuthRecords()
		  return {
		    title: "我是"+this.data.guestName+"，我正在填表申请开门，请审核",
			path:"/pages/record/record?id="+this.shareId
		  };
		},
		onLoad(options) {
			that=this
			if (!this.$isEmpty(options.scene)) {
				let scene=decodeURIComponent(options.scene).split(",")
				//从小程序二维码进入
				options.id=scene[0]
				options.doorNeedAudit=scene[1]
				options.memberId=scene[2]
			}
			//附带的页面参数id为空，则锁定页面
			if (this.$isEmpty(options.id)) {
				uni.showModal({
					showCancel:false,
					content:"系统错误,已锁定",
					success: (res) => {
						if (res.confirm) {
							that.islock=true
						}
					}
				})
				return
			}
			this.id=options.id
			this.doorNeedAudit=options.doorNeedAudit
			this.memberId=options.memberId
			this.data.guestAuthId=this.id
			this.getAuthRecords()
		},
		methods: {
			getPhoneNumber (e) {
				let that=this
				if (e.detail.errMsg == "getPhoneNumber:ok") {
					console.log(e);
					let params={
						sessionKey:that.sessionKey,
						encryptedData:e.detail.encryptedData,
						iv:e.detail.iv
					}
					let operation = 'miniprogram/getOpenData';
					getApp().globalData.postRequest(params,operation,function(res){
						that.data.guestTel=res.data.purePhoneNumber
					})
				}else{
					this.$refs.uToast.show({
						title: '获取手机号失败!',
						position:"top",
						type: 'error',
					})
					return
				}
			},
			/**
			 * 跳转到设备列表
			 */
			jumpOpenDoor(){
				let params={
					memberId:this.memberId,
					residentialId:this.residentialId,
					guestTel:this.data.guestTel
				}
				uni.redirectTo({
					url:"/pages/guest/open_door"+this.$u.queryParams(params)
				})
			},
			timeConfirm(e){
				this.data.guestTime=e.year+"-"+e.month+"-"+e.day+" "+e.hour+":"+e.minute+":"+e.second
				console.log(this.data.guestTime);
			},
			/**
			 * 先通过id查询授权记录表查看该授权是否过期
			 * 过期了就不能进行接下来的操作，提示访客联系业主重新授权
			 * 没有过期就判断审核配置，配置了不需要审核表单就直接跳到设备列表，
			 * 需要审核就通过授权记录的id和openid查询访客记录表，查询到记录就直接跳到设备列表
			 * 查不到记录就填表
			 */
			async getAuthRecords(){
				let that=this
				let operation="guestAuthorize/getById/"+this.id
				let params={}
				let res=await app.globalData.postRequestAsync(params, operation);
				if (res.data.result_code!=1) {
					uni.showModal({
						showCancel:false,
						content:"没有该授权记录，或者授权记录已被撤销",
						success: (res) => {
							if (res.confirm) {
								that.islock=true
							}
						}
					})
					return
				}
				//授权详情
				let guestAuthorize=res.data.guestAuthorize
				that.residentialId=guestAuthorize.residentialId
				//授权结束时间
				that.data.endTime=guestAuthorize.endDate
				let endDate= that.$commonDate(guestAuthorize.endDate).getTime()
				//当前时间
				let now= new Date().getTime()
				//判断授权是否过期
				if (now>endDate) {
					uni.showModal({
						title:"提示",
						content:"授权时间已过期，请联系被访者重新授权",
						showCancel:false,
						success: (res) => {
							if (res.confirm) {
								that.islock=true
							}
						}
					})
					return
				}
				// 授权没有过期
				//通过openid,授权记录id查询访客记录表
				let guestRes=await this.getGuestRecords()
				if (guestRes.data.result_code!=1) {
					//没有记录，就填表
					that.data.guestPosition=guestAuthorize.residentialName+","
									+guestAuthorize.buildingName+","+guestAuthorize.unitName+","+
									guestAuthorize.roomName
					that.data.userName=guestAuthorize.userName
					that.data.residentialId=guestAuthorize.residentialId
					that.data.residentialName=guestAuthorize.residentialName
					that.data.userId=guestAuthorize.userId
					return
				}
				//有记录，就判断审核状态
				let guestRecord=guestRes.data.guestRecords[0]
				var {orgId,orgPosition,rootOrgId,createDate,...restData} = guestRecord
				that.data=restData
				that.auditStatus=guestRecord.auditStatus
				if (that.auditStatus==1) {
					//审核通过。跳转到设备列表
					that.jumpOpenDoor()
				}
			},
			/**
			 * 通过openid和授权记录id和审核通过的状态查看访客记录表
			 */
			async getGuestRecords(){
				let jsCode = await new Promise((resolve, reject) => {  
					uni.login({  
						provider: 'weixin',  
						success: res => {
							resolve(res.code);  
						},  
						fail: err => {  
							reject(err);  
						}  
					})
				})
				let params = {
					js_code:jsCode,
					name:'community',
					app_type: 1
				};
				// let operation = 'miniprogram/getOpenid'; //发起请求
				let res= await this.$http.getOpenid(params);
				that.sessionKey=res.data.session_key
				this.openId=res.data.openid
				//获取成功
				let url='guestRecord/getByCondition'
				let guestParams={
					guestAuthId:this.id,
					openId:this.openId
				}
				let guestRes=await app.globalData.postRequestAsync(guestParams,url)
				return guestRes
			},
			submit(){
				let that=this
				if (this.$isEmpty(this.data.guestPosition)) {
					uni.showModal({
						title:"提示",
						content:"系统错误",
						showCancel:false,
						success: (res) => {
							if (res.confirm) {
								that.islock=true
							}
						}
					})
					return
				}
				if (this.$isEmpty(this.data.guestTime)) {
					this.$refs.uToast.show({
						title: '请选择访问日期',
						position:"top",
						type: 'error',
					})
					return
				}
				
				if (this.$isEmpty(this.data.userName)) {
					this.$refs.uToast.show({
						title: '请填写接待人姓名',
						position:"top",
						type: 'error',
					})
					return
				}
				if (this.$isEmpty(this.data.guestName)) {
					this.$refs.uToast.show({
						title: '请填写您的姓名',
						position:"top",
						type: 'error',
					})
					return
				}
				if (this.$isEmpty(this.data.guestTel)) {
					this.$refs.uToast.show({
						title: '请填写联系方式',
						position:"top",
						type: 'error',
					})
					return
				}
				if (!this.$u.test.mobile(this.data.guestTel)) {
					this.$refs.uToast.show({
						title: '联系方式不正确',
						position:"top",
						type: 'error',
					})
					return
				}
				if (this.$isEmpty(this.data.guestIdcard)) {
					this.$refs.uToast.show({
						title: '请填写身份证号',
						position:"top",
						type: 'error',
					})
					return
				}
				if (!this.$u.test.idCard(this.data.guestIdcard)) {
					this.$refs.uToast.show({
						title: '身份证号不正确',
						position:"top",
						type: 'error',
					})
					return
				}
				if (this.$isEmpty(this.data.guestReason)) {
					this.$refs.uToast.show({
						title: '请填写来访目的',
						position:"top",
						type: 'error',
					})
					return
				}
				if (JSON.stringify(this.oldData)==JSON.stringify(this.data)) {
					this.$refs.uToast.show({
						title: '无任何修改痕迹，请先修改后再提交',
						position:"top",
						type: 'error',
						icon:false,
						duration:2500
					})
					return
				}
				this.data.openId=this.openId
				let operation=''
				if (this.operaType==0) {
					//新增
					operation="guestRecord/addGuestRecord"
					if (this.doorNeedAudit==0) {
						//1不需要审核,直接审核通过
						this.data.auditStatus=1
					}
				}else{
					//修改
					operation="guestRecord/updateGuestRecord"
					this.data.auditStatus=0
				}
				app.globalData.postRequest(this.data, operation,function(res){
					if (res.data.result_code==1) {
						if (that.doorNeedAudit==0) {
							//不需要审核，直接跳转到设备列表页
							that.jumpOpenDoor()
						}else{
							that.shareId=res.data.guestRecordId
							//需要审核，弹框分享给好友审核
							that.showModal=true
						}
					}else{
						that.$refs.uToast.show({
							title: '操作失败',
							position:"top",
							type: 'error',
						})
					}
				})
				
			}
		}
	}
</script>

<style lang="scss">
	.bg-gray{
		background-color: #f7f7f7;
	}
	.card{
		box-sizing: border-box;
		background-color: #FFFFFF;
	}
	.card .form{
		padding: 20rpx 40rpx;
	}
	.need{
		font-size: 38rpx;
		font-weight: 800;
		color: #ff0000;
		padding-right: 10rpx;
	}
	
	
	
	.modal-mask {
	  width: 100%;
	  height: 100%;
	  position: fixed;
	  top: 0;
	  left: 0;
	  background: #000;
	  opacity: 0.5;
	  overflow: hidden;
	  z-index: 9000;
	  color: #fff;
	}
	
	.modal-dialog {
	  width: 540rpx;
	  overflow: hidden;
	  position: fixed;
	  top: 45%;
	  left: 0;
	  z-index: 9999;
	  background: #f9f9f9;
	  margin: -180rpx 105rpx;
	  border-radius: 36rpx;
	}
	
	.modal-title {
	  padding-top: 50rpx;
	  font-size: 36rpx;
	  color: #030303;
	  text-align: center;
	}
	
	.modal-content {
	  padding: 60rpx 0;
	}
	
	.modal-input {
	  display: flex;
	  font-size: 30rpx;
	}
	
	.password {
	  width: 100%;
	  height: 80rpx;
	  font-size: 30rpx;
	  line-height: 80rpx;
	  padding: 0 20rpx;
	  box-sizing: border-box;
	  color: #606266;
	  text-align: center;
	}
	
	input-holder {
	  color: #666;
	  font-size: 28rpx;
	}
	
	.modal-footer {
	  display: flex;
	  flex-direction: row;
	  height: 86rpx;
	  border-top: 1px solid #dedede;
	  font-size: 34rpx;
	  line-height: 86rpx;
	}
	.modal-footer button::after{
	   border: none;
	  
	}
	.modal-footer .btn-cancel {
	  width: 50%;
	  color: #2a7fff;
	  text-align: center;
	 border-radius: 0;
	}
	
	.modal-footer .btn-confirm {
	  width: 50%;
	  color: #666;
	  border-right: 1px solid #dedede;
	  text-align: center;
	}
	
</style>
