<template>
	<view class="container">
		<view class="body">
			<!-- 访客姓名区域 -->
			<view class="body_box">
				<view class="box_key">
					<text class="key_icon">*</text>
					访客姓名
				</view>
				<view class="box_value">
					<input :disabled="type == 1" class="value_input" type="text" placeholder="请输入访客姓名" placeholder-style="color:#CCCCCC;" v-model="visName" />
				</view>
			</view>

			<!-- 访客手机号区域 -->
			<view class="body_box">
				<view class="box_key">
					<text class="key_icon">*</text>
					访客手机号
				</view>
				<view class="box_value">
					<input :disabled="type == 1" class="value_input" type="text" placeholder="请输入访客手机号" placeholder-style="color:#CCCCCC;" v-model="visPhone" />
				</view>
			</view>

			<!-- 来访时间区域 -->
			<view class="body_box">
				<view class="box_key">
					<text class="key_icon">*</text>
					来访时间
				</view>
				<view class="box_value">
					<uni-datetime-picker v-model="visStartTime" @change="changeStart">
						<view class="value_time" :class="{ activeTime: visStartTime }">{{ visStartTime || '请选择来访时间 >' }}</view>
					</uni-datetime-picker>
				</view>
			</view>

			<view class="body_box">
				<view class="box_key">
					<text class="key_icon">*</text>
					来访结束时间
				</view>
				<view class="box_value">
					<!-- <uni-datetime-picker v-model="visEndTime" :start="visStartTime"> -->
					<view class="value_time" :class="{ activeTime: visEndTime }">{{ visEndTime || '来访时间为4小时' }}</view>
					<!-- </uni-datetime-picker> -->
				</view>
			</view>

			<!-- 证件号区域 -->
			<view class="body_box" v-if="type != 1">
				<view class="box_key">
					<text class="key_icon">*</text>
					证件号
				</view>
				<view class="box_value">
					<input :disabled="type == 1" class="value_input" type="text" placeholder="请输入访客证件号" placeholder-style="color:#CCCCCC;" v-model="visIdNumber" />
				</view>
			</view>

			<!-- 访问事由区域 -->
			<view class="body_box no_border">
				<view class="box_key">
					<text class="key_icon">*</text>
					访问事由
				</view>
				<!-- <view class="box_value">
					<input class="value_input" type="text" placeholder="请输入访问事由" placeholder-style="color:#CCCCCC;" v-model="visReason" maxlength="50" />
				</view> -->
			</view>

			<view class="textarea">
				<uni-easyinput type="textarea" :maxlength="50" placeholder="请输入访问事由(不超过50个字符)" v-model="visReason"></uni-easyinput>
			</view>

			<!-- 图片上传区域 -->
			<view class="body_box no_border" v-if="type == 1">
				<view class="box_key">
					图片
					<span class="span">（上传图片，最多{{ maxImgCount }}张）</span>
				</view>
			</view>

			<view class="filePicker" v-if="type == 1">
				<!-- 图片展示区域 -->
				<view class="img_box" v-for="(item, index) in imgList" :key="item">
					<img class="img" mode="aspectFill" :src="item" @click="handleLookImg(imgList, index)" />
					<!-- 关闭图标 -->
					<img class="close" src="@/static/images/close.png" @click="handleDelete(index)" />
				</view>

				<!-- 上传按钮区域 -->
				<img v-if="imgList.length < maxImgCount" class="uploading" src="@/static/images/uploading.png" @click="uploadingImg" />
			</view>

			<!-- 车牌号区域 -->
			<view class="body_box">
				<view class="box_key">车牌号</view>
				<view class="box_value">
					<input class="value_input" type="text" placeholder="（选填）驾车请填写车牌号" placeholder-style="color:#CCCCCC;" v-model="visCarNumber" />
				</view>
			</view>

			<!-- 同行人数区域 -->
			<view class="body_box">
				<view class="box_key">同行人数</view>
				<view class="box_value">
					<input class="value_input" type="number" placeholder="请输入同行的人数" placeholder-style="color:#CCCCCC;" v-model.number="visPeopleNum" />
					<text class="value_text">人</text>
				</view>
			</view>

			<!-- 受访者姓名区域 -->
			<view class="body_box" v-if="type == 2">
				<view class="box_key">
					<text class="key_icon">*</text>
					受访者姓名
				</view>
				<view class="box_value">
					<input :disabled="type == 2" class="value_input" type="text" placeholder="请输入受访者姓名" placeholder-style="color:#CCCCCC;" v-model="passiveName" />
				</view>
			</view>

			<!-- 受访者手机号区域 -->
			<view class="body_box" v-if="type == 2">
				<view class="box_key">
					<text class="key_icon">*</text>
					受访者手机号
				</view>
				<view class="box_value">
					<input :disabled="type == 2" class="value_input" type="text" placeholder="请输入受访者手机号" placeholder-style="color:#CCCCCC;" v-model="passivePhone" />
				</view>
			</view>

			<!-- 选择受访学生区域 -->
			<view class="body_box no_border" v-if="type == 1">
				<view class="box_key">
					<text class="key_icon">*</text>
					选择受访学生（可多选）
				</view>
			</view>

			<!-- 学生列表区域 -->
			<view class="student_list" v-if="type == 1">
				<!-- 每一个学生区域 -->
				<view class="student" v-for="item in list" :key="item.id" @click="handleClick(item)">
					<radio class="student_checked" color="#0061FF" :checked="item.isChecked" />
					<view class="student_info">{{ item.name }}（{{ item.cardNo }}）</view>
				</view>
			</view>
		</view>

		<!-- 授权区域 -->
		<label class="auth" @click="handleAuth">
			<radio style="transform: scale(0.5)" color="#0061FF" :checked="authValue" />
			<text class="auth_text">同意授权证件号用于访客身份的验证</text>
		</label>

		<!-- 按钮区域 -->
		<view class="btn" :class="{ active: btnFlag }" @click="handleSubmit">访客预约</view>

		<!-- 用于图片压缩的canvas画布 -->
		<canvas
			:style="{
				width: cw + 'px',
				height: cw + 'px',
				position: 'absolute',
				zIndex: -1,
				left: '-10000rpx',
				top: '-10000rpx'
			}"
			canvas-id="zipCanvas"
		></canvas>
		<!--画布结束-->
	</view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { myRequest } from '@/utils/api.js'
import { time_format } from '@/utils/formatTime.js'
import { isVehicleNumber } from '@/utils/plate.js'
import { decryptDes } from '@/utils/des.js'
import getLessLimitSizeImage from '@/utils/imageCompress.js'
import { cos } from '@/utils/cos.js'

// 判断是哪种身份 1为学生家长 2为其他访客
const type = ref('')

// 访客姓名
const visName = ref('')

// 访客手机号
const visPhone = ref('')

// 来访开始时间
const visStartTime = ref('')

// 来访结束时间
const visEndTime = ref('')

// 证件号
const visIdNumber = ref('')

// 访问事由
const visReason = ref('')

// 展示的图片
const imgList = ref([])

// 车牌号
const visCarNumber = ref('')

// 同行人数
const visPeopleNum = ref('')

// 受访学生列表数据
const list = ref([])

// 受访者姓名
const passiveName = ref('')

// 受访者电话
const passivePhone = ref('')

// 是否授权证件号
const authValue = ref(false)

// 图片上传的最大数
const maxImgCount = ref(3)

//画板边长默认是屏幕宽度，正方形画布
const cw = uni.getSystemInfoSync().windowWidth

// 预约按钮是否高亮展示
const btnFlag = computed(() => {
	const tem = list.value.some((item) => item.isChecked)
	if (
		visName.value &&
		visPhone.value &&
		visStartTime.value &&
		visEndTime.value && [type.value === '1' && !visIdNumber.value] &&
		visReason.value && [type.value === '1' && !list.value.length] && [type.value === '1' && !tem] && [type.value === '2' && !passiveName.value] && [
			type.value === '2' && !passivePhone.value
		] &&
		authValue.value
	) {
		return true
	} else {
		return false
	}
})

onLoad((options) => {
	type.value = options.type
	if (type.value === '1') {
		visName.value = uni.getStorageSync('userInfo').name
		visPhone.value = uni.getStorageSync('userInfo').phone
		visIdNumber.value = uni.getStorageSync('userInfo').idCard
		getList()
	} else {
		passiveName.value = uni.getStorageSync('userInfo').name
		passivePhone.value = uni.getStorageSync('userInfo').phone
	}
})

// 获取家长绑定学生数组
const getList = async () => {
	const res = await myRequest({
		url: '/wanzai/api/smartUser/queryAffiliateUserById',
		data: {
			id: uni.getStorageSync('userInfo').id
		}
	})
	// console.log(res)
	const result = JSON.parse(decryptDes(res.data))
	list.value = result
}

// 访客预约按钮回调
const handleSubmit = () => {
	const flag = verifyValue()
	if (flag) {
		if (type.value === '1') {
			parentAppointment()
		} else {
			otherAppointment()
		}
	}
}

