<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 { onLoad } from "@dcloudio/uni-app";
	// 请求接口
	const $api = inject('$api');
	const $apifile = inject('$apifile');
	// 基本信息
	const config = ref({ logo: [], file: [] });
	const form = ref({ icon: [], card: [] });
	const errors = ref({});
	// user
	const user = computed(() => {
		return uni.getStorageSync('user');
	})
	// 字典表
	const genderList = ref([])
	const educationList = ref([])
	const learnStatusList = ref([])
	const showList = ref([])
	onLoad(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: 'learnStatus', is_use: '0' });
		if (res.errcode === 0) learnStatusList.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.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
				}
				form.value = res.data
				uni.setStorageSync('user', { ...res.data, role_type: user.value.role_type });
			}
		}
	};
	// 删除图片
	const deletePic = (event) => {
		const file = form.value[event.name].filter(i => i.url !== event.file.url)
		form.value[event.name] = file
	};
	// 新增图片
	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[event.name] = [...form.value[event.name], ...[result]]
	};
	// 学历类型选择
	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 bindDateChange = (e) => {
		form.value.birth = e.detail.value
	};
	// 自定义的验证函数
	const validateObject = (obj : any) => {
		const errors : any = {};
		if (!obj.nick_name || obj.nick_name.trim() === '') {
			errors.nick_name = '请填写昵称！';
		}
		if (!obj.birth || obj.birth.trim() === '') {
			errors.birth = '请选择出生日期！';
		}
		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') {
			if (!obj.is_show || obj.is_show.trim() === '') {
				errors.is_show = '请选择是否公开！';
			}
			if (!obj.education || obj.education.trim() === '') {
				errors.education = '请选择学历！';
			}
			if (!obj.college || obj.college.trim() === '') {
				errors.college = '请输入院校！';
			}
			if (!obj.card || !obj.card.some(value => value !== undefined)) {
				errors.card = '请上传身份证照片！';
			}
		}
		// 如果有错误，返回错误对象
		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 == 'education_name' || key == 'learnStatus_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;
			data.status = '0'
			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();
				if (user.value.role_type == 'Student') {
					uni.showToast({
						title: '保存成功',
						icon: 'success'
					});
				}
				else {
					uni.showToast({
						title: '保存成功，等待管理员审核方可展示！',
						icon: 'none'
					});
				}
			}
		}
	};
	// provide
	provide('form', form)
	provide('errors', errors)
	provide('deletePic', deletePic)
	provide('afterRead', afterRead)
	provide('formSubmit', formSubmit)
	provide('educationChange', educationChange)
	provide('learnStatusChange', learnStatusChange)
	provide('bindDateChange', bindDateChange)
	// 字典
	provide('showList', showList)
	provide('genderList', genderList)
	provide('learnStatusList', learnStatusList)
	provide('educationList', educationList)
</script>
<style lang="scss" scoped>
	.content {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
		background-color: var(--f1Color);
	}
</style>