<template>
	<view class="container">
		<!-- 姓名区域 -->
		<view class="box">
			<view class="box_key">
				<text class="text">*</text>
				孩子姓名
			</view>
			<view class="box_value">
				<input class="input" type="text" placeholder="请输入孩子姓名" v-model="name" />
			</view>
		</view>

		<!-- 性别区域 -->
		<view class="box">
			<view class="box_key">
				<text class="text">*</text>
				性别
			</view>
			<view class="box_value">
				<view class="men" @click="handlegender(1)">
					<radio color="#0061FF" style="transform: scale(0.7)" :checked="gender == 1" />
					男
				</view>

				<view class="women" @click="handlegender(2)">
					<radio color="#0061FF" style="transform: scale(0.7)" :checked="gender == 2" />
					女
				</view>
			</view>
		</view>

		<!-- 人脸图片区域 -->
		<view class="box2">
			<view class="box_key">
				<text class="text">*</text>
				人脸图片
			</view>
			<view v-if="!headImage" class="box_upload" @click="handleUpload">
				<uni-icons type="plusempty" size="30" color="#666666"></uni-icons>
				上传照片
			</view>
			<view v-else class="box_upload">
				<image :src="headImage" mode="aspectFill" style="width: 160rpx; height: 160rpx" @click="clickImg(headImage)"></image>
				<!-- 图片删除图标 -->
				<view class="delete" @click="deleteImg">
					<uni-icons type="close" size="20"></uni-icons>
				</view>
			</view>
		</view>
		<view class="tips">注：支持.jpg .png，五官清晰无遮挡，大小不超过2M</view>

		<!-- 时间组区域 -->
		<view class="box">
			<view class="box_key">
				<text class="text">*</text>
				时间组
			</view>

			<picker @change="bindPickerChange" :value="currentIndex" :range="timeGroups" range-key="name">
				<view class="box_value" :class="{ unactive: !currentIndex }">
					{{ currentIndex ? timeGroups[currentIndex].name : '请选择' }}
					<image class="value_img" src="/static/images/bottom2.png" mode="aspectFill"></image>
				</view>
			</picker>
		</view>

		<!-- 家属列表区域 -->
		<view v-for="(item, index) in list" :key="index">
			<!-- 家属区域 -->
			<view class="box">
				<view class="box_key">
					<text class="text">*</text>
					家属{{ index + 1 }}
				</view>
				<view class="box_value">
					<input v-model="item.name" class="input" type="text" placeholder="请输入称呼或职业" />
					<view class="value_icon">
						<uni-icons v-if="index == 0" type="plus" size="25" color="#0061FF" @click="handleAdd"></uni-icons>
						<uni-icons v-else type="close" size="25" color="#0061FF" @click="handleDelete(index)"></uni-icons>
					</view>
				</view>
			</view>

			<!-- 手机号码区域 -->
			<view class="box">
				<view class="box_key">
					<text class="text">*</text>
					手机号码
				</view>
				<view class="box_value">
					<input v-model="item.phone" class="input" type="text" placeholder="请输入手机号码" />
				</view>
			</view>

			<!-- 家属与本人的关系区域 -->
			<view class="box">
				<view class="box_key">
					<text class="text">*</text>
					家属与本人的关系
				</view>
				<view class="box_value">
					<input v-model="item.ship" class="input" type="text" placeholder="请输入家属与本人的关系" />
				</view>
			</view>
		</view>

		<!-- 确认按钮区域 -->
		<view class="btn" @click="handleConfirm">确认</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 } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { myRequest } from '@/utils/api.js'
import { decryptDes } from '@/utils/des.js'
import getLessLimitSizeImage from '@/utils/imageCompress.js'

// 姓名
const name = ref()
// 性别
const gender = ref(1)
// 照片
const headImage = ref('')
// 时间组当前激活索引
const currentIndex = ref('')
// 时间组数据
const timeGroups = ref([])