// 家长预约请求
const parentAppointment = async () => {
	let temList = []
	list.value.forEach((ele) => {
		if (ele.isChecked) {
			temList.push(ele)
		}
	})

	const res = await myRequest({
		url: '/wanzai/api/smartVisitor/parentsAppointment',
		method: 'post',
		data: {
			userId: uni.getStorageSync('userInfo').id,
			visitorTime: visStartTime.value,
			visitReason: visReason.value,
			carNum: visCarNumber.value,
			peerNum: visPeopleNum.value ? visPeopleNum.value : 0,
			image: imgList.value.join(','),
			students: temList
		}
	})
	// console.log(res)
	uni.showToast({
		title: res.message,
		icon: 'none',
		duration: 2000
	})
	setTimeout(() => {
		uni.setStorageSync('Tab-activeIndex', 1)
		uni.reLaunch({
			url: '/pagesReservation/record/record'
		})
	}, 2000)
}

// 其他访客预约请求
const otherAppointment = async () => {
	const res = await myRequest({
		url: '/wanzai/api/smartVisitor/otherAppointment',
		method: 'post',
		data: {
			userId: uni.getStorageSync('userInfo').id,
			userName: visName.value,
			userPhone: visPhone.value,
			userCard: visIdNumber.value,
			visitorTime: visStartTime.value,
			visitReason: visReason.value,
			carNum: visCarNumber.value,
			peerNum: visPeopleNum.value ? visPeopleNum.value : 0,
			respondentName: passiveName.value,
			respondentPhone: passivePhone.value
		}
	})
	// console.log(res)
	uni.showToast({
		title: res.message,
		icon: 'none',
		duration: 2000
	})
	setTimeout(() => {
		uni.setStorageSync('Tab-activeIndex', 2)
		uni.reLaunch({
			url: '/pagesReservation/record/record'
		})
	}, 2000)
}

// 选择来访开始时间时的回调
const changeStart = (e) => {
	// 兼容ios部分系统转换时间格式
	const temTime = e.replace(/-/g, '/')
	// 转化成时间戳
	const timestamp = Date.parse(new Date(temTime))
	// 默认访问时间4小时
	const addTime = 1000 * 60 * 60 * 4

	visEndTime.value = time_format(timestamp + addTime)
}

// 验证表格数据是否符合规范
const verifyValue = () => {
	// 姓名验证规则
	const regName = /^[\u4e00-\u9fa5]{2,4}$/
	// 手机号码验证规则
	const regPhone = /^1[3-9]\d{9}$/
	// 身份证号码验证规则
	const regIdentity = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/

	if (!visName.value) {
		uni.showToast({
			title: '请输入访客姓名',
			icon: 'none'
		})
		return false
	}
	if (!regName.test(visName.value)) {
		uni.showToast({
			title: '姓名格式错误',
			icon: 'none'
		})
		return false
	}
	if (!visPhone.value) {
		uni.showToast({
			title: '请输入访客手机号',
			icon: 'none'
		})
		return false
	}
	if (!regPhone.test(visPhone.value)) {
		uni.showToast({
			title: '手机号码格式错误',
			icon: 'none'
		})
		return false
	}
	if (!visStartTime.value) {
		uni.showToast({
			title: '请选择来访时间',
			icon: 'none'
		})
		return false
	}
	if (!visEndTime.value) {
		uni.showToast({
			title: '请选择来访结束时间',
			icon: 'none'
		})
		return false
	}
	if (type.value != 1 && !visIdNumber.value) {
		uni.showToast({
			title: '请输入访客证件号',
			icon: 'none'
		})
		return false
	}
	if (type.value != 1 && !regIdentity.test(visIdNumber.value)) {
		uni.showToast({
			title: '证件号格式错误',
			icon: 'none'
		})
		return false
	}
	if (!visReason.value) {
		uni.showToast({
			title: '请输入访问事由',
			icon: 'none'
		})
		return false
	}
	if (visCarNumber.value && !isVehicleNumber(visCarNumber.value)) {
		uni.showToast({
			title: '请输入正确的车牌号',
			icon: 'none'
		})
		return false
	}

	if (type.value === '1' && !list.value.length) {
		uni.showToast({
			title: '请绑定学生后再开始预约',
			icon: 'none'
		})
		return false
	}
	const tem = list.value.some((item) => item.isChecked)
	if (type.value === '1' && !tem) {
		uni.showToast({
			title: '请选择受访学生',
			icon: 'none'
		})
		return false
	}
	if (type.value === '2' && !passiveName.value) {
		uni.showToast({
			title: '请输入受访者姓名',
			icon: 'none'
		})
		return false
	}
	if (type.value === '2' && !regName.test(passiveName.value)) {
		uni.showToast({
			title: '受访者姓名格式错误',
			icon: 'none'
		})
		return false
	}
	if (type.value === '2' && !passivePhone.value) {
		uni.showToast({
			title: '请输入受访者电话',
			icon: 'none'
		})
		return false
	}
	if (type.value === '2' && !regPhone.test(passivePhone.value)) {
		uni.showToast({
			title: '受访者手机号格式错误',
			icon: 'none'
		})
		return false
	}
	if (!authValue.value) {
		uni.showToast({
			title: '请同意授权证件号',
			icon: 'none'
		})
		return false
	}
	return true
}

