<template>
	<view>
		<view class="is-debug">
			<view class="guest-list" v-for="guest in guestListDebug">
				<u-form class="guest-form" :model="guestModel" labelAlign="center" :ref="'form' + guest.id">
					<u-form-item class="guest-form-item" label="姓名:" prop="guest.name" labelWidth="160rpx">
						<u-input placeholder="请输入姓名" border="surround" v-model="guest.name" clearable></u-input>
					</u-form-item>
					<u-form-item class="guest-form-item" label="证件号:" prop="guest.idNumber" labelWidth="160rpx">
						<u-input placeholder="请输入证件号" border="surround" v-model="guest.idNumber" clearable></u-input>
					</u-form-item>
					<view class="guest-form-bottom">
						<u-form-item class="" :label="uploadPicTip" prop="guest.pic" labelWidth="160rpx">
							<u-upload :fileList="guest.pic" @afterRead="afterRead" @delete="deletePic" :name="guest.id"
								:maxCount="1" :previewFullImage="true" :maxSize="1024*1024*1.5" @oversize="oversize"></u-upload>
						</u-form-item>
						<view class="delete-guest-btn">
							<u-button v-if="guestListDebug.length>1" type="error"
								@click="deleteGuest(guest.id)">删除入住人</u-button>
						</view>
					</view>
				</u-form>
			</view>
			<view class="bottom">
				<view class="add-guest-btn">
					<u-button type="primary" :disabled="this.guestListDebug.length >= 3 && addGuestButtonDisabled"
						@click="addGuest">添加入住人</u-button>
				</view>
				<view class="checkin-btn">
					<u-button type="primary" @click="checkin" :loading="debugCheckinButtonLoading"
						:loadingText="debugCheckinButtonLoadingText" :disabled="checkinButtonDisabled">入住</u-button>
				</view>
			</view>
		</view>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import moment from 'moment'
	export default {
		data() {
			return {
				nameTip: '姓名：',
				idNumberTip: '证件号：',
				uploadPicTip: '上传人脸：',
				guestListDebug: [{
					id: 0,
					name: '',
					idNumber: '',
					pic: [],
					picBase64: '',
					picValid: false,
					checkinButtonDisabled: false
				}],
				guestModel: {
					guestInfo: {
						name: '',
						idNumber: '',
						pic: []
					}
				},
				reservation: {},
				debugCheckinButtonLoading: false,
				debugCheckinButtonLoadingText: '办理中',
				addGuestButtonDisabled: false
			};
		},
		computed: {
			...mapState('m_user', ['userInfo']),
			...mapState('m_business', ['hotelParams']),
		},
		methods: {
			addGuest() {
				if (this.guestListDebug.length < 3) {
					this.guestListDebug.push({
						id: this.guestListDebug[this.guestListDebug.length - 1].id + 1,
						name: '',
						idNumber: '',
						pic: [],
						picBase64: '',
						picValid: false
					})
					console.log(this.guestListDebug[this.guestListDebug.length - 1].id)
				} else {
					uni.$showMsg('入住人数已达到上限！')
				}
			},
			oversize(){
				uni.$showMsg('图片超出允许大小（1.5M）')
			},
			//删除图片
			deletePic(event) {
				console.log(event.name)
				this.guestListDebug.forEach(guest => {
					console.log(guest)
					if (guest.id == event.name) {
						guest.pic = []
						guest.picBase64 = ''
						return
					}
				})
			},
			//上传图片
			async afterRead(event) {
				let _this = this
				let params = {
					type: 'loading',
					message: '正在加载',
					duration: '500'
				}
				this.$refs.uToast.show({
					...params,
					complete() {
						console.log(event)
						_this.guestListDebug.forEach(guest => {
							console.log(guest.id)
							console.log(guest.id == event.name)
							if (guest.id == event.name) {
								guest.pic.push(event.file)
								uni.getFileSystemManager().readFile({
									filePath: guest.pic[0].url, //选择图片返回的相对路径
									encoding: 'base64', //编码格式
									success: res => {
										console.log(res);
										guest.picBase64 = res.data
										uni.$http.post('/faceVerification/checkPic', {
											hotelId: _this.reservation.hotelId,
											faceData: guest.picBase64
										}).then((res) => {
											if (res.data.code === 200 && res.data
												.success ===
												true) {
												uni.$showMsg('上传成功！')
												guest.picValid = true
											} else {
												uni.$showMsg('未检测到人脸，请重新上传！')
											}
											console.log(res)
										})
									},
									fail: (e) => {
										uni.$showMsg('图片转换失败，请重试！')
										console.log("图片转换失败!");
										console.log(e);
									}
								})
							}
						})
					}
				})

			},
			deleteGuest(id) {
				console.log(id)
				this.guestListDebug = this.guestListDebug.filter(guest => guest.id != id)
			},
			async checkin() {
				//检查姓名、证件号是否填入，上传图片是否通过检查
				if (this.guestListDebug.length < 1) {
					uni.$showMsg('请添加入住人！')
					return
				} else {
					let isEmpty = false;
					let allPicValid = true;
					this.guestListDebug.forEach((guest) =>
						Object.keys(guest).forEach(key => {
							console.log(key + ' + ' + guest[key])
							if (!guest.picValid) {
								allPicValid = false
							}
							if (guest[key] === null || guest[key] === undefined || guest[
									key] === '') {
								isEmpty = true;
								return
							}
						})
					)
					if (isEmpty) {
						uni.$showMsg('请正确填写信息！')
						return
					}
					if (!allPicValid) {
						uni.$showMsg('请检查图片！')
						return
					}
				}
				//办理入住
				this.debugCheckinButtonLoading = true
				try {
					let start = new Date(this.reservation.startTime)
					let checkinInfo = {
						hotelId: this.reservation.hotelId,
						building: this.reservation.building,
						floorId: this.reservation.floor,
						roomId: this.reservation.room,
						startTime: moment(this.reservation.startTime).format('YYMMDDHHmmss'),
						endTime: moment(this.reservation.endTime).format('YYMMDDHHmmss'),
						cardId: '0',
						userType: 1,
						isDebug: this.userInfo.isDebug
					}
					let checkinResult = new Array(this.guestListDebug.length).fill(false)
					console.log(checkinResult)
					for (let i = 0; i < this.guestListDebug.length; i++) {
						checkinInfo.userName = this.guestListDebug[i].name;
						checkinInfo.userId = this.guestListDebug[i].idNumber;
						checkinInfo.faceData = this.guestListDebug[i].picBase64;
						let res = await uni.$http.post('/checkin', checkinInfo)
						console.log(res)
						if (res.data.code == 200 && res.data.success === true) {
							checkinResult[i] = true
							console.log('checkinResult[' + i + '] = true')
						}
					}
					if (checkinResult.indexOf(false) < 0) {
						uni.$showMsg('办理成功！')
						setTimeout(() => {
							uni.switchTab({
								url: '/pages/home/home'
							})
						}, 1500)
					} else {
						let failMsg = '办理失败！'
						uni.$showMsg(failMsg)
					}
				} catch (e) {
					console.log(e)
					let failMsg = '办理失败！'
					uni.$showMsg(failMsg)
				} finally {
					this.debugCheckinButtonLoading = false
				}
			},
			async getReservationInfo() {
				let res = await uni.$http.post('/userPicRoomInfo/queryByCondition', {
					userId: this.userInfo.userId,
					// userId: 29,
					status: true,
					pageNo: 1,
					pageSize: 1
				})
				console.log(res)
				if (res.data.data.records?.length > 0) {
					this.reservation = res.data.data.records[0]
					this.reservation.startTime = moment(this.reservation.startTime).format('YYYY/MM/DD HH:mm:ss')
					this.reservation.endTime = moment(this.reservation.endTime).format('YYYY/MM/DD HH:mm:ss')
				} else {
					this.reservation = {}
				}
				console.log(this.reservation)
			}
		},
		onLoad() {
			this.getReservationInfo()
			this.guestListDebug[0].idNumber = this.userInfo.idNumber
			this.guestListDebug[0].name = this.userInfo.name
		}
	}
</script>

<style lang="scss">
	.is-debug {
		height: 900rpx;
		overflow: scroll;
	}

	.guest-list {
		border: 1rpx solid grey;
		margin: 20rpx;
	}

	.guest-form-item {
		display: flex;
		width: 80%;
	}

	.guest-form-item-tip {
		width: 160rpx;
		display: flex;
		margin-left: 20rpx;
	}

	.add-guest-btn,
	.checkin-btn {
		width: 80%;
		height: 72rpx;
		margin: 40rpx auto;
	}

	.u-input {
		width: 80%;
	}

	.guest-form-bottom {
		display: flex;
	}

	.delete-guest-btn {
		margin: 0 auto;
		position: relative;
		top: 30%;
		/*偏移*/
		transform: translateY(30%);
		text-align: center;
	}

	.bottom {
		z-index: 999;
		position: fixed;
		bottom: 0;
		background-color: white;
		width: 100%;
		height: 300rpx;
	}
</style>