// 家属列表
const list = ref([
	{
		name: '',
		phone: '',
		ship: '',
		departmentId: uni.getStorageSync('departmentId_list')
	}
])

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

onLoad(() => {
	// 获取时间组列表数据
	getTimeGroups()
})

// 获取时间组列表数据
const getTimeGroups = async () => {
	const res = await myRequest({
		url: '/wanzai/api/smartUser/timeGroups'
	})
	// console.log(res)
	const result = JSON.parse(decryptDes(res.data))
	// console.log(result)
	timeGroups.value = result
}

// 切换性别回调
const handlegender = (v) => {
	gender.value = v
}

// 切换时间组回调
const bindPickerChange = (e) => {
	currentIndex.value = e.detail.value
}

// 上传照片回调
const handleUpload = () => {
	uni.chooseMedia({
		count: 1,
		mediaType: ['image'],
		sourceType: ['album'],
		sizeType: ['compressed'],
		success: (res) => {
			// console.log(res.tempFiles)

			res.tempFiles.forEach((ele) => {
				if (ele.fileType === 'image' && ele.size > 1024 * 1024 * 2) {
					//这里的id和页面中写的html代码的canvas的id要一致
					let canvasId = 'zipCanvas'
					//原图的路径
					let imagePath = ele.tempFilePath
					//大小限制1024kb
					let limitSize = 1024 * 2
					//初始绘画区域是画布自身的宽度也就是屏幕宽度
					let drawWidth = uni.getSystemInfoSync().windowWidth
					// 图片过大压缩
					getLessLimitSizeImage(canvasId, imagePath, limitSize, drawWidth, (resPath) => {
						handleUploadMini({ tempFilePath: resPath, fileType: ele.fileType })
					})
				} else {
					handleUploadMini(ele)
				}
			})
		}
	})
}

const handleUploadMini = (ele) => {
	uni.showLoading({
		title: '上传中，请稍后',
		mask: true
	})
	uni.uploadFile({
		url: `https://www.campussmartlife.com/smartApi/wanzai/api/upload/toCos`,
		filePath: ele.tempFilePath,
		name: 'files',
		header: {
			token: uni.getStorageSync('token') || '',
			user_head: uni.getStorageSync('userhead') || ''
		},
		success: (uploadFileRes) => {
			// console.log(uploadFileRes)
			let imgUrl = JSON.parse(uploadFileRes.data).data

			const result = JSON.parse(decryptDes(imgUrl))
			console.log(result)
			headImage.value = result
		},
		fail: () => {
			uni.showToast({
				title: '上传失败',
				icon: 'error'
			})
		},
		complete: () => {
			uni.hideLoading()
		}
	})
}

// 家属添加图标回调
const handleAdd = () => {
	list.value.push({
		name: '',
		phone: '',
		ship: '',
		departmentId: uni.getStorageSync('departmentId_list')
	})
}

// 家属删除图标回调
const handleDelete = (index) => {
	// console.log(index)
	uni.showModal({
		title: '提示',
		content: '确定删除该家属吗？',
		success: (res) => {
			if (res.confirm) {
				list.value.splice(index, 1)
			}
		}
	})
}

// 确认按钮回调
const handleConfirm = () => {
	const flag = verify()

	if (flag) {
		uni.showModal({
			title: '提示',
			content: '确定添加该学生吗？',
			success: (res) => {
				if (res.confirm) {
					handleConfirmReq()
				}
			}
		})
	}
}