// 点击每一个学生回调
const handleClick = (item) => {
	item.isChecked = !item.isChecked
}

// 点击授权radio时的回调
const handleAuth = () => {
	authValue.value = !authValue.value
}

// 点击上传图片时的回调
const uploadingImg = () => {
	uni.chooseMedia({
		count: maxImgCount.value - imgList.value.length,
		mediaType: ['image'],
		sizeType: ['compressed'],
		success: (res) => {
			// console.log(res)
			res.tempFiles.forEach((ele) => {
				//这里的id和页面中写的html代码的canvas的id要一致
				let canvasId = 'zipCanvas'
				//原图的路径
				let imagePath = ele.tempFilePath
				//大小限制1024kb
				let limitSize = 1024 * 3
				//初始绘画区域是画布自身的宽度也就是屏幕宽度
				let drawWidth = uni.getSystemInfoSync().windowWidth
				// 图片过大压缩
				getLessLimitSizeImage(canvasId, imagePath, limitSize, drawWidth, (resPath) => {
					handleUploadMini(resPath, 1)
				})
			})
		}
	})
}

// 上传请求
const handleUploadMini = (ele) => {
	// 开始上传
	uni.showLoading({
		title: '上传中',
		mask: true
	})

	let filePath = ele
	let Key = filePath.substr(filePath.lastIndexOf('/') + 1)

	cos.postObject(
		{
			Bucket: 'wanzai-1306339220',
			Region: 'ap-shanghai',
			Key: Key,
			FilePath: filePath,
			onProgress: (info) => {
				// console.log(info)
			}
		},
		(err, data) => {
			if (err) {
				console.log('上传失败', err)
			} else {
				console.log('上传成功', data)

				uni.hideLoading()
				let imgUrl = 'https://' + data.Location
				imgList.value.push(imgUrl)
				console.log(imgList.value)
			}
		}
	)
}

// 删除图片回调
const handleDelete = (index) => {
	imgList.value.splice(index, 1)
}

// 点击图片回调
const handleLookImg = (urls, current) => {
	uni.previewImage({
		urls,
		current
	})
}
</script>

<style lang="scss" scoped>
.container {
	display: flex;
	flex-direction: column;
	min-height: 100vh;
	background-color: #f1f6fe;

	.body {
		margin-top: 20rpx;
		padding-left: 20rpx;
		background-color: #fff;

		.body_box {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding-right: 20rpx;
			height: 85rpx;
			font-size: 28rpx;
			border-bottom: 1rpx solid #e6e6e6;

			.box_key {
				.key_icon {
					color: #d43030;
				}

				.span {
					font-size: 20rpx;
					color: #999999;
				}
			}

			.box_value {
				display: flex;
				justify-content: flex-end;
				align-items: center;
				width: 50%;

				.value_input {
					text-align: right;
				}

				.value_text {
					margin-left: 20rpx;
				}

				.value_time {
					text-align: end;
					color: #cccccc;
				}

				.activeTime {
					color: #000;
				}
			}
		}

		.textarea {
			padding-right: 20rpx;
			width: 710rpx;
		}

		.filePicker {
			display: flex;
			margin-bottom: 20rpx;
			height: 100rpx;

			.img_box {
				position: relative;
				margin-right: 20rpx;
				width: 100rpx;
				height: 100rpx;

				.img {
					width: 100rpx;
					height: 100rpx;
				}

				.close {
					position: absolute;
					top: 0;
					right: 0;
					width: 40rpx;
					height: 40rpx;
					background-color: rgba(000, 000, 000, 0.3);
				}
			}

			.uploading {
				width: 100rpx;
				height: 100rpx;
			}
		}

		.no_border {
			border: none;
		}

		.student_list {
			.student {
				display: flex;
				align-items: center;
				margin-bottom: 30rpx;
				width: 710rpx;
				height: 110rpx;
				border-radius: 18rpx;
				background-color: #f2f4f9;

				.student_checked {
					margin-left: 48rpx;
				}

				.student_info {
					margin-left: 53rpx;
					font-size: 32rpx;
				}
			}
		}
	}

	.auth {
		display: flex;
		align-items: center;
		margin: 20rpx 0 40rpx 20rpx;
		font-size: 24rpx;

		.auth_text {
			height: 35rpx;
		}
	}

	.btn {
		display: flex;
		justify-content: center;
		align-items: center;
		margin: 0 auto 100rpx;
		width: 710rpx;
		height: 100rpx;
		color: #fff;
		font-size: 32rpx;
		border-radius: 8rpx;
		background-color: #95b8e6;
	}

	.active {
		background-color: #0061ff;
	}
}
</style>
