<template>
	<view class="bg-white" style="min-height: 100vh;">
		<view class="content" v-if="!loading">
			<view class="padding-20 bg-white" v-if="!this.islock&&description">
				<u-alert-tips type="warning" :description="description"></u-alert-tips>
			</view>

			<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 ">
						<ruiDatePicker v-if="$isNotEmpty(data.interviewTime)" :start="guestAuthorize.beginDate"
							:end="guestAuthorize.endDate" fields="second" @change="timeConfirm"
							:value="data.interviewTime">
						</ruiDatePicker>
					</view>
					<view class="text-sm text-right text-orange" style="padding-top: 8rpx;">
						<text>有效时间：{{guestAuthorize.beginDate}} 至 {{guestAuthorize.endDate}}</text>
					</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 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>您的身份证号</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>

			<view @click="again" 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>
		</view>


		<view v-else style="position: absolute;top: 40%;left: 50%;transform: translate(-50%,-50%);">
			<u-loading mode="flower" size="80"></u-loading>
		</view>


		<!--弹窗-->
		<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="reload" class="cuIcon cu-btn "
			style="width: 80rpx;height: 80rpx;background-color: rgba(0,0,0,.2);color: #FFFFFF;position: fixed;bottom: 40%;right: 20rpx;z-index: 9;">
			<u-loading mode="flower" size="50" color="#fff" :show="isReload"></u-loading>
			<text class="cuIcon-refresh rotateCenter" v-if="!isReload" style="font-size: 50rpx;"></text>
		</view>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	var app = getApp()
	var that;
	import ruiDatePicker from '@/comps/rattenking-dtpicker/rattenking-dtpicker.vue';
	export default {
		components: {
			ruiDatePicker
		},
		data() {
			return {
				guestRecordId:'',
				
				loading: false,
				isReload: false,
				timeValue: '',
				guestAuthorize: {},

				//0新增表单操作，1修改表单操作
				operaType: 0,

				id: '', //授权记录的id
				doorNeedAudit: 0, //该授权开门是否需要审核
				memberId: '', //业主的 memberId，用来获取设备列表
				residentialId: '', //小区id，用来获取设备列表
				openId: '',
				sessionKey: '',

				showModal: false,

				//查询出来的审核状态
				auditStatus: null,
				islock: false,

				//审核不通过重新修改时的旧数据
				oldData: {},
				//提交的数据
				data: {
					userId: '',
					//授权记录的表id
					guestAuthId: '',
					//被访者区域
					guestPosition: '',
					//来访日期
					interviewTime: '',
					beginTime: '',
					endTime: '',
					//接待人
					userName: '',
					//来访者姓名
					guestName: '',
					//来访者联系方式
					guestTel: '',
					//来访者身份证号
					guestIdcard: '',
					//来访原因
					guestReason: '',
					//审核状态
					auditStatus: 0,
					//登记来源小程序
					registerSource: 1
				},
				//添加访客记录后，将访客记录id分享给好友审核
				shareId: '',
			}
		},
		computed: {
			isDisabled: {
				get() {
					if (this.auditStatus == null) {
						if (this.islock) {
							return true
						} else {
							return false
						}
					} else {
						return true
					}
				}
			},
			description() {
				if (this.auditStatus == 0) {
					return '待审核,请通知被访者进入小程序审核'
				}
				if (this.auditStatus == 2) {
					if (this.$isNotEmpty(this.data.opinion)) {
						return `审核失败：${this.data.opinion}`
					} else {
						return `审核失败：请点击重新填表`
					}
				}
				return false
			}
		},
		onShareAppMessage: function(ops) {
			this.showModal = false
			this.getAuthRecords()
			return {
				title: "我是" + this.data.guestName + "，我正在填表申请开门，请审核",
				path: "/pages/record/record?id=" + this.shareId
			};
		},
		async onLoad(options) {
			this.loading = true
			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
						}
					}
				})
				this.loading = false
				return
			}
			
			this.id = options.id
			this.doorNeedAudit = options.doorNeedAudit
			this.memberId = options.memberId
			this.data.userId = this.memberId
			this.data.guestAuthId = this.id
			await this.getAuthRecords()
			setTimeout(() => {
				this.loading = false
			}, 200)
		},
		methods: {
			again() {
				this.auditStatus = null;
				this.operaType = 1;
				this.oldData = this.$u.deepClone(this.data)
				this.$forceUpdate()
			},
			async reload() {
				this.isReload = true
				await this.getAuthRecords()
				this.isReload = false
			},
			getPhoneNumber(e) {
				let that = this
				if (e.detail.errMsg == "getPhoneNumber:ok") {
					let params = {
						sessionKey: that.sessionKey,
						encryptedData: e.detail.encryptedData,
						iv: e.detail.iv
					}
					this.$http.getOpenData(params).then(res => {
						this.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,
					guestRecordId:this.guestRecordId
				}
				uni.redirectTo({
					url: "/pages/guest/open_door" + this.$u.queryParams(params)
				})
			},
			timeConfirm(e) {
				this.data.interviewTime = e
			},
			getTime(value) {
				let date = typeof(value) == 'string' ? value.replace(/\-/g, '/') : value
				return new Date(date).getTime()
			},
			/**
			 * 先通过id查询授权记录表查看该授权是否过期
			 * 过期了就不能进行接下来的操作，提示访客联系业主重新授权
			 * 没有过期就判断审核配置，配置了不需要审核表单就直接跳到设备列表，
			 * 需要审核就通过授权记录的id和openid查询访客记录表，查询到记录就直接跳到设备列表
			 * 查不到记录就填表
			 */
			async getAuthRecords() {
				let params = {
					id: this.id
				}
				let res = await this.$http.guestAuthorizeDetail(params)
				if (this.$isEmpty(res.data.data)) {
					this.$dialog.showModal('没有该授权记录，或者授权记录已被撤销', false).then(() => {
						this.islock = true
					})
					return
				}
				//授权详情
				let guestAuthorize = res.data.data
				this.guestAuthorize = guestAuthorize
				this.data.beginTime = this.guestAuthorize.beginDate
				this.data.interviewTime = this.guestAuthorize.beginDate
				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 (this.$isEmpty(guestRes.data.data)) {
					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
					return
				}
				//有记录，就判断审核状态
				this.data=guestRes.data.data[0]
				this.guestRecordId=this.data.id
				this.data.guestPosition = that.data.residentialName + "," +
					that.data.buildingName + "," + that.data.unitName + "," +
					that.data.roomName
				that.auditStatus = that.data.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 guestParams = {
					guestAuthId: this.id,
					openId: this.openId
				}
				let guestRes = await this.$http.guestRecordsList(guestParams)
				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.interviewTime)) {
					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.$isNotEmpty(this.data.guestIdcard) && !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
				}
				this.data.openId = this.openId
				let operation = ''
				if (this.operaType == 0) {
					//新增
					if (this.doorNeedAudit == 0) {
						//1不需要审核,直接审核通过
						this.data.auditStatus = 1
					}
				} else {
					//修改
					this.data.auditStatus = 0
				}
				this.$http.guestRecordsSubmit(this.data).then(res => {
					if (res.data.success) {
						if (this.doorNeedAudit == 0) {
							//不需要审核，直接跳转到设备列表页
							this.jumpOpenDoor()
						} else {
							this.$dialog.showModal('提交成功,请通知被访者审核', false).then(() => {
								this.getAuthRecords()
							})
							// this.shareId = res.data.guestRecordId
							// this.showModal = true
						}
					} else {
						this.$refs.uToast.show({
							title: '操作失败',
							position: "top",
							type: 'error',
						})
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.bg-gray {
		background-color: #f7f7f7;
	}

	.card {
		box-sizing: border-box;
		background-color: #FFFFFF;
	}

	.bg-red {
		background-color: #e54d42;
		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>
