<template>
	<view class="content">
		<view class="one" v-show="user.role_type=='Teacher'">
			<teacher></teacher>
		</view>
		<view class="two" v-show="user.role_type=='Student'">
			<student></student>
		</view>
	</view>
</template>

<script setup lang="ts">
	import teacher from "./path/teacher.vue"
	import student from "./path/student.vue"
	import { inject, provide, computed, ref } from 'vue';
	//该依赖已内置不需要单独安装
	import { onShow, onPullDownRefresh } from "@dcloudio/uni-app";
	// 请求接口
	const $api = inject('$api');
	const $config = inject('$config');
	const $apifile = inject('$apifile');
	// 基本信息
	const config = ref({ logo: [], file: [] });
	const form = ref({ icon: [] });
	const errors = ref({});
	// user
	const user = computed(() => {
		return uni.getStorageSync('user');
	})
	// 字典表
	const genderList = ref([])
	const educationList = ref([])
	const learnStatusList = ref([])
	const gradeList = ref([])
	const cardTypeList = ref([])
	const subjectList = ref([])
	const showList = ref([])
	onShow(async () => {
		await searchConfig();
		await searchOther();
		await search();
	})
	// config信息
	const searchConfig = async () => {
		config.value = uni.getStorageSync('config');
	};
	// 其他查询信息
	const searchOther = async () => {
		let res;
		// 性别
		res = await $api(`dictData`, 'GET', { code: 'gender', is_use: '0' });
		if (res.errcode === 0) genderList.value = res.data;
		// 学历
		res = await $api(`dictData`, 'GET', { code: 'education', is_use: '0' });
		if (res.errcode === 0) educationList.value = res.data;
		// 年级
		res = await $api(`dictData`, 'GET', { code: 'grade', is_use: '0' });
		if (res.errcode === 0) gradeList.value = res.data;
		// 学业状态
		res = await $api(`dictData`, 'GET', { code: 'learnStatus', is_use: '0' });
		if (res.errcode === 0) learnStatusList.value = res.data;
		// 身份证类型
		res = await $api(`dictData`, 'GET', { code: 'cardType', is_use: '0' });
		if (res.errcode === 0) cardTypeList.value = res.data;
		// 学科
		res = await $api(`dictData`, 'GET', { code: 'subject', is_use: '0' });
		if (res.errcode === 0) subjectList.value = res.data;
		// 是否公开
		res = await $api(`dictData`, 'GET', { code: 'show', is_use: '0' });
		if (res.errcode === 0) showList.value = res.data;
	};
	// 查询
	const search = async () => {
		if (user && user.value._id) {
			let res;
			if (user.value.role_type == 'Teacher') res = await $api(`teacher/${user.value._id}`, 'GET', {});
			else res = await $api(`student/${user.value._id}`, 'GET', {});
			if (res.errcode == '0') {
				if (res.data.cardType) {
					const data = cardTypeList.value.find(i => i.value === res.data.cardType)
					if (data) res.data.cardType_name = data.label
				}
				if (res.data.education) {
					const data = educationList.value.find(i => i.value === res.data.education)
					if (data) res.data.education_name = data.label
				}
				if (res.data.learnStatus) {
					const data = learnStatusList.value.find(i => i.value === res.data.learnStatus)
					if (data) res.data.learnStatus_name = data.label
				}
				if (res.data.grade) {
					const data = gradeList.value.find(i => i.value === res.data.grade)
					if (data) res.data.grade_name = data.label
				}
				if (res.data.subject) {
					const data = subjectList.value.find(i => i.value === res.data.subject)
					if (data) res.data.subject_name = data.label
				}
				form.value = res.data
				uni.setStorageSync('user', { ...res.data, role_type: user.value.role_type });
			}
		}
	};
	// 删除图片
	const deletePic = (event) => {
		form.value.icon = []
	};
	// 新增图片
	const afterRead = async (event) => {
		const url = event.file[0].url
		const result = await $apifile(`/web/learn_user/upload`, 'file', url, 'file');
		if (result.errcode === 0) form.value.icon = [result]
	};
	// 身份类型选择
	const cardChange = (e) => {
		const data = cardTypeList.value[e.detail.value]
		if (data) {
			form.value.cardType = data.value
			form.value.cardType_name = data.label
		}
	};
	// 学历类型选择
	const educationChange = (e) => {
		const data = educationList.value[e.detail.value]
		if (data) {
			form.value.education = data.value
			form.value.education_name = data.label
		}
	};
	// 学业状态类型选择
	const learnStatusChange = (e) => {
		const data = learnStatusList.value[e.detail.value]
		if (data) {
			form.value.learnStatus = data.value
			form.value.learnStatus_name = data.label
		}
	};
	// 年级类型选择
	const gradeChange = (e) => {
		const data = gradeList.value[e.detail.value]
		if (data) {
			form.value.grade = data.value
			form.value.grade_name = data.label
		}
	};
	// 学科类型选择
	const subjectChange = (e) => {
		const data = subjectList.value[e.detail.value]
		if (data) {
			form.value.subject = data.value
			form.value.subject_name = data.label
		}
	};
	// 自定义的验证函数
	const validateObject = (obj : any) => {
		const errors : any = {};
		// 检查name属性是否填写
		if (!obj.nick_name || obj.nick_name.trim() === '') {
			errors.nick_name = '请填写昵称！';
		}
		// 检查email属性是否填写
		if (!obj.age || obj.age.trim() === '') {
			errors.age = '请填写年龄！';
		}
		// 检查email属性是否填写
		if (!obj.gender || obj.gender.trim() === '') {
			errors.gender = '请填写性别！';
		}
		// 检查email属性是否填写
		if (!obj.phone || obj.phone.trim() === '') {
			errors.phone = '请填写手机号！';
		} else {
			const regex = /^1[3456789]\d{9}$/;
			if (!regex.test(obj.phone)) errors.phone = '请填写正确的手机号码！';
		}
		if (user.value.role_type == 'Teacher') {
			// 检查email属性是否填写
			if (!obj.cardType || obj.cardType.trim() === '') {
				errors.cardType = '请选择证件类型！';
			}
			// 检查email属性是否填写
			if (!obj.card || obj.card.trim() === '') {
				errors.card = '请填写证件号码！';
			} else {
				let regex;
				if (obj.cardType == '0') regex = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}([0-9]|X)$/;
				else regex = /^\d{9}$/;
				if (!regex.test(obj.card)) errors.card = '请填写正确的证件号码！';
			}
			// 检查email属性是否填写
			if (!obj.is_show || obj.is_show.trim() === '') {
				errors.is_show = '请选择是否公开！';
			}
		}
		// 如果有错误，返回错误对象
		if (Object.keys(errors).length > 0) {
			return errors;
		}
		// 如果没有错误，返回null或undefined
		return null;
	}
	// 处理两个对象合并
	const mergeObjectsWithoutDuplicates = async (obj1, obj2) => {
		return Object.keys({ ...obj1, ...obj2 }).reduce((acc, key) => {
			if (!acc.hasOwnProperty(key)) {
				if (key == 'cardType_name' || key == 'education_name' || key == 'learnStatus_name' || key == 'grade_name' || key == 'subject_name') {
					delete acc[key]
				} else {
					// 如果累加器对象（acc）中不存在该键，则添加它
					acc[key] = obj1.hasOwnProperty(key) ? obj1[key] : obj2[key];
				}
			}
			return acc;
		}, {});
	}
	// 保存
	const formSubmit = async (e) => {
		// 调用验证函数
		const data = await mergeObjectsWithoutDuplicates(e.detail.value, form.value);
		const errorsInfo = await validateObject(data);
		// 检查是否有错误
		if (errorsInfo) {
			errors.value = errorsInfo
			// 遍历错误对象并显示错误信息
			for (const key in errorsInfo) {
				if (errorsInfo.hasOwnProperty(key)) {
					console.error(`${key} 错误: ${errorsInfo[key]}`);
				}
			}
		} else {
			errors.value = {}
			let res;
			if (user.value.role_type == 'Teacher') res = await $api(`teacher/${form.value._id}`, 'POST', data);
			else res = await $api(`student/${form.value._id}`, 'POST', data);
			if (res.errcode == '0') {
				await search();
				uni.showToast({
					title: '保存成功',
					icon: 'success'
				});
			}
		}
	};
	// provide
	provide('form', form)
	provide('errors', errors)
	provide('deletePic', deletePic)
	provide('afterRead', afterRead)
	provide('formSubmit', formSubmit)
	provide('cardChange', cardChange)
	provide('educationChange', educationChange)
	provide('learnStatusChange', learnStatusChange)
	provide('gradeChange', gradeChange)
	provide('subjectChange', subjectChange)
	// 字典
	provide('showList', showList)
	provide('genderList', genderList)
	provide('gradeList', gradeList)
	provide('subjectList', subjectList)
	provide('learnStatusList', learnStatusList)
	provide('cardTypeList', cardTypeList)
	provide('educationList', educationList)
</script>
<style lang="scss" scoped>
	.content {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
		background-color: var(--f1Color);
	}
</style>