// 验证提交数据是否合法
const verify = () => {
	if (!name.value) {
		uni.showToast({
			title: '请输入姓名',
			icon: 'none'
		})
		return false
	}

	let reg_name = /^[\u4e00-\u9fa5]{2,4}$/
	if (!reg_name.test(name.value)) {
		uni.showToast({
			title: '姓名格式错误',
			icon: 'none'
		})
		return false
	}

	if (!headImage.value) {
		uni.showToast({
			title: '请上传图片',
			icon: 'none'
		})
		return false
	}

	if (!currentIndex.value) {
		uni.showToast({
			title: '请选择时间组',
			icon: 'none'
		})
		return false
	}

	let res = list.value.some((ele) => !ele.name || !ele.phone || !ele.ship)

	if (res) {
		uni.showToast({
			title: '家属数据不能为空',
			icon: 'none'
		})
		return false
	}

	let res2 = list.value.some((ele) => !reg_name.test(ele.name))

	if (res2) {
		uni.showToast({
			title: '家属姓名格式错误',
			icon: 'none'
		})
		return false
	}

	let reg_phone = /^1[3-9]\d{9}$/
	let res3 = list.value.some((ele) => !reg_phone.test(ele.phone))

	if (res3) {
		uni.showToast({
			title: '家属手机号码格式错误',
			icon: 'none'
		})
		return false
	}

	return true
}

// 确认请求
const handleConfirmReq = async () => {
	let data = {
		name: name.value,
		sexId: gender.value,
		headImage: headImage.value,
		departmentId: uni.getStorageSync('departmentId'),
		gradeId: uni.getStorageSync('grade_student'),
		classId: uni.getStorageSync('classes_student'),
		timeGroupId: timeGroups.value[currentIndex.value].id,
		list: list.value
	}
	// console.log(data)
	const res = await myRequest({
		url: '/wanzai/api/smartEnrollmentUser/insertTeacherSmartEnrollmentUser',
		method: 'post',
		data
	})
	// console.log(res)
	if (res.code == 200) {
		uni.showToast({
			title: '添加成功',
			icon: 'success'
		})
		setTimeout(() => {
			uni.reLaunch({
				url: '/pages/studentManage/studentManage'
			})
		}, 1500)
	}
}

// 点击图片回调
const clickImg = (url) => {
	uni.previewImage({
		urls: [url],
		current: 1
	})
}

// 删除图片回调
const deleteImg = () => {
	uni.showModal({
		title: '提示',
		content: '确定删除该图片吗？',
		success: (res) => {
			if (res.confirm) {
				headImage.value = ''
			}
		}
	})
}
</script>

<style lang="scss" scoped>
.container {
	box-sizing: border-box;
	padding: 10rpx 0 30rpx 15rpx;
	min-height: 100vh;
	font-size: 28rpx;

	.box {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 96rpx;
		border-bottom: 2rpx solid #e6e6e6;

		.box_key {
			display: flex;
			align-items: center;
			font-weight: bold;

			.text {
				color: #d43030;
			}
		}

		.box_value {
			display: flex;
			align-items: center;
			justify-content: flex-end;
			padding-right: 20rpx;
			width: 320rpx;
			height: 96rpx;

			.input {
				height: 100%;
				text-align: end;
			}

			.men,
			.women {
				display: flex;
				align-items: center;
			}

			.women {
				margin-left: 20rpx;
			}

			.value_icon {
				margin-left: 15rpx;
			}

			.value_img {
				margin-left: 20rpx;
				width: 27rpx;
				height: 16rpx;
			}
		}

		.unactive {
			color: #6a6a6a;
		}
	}

	.box2 {
		display: flex;
		margin-top: 40rpx;

		.box_key {
			display: flex;
			font-weight: bold;

			.text {
				color: #d43030;
			}
		}

		.box_upload {
			position: relative;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			margin-left: 30rpx;
			width: 160rpx;
			height: 160rpx;
			font-size: 24rpx;
			color: #666666;
			border-radius: 6rpx;
			background-color: #f2f2f2;

			.delete {
				position: absolute;
				right: 10rpx;
				top: 10rpx;
			}
		}
	}

	.tips {
		margin-top: 20rpx;
		margin-bottom: 5rpx;
		font-size: 24rpx;
		color: #a6a6a6;
	}

	.btn {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-top: 100rpx;
		width: 710rpx;
		height: 100rpx;
		font-size: 32rpx;
		color: #fff;
		border-radius: 8rpx;
		background-color: #0061ff;
	}
}
</style>
