<template>
	<view class="page_body">
		<!-- 头部 -->
		<nav-bar height="96" :title="state.title" :onlyTitle="true" :showHeaderborder="true" @GoBack="GoBack"></nav-bar>
		<view class="page_content">
			<uni-forms ref="valiForm" class="forms_style" :rules="rules" :model="state.formData" border
				labelWidth="160rpx" label-align="right">
				<uni-forms-item label="学年学期：" required name="schoolYearId">
					<uni-data-select v-model="state.formData.schoolYearId" :clear="false" placeholder="请选择学年学期"
						:localdata="state.schoolYearData" style="width: 320rpx;" @change="ChangSchoolYear"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="归属分类：" required name="departmentId">
					<uni-data-select v-model="state.formData.departmentId" :clear="false" placeholder="请选择归属分类"
						:localdata="state.departmentData" style="width: 320rpx;"
						@change="GetMaterialCategoryData"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="材料类目：" required name="materialCategory">
					<uni-data-select v-model="state.formData.materialCategory" :clear="false" placeholder="请选择材料类目"
						:localdata="state.materialCategoryData" style="width: 320rpx;"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="任务名称：" required name="taskName">
					<uni-easyinput v-model="state.formData.taskName" :maxlength="100" placeholder="请输入任务名称" />
				</uni-forms-item>
				<uni-forms-item class="item_textarea" label="采集要求：" required name="collectionRequire">
					<uni-easyinput type="textarea" v-model="state.formData.collectionRequire"
						:style="state.easyinputStyle" placeholder="请输入采集要求"
						placeholderStyle="font-weight: 400;font-size: 28rpx;color: #999999;"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item label="采集周期：" required name="taskTime">
					<uni-datetime-picker type="daterange" :clear-icon="false" v-model="state.formData.taskTime"
						placeholder="请选择采集周期" style="width: 480rpx;" />
				</uni-forms-item>
				<uni-forms-item label="审核机制：" required name="auditMechanism">
					<uni-data-checkbox v-model="state.formData.auditMechanism" selectedColor="#2E64FA"
						selectedTextColor="#333333" :localdata="state.radioList"></uni-data-checkbox>
				</uni-forms-item>
				<uni-forms-item label="审核人：" required name="taskAuditors" v-if="state.formData.auditMechanism === 1">
					<zxz-uni-data-select v-model="state.formData.taskAuditors" collapse-tags :collapse-tags-num="1"
						filterable multiple dataKey="teacherName" dataValue="teacherId" :clear="false"
						:localdata="state.auditorsData"></zxz-uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="采集对象：" required name="taskTargets">
					<view class="forms_target">
						<view class="target_left" @click="GoPersonList">
							<text class="left_text">{{targetTypeObj[state.formData.targetType]}}</text>
							<text class="left_text">已选{{state?.formData?.taskTargets?.length || 0}}人</text>
						</view>
						<view class="target_right" @click="SelectCollectionObject">
							<text>选择采集对象</text>
							<uni-icons class="right_icon" type="right"></uni-icons>
						</view>
					</view>
				</uni-forms-item>
			</uni-forms>
		</view>
		<view class="page_foot"><button class="btn_submit" type="primary" :loading="state.loading"
				@click="honorTypeConfirm">确认</button></view>
	</view>
</template>

<script setup>
	import navBar from '@/components/navBar.vue';
	import uniForms from '@/uni_modules/uni-forms/components/uni-forms/uni-forms.vue';
	import uniFormsItem from '@/uni_modules/uni-forms/components/uni-forms-item/uni-forms-item.vue';
	import uniEasyinput from '@/uni_modules/uni-easyinput/components/uni-easyinput/uni-easyinput.vue';
	import uniDataSelect from '@/uni_modules/uni-data-select/components/uni-data-select/uni-data-select.vue';
	import uniDatetimePicker from '@/uni_modules/uni-datetime-picker/components/uni-datetime-picker/uni-datetime-picker.vue';
	import zxzUniDataSelect from '@/uni_modules/zxz-uni-data-select/components/zxz-uni-data-select/zxz-uni-data-select.vue';
	import uniIcons from '@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue';
	import {
		getSchoolYearList,
		getCategoryList,
		queryTeacherInfo,
		getCollectionTaskInfo,
		insertCollectionTask,
		UpdateCollectionTask
	} from '@/reqApi/notification.js';
	import {getDeptTreeData,subjectTreeData,gradTreeData,permTreeData} from '@/common/common.js'
	import {
		reactive,
		ref,
		onMounted
	} from 'vue';
	import {
		onShow,
		onLoad
	} from '@dcloudio/uni-app';
	const state = reactive({
		taskId: '', //任务id
		title: '', //标题
		type: '',
		formData: {
			schoolId:'',
			schoolYearId: '', //学年学期
			schoolYearCode:'',//学年学期code
			departmentId: '', //归属分类
			materialCategory: '', //材料类目
			taskName: '', //任务名称
			collectionRequire: '', //采集要求
			taskTime: [], //采集周期
			auditMechanism: 1, //审核机制 0-无需审核 1-需要审核	
			taskAuditors: [], //审核人
			targetType:1,//采集对象 1-按部门，2-按学科，3-按年级，4-按权限，5-按学生
			taskTargets:[],//选择的采集对象明细
		},
		taskTargetsTree:[],//采集对象Tree
		schoolYearData:[],//学年学期
		departmentData:[],//归属分类
		materialCategoryData:[],//材料类目
		auditorsData:[],//审核人
		radioList:[{//审核机制
			text:'需审核',
			value:1
		},{
			text:'无审核',
			value:0
		}],
		easyinputStyle: {
			color: '#303133',
			borderColor: '#E9E9E9'
		},
		loading: false
	})
	const targetTypeObj = {
		1:'按部门',
		2:'按学科',
		3:'按年级',
		4:'按权限',
		5:'按学生'
	}
	const rules = ref({
		schoolYearId: {rules: [{required: true,errorMessage: '请选择学年学期'}]},
		departmentId: {rules: [{required: true,errorMessage: '请选择归属分类'}]},
		materialCategory: {rules: [{required: true,errorMessage: '请选择材料类目'}]},
		taskName: {rules: [{required: true,errorMessage: '请输入任务名称'}]},
		collectionRequire: {rules: [{required: true,errorMessage: '请输入采集要求'}]},
		taskTime: {rules: [{required: true,errorMessage: '请输入采集周期'}]},
		auditMechanism: {rules: [{required: true,errorMessage: '请选择审核机制'}]},
		taskTargets: {rules: [{required: true,errorMessage: '请选择采集对象'}]},
	});
	onShow(()=>{
		const taskTargetsTreeData = uni.getStorageSync('taskTargetsTreeData');//采集对象
		if(taskTargetsTreeData){
			state.formData.targetType = taskTargetsTreeData.targetType;
			state.formData.taskTargets = taskTargetsTreeData.taskTargets;//采集对象
		}
	})
	onLoad(async(option) => {
		state.taskId = option.taskId;
		state.title = state.taskId ? '编辑采集任务' : '新增采集任务';
		uni.setStorageSync('isLoadCollectTaskOverview', false); //返回列表页是否重新加载列表
		fetchSchoolYearList();//学年学期列表
		QueryTeacherInfo();//审核人
		await fetchCategoryList();//归属分类
		if(state.taskId){
			GetCollectionTaskInfo();
		}
	})
	// 学年学期列表
	const fetchSchoolYearList = async () => {
		try {
			const res = await getSchoolYearList();
			if (res.data && Array.isArray(res.data)) {
				const resData = res.data;
				state.schoolYearData = resData.map(item=>({
					...item,
					text:item.schoolYearName,
					value:item.id
				}))
				const schoolYearId = state.schoolYearData?.[0]?.value || '';
				const schoolYearCode = state.schoolYearData?.[0]?.schoolYearCode || '';
				state.formData.schoolYearId = schoolYearId;//默认值学年id
				state.formData.schoolYearCode = schoolYearCode;//默认值学年code
			}
		} catch (error) {
			console.error('获取学年学期列表失败:', error);
		}
	};
	//改变学年学期
	const ChangSchoolYear = (val) => {
		state.formData.schoolYearId = val;//学年id
		state.formData.schoolYearCode = state.schoolYearData.find(item=>item.id==val)?.schoolYearCode || '';//学年code
	}
	// 归属分类
	const fetchCategoryList = async () => {
		try {
			const res = await getCategoryList();
			if (res.data && Array.isArray(res.data)) {
				const categoryData = res.data;
				state.departmentData = categoryData.map(item=>({
					...item,
					text:item.categoryName,
					value:item.id
				}))
				const schoolId = state.departmentData?.[0]?.schoolId || '';
				state.formData.schoolId = schoolId;
			}
		} catch (error) {
			console.error('获取分类列表失败:', error);
		}
	};
	//改变归属分类
	const GetMaterialCategoryData = (val) => {
		const materialCategoryData = state.departmentData.find(item=>val == item.id)?.childList || [];
		state.materialCategoryData = materialCategoryData.map(item=>({
			...item,
			text:item.categoryName,
			value:item.id
		}))
	}
	//审核人
	const QueryTeacherInfo = () => {
		queryTeacherInfo('').then(res=>{
			if(res.code == 200){
				state.auditorsData = res?.data || [];
			}
		})
	}
	//详情
	const GetCollectionTaskInfo = () => {
		getCollectionTaskInfo(state.taskId).then(res=>{
			if(res.code == 200){
				const resData = res?.data || null;
				state.formData.schoolId = resData?.schoolId || '';
				state.formData.schoolYearId = resData?.schoolYearId || '';//学年学期
				state.formData.schoolYearCode = resData?.schoolYearCode || '';//学年学期code
				state.formData.departmentId = resData?.departmentId || '';//学年学期code
				Object.keys(state.formData).forEach(key=>{
					if(key == 'taskTime'){//采集周期
						state.formData.taskTime = [resData.startTime,resData.endTime];
					}else if(key == 'taskAuditors'){//审核人
						const taskAuditorsList = resData?.taskAuditors || [];
						state.formData.taskAuditors = taskAuditorsList.map(item=>item.auditorId);
					}else if (key == 'taskTargets') {
						const personList = resData?.personalInfoMap?.personVoList || [];
						const targetType = resData.targetType;
						let taskTargetsTree = [];
						if (targetType == 1) {
							taskTargetsTree = getDeptTreeData(personList)
						}else if (targetType === 2) {
							taskTargetsTree = subjectTreeData(personList)
						}else if (targetType === 3) {
							taskTargetsTree = gradTreeData(personList)
						}else if (targetType === 4) {
							taskTargetsTree = permTreeData(personList)
						}else{
							taskTargetsTree = [];
						}
						state.formData.taskTargets = GetSelectPerson(taskTargetsTree);//已选择
						state.taskTargetsTree = taskTargetsTree;//对象选择tree
					}else{
						state.formData[key] = resData[key];
						if(key=='departmentId'){
							GetMaterialCategoryData(resData.departmentId);
						}
					}
				})
			}
		})
	}
	//获取已选的采集对象
	const GetSelectPerson = (tree) => {
	    const result = [];
	    const dfs = (node) => {
	        if (Array.isArray(node)) {
	            node.forEach(dfs);
	        } else if (node.children && node.children.length) {
	            node.children.forEach(dfs);
	        } else if (node.selected) {
	            result.push(node);
	        }
	    };
	    dfs(tree);
	    return result;
	};
	//提交
	const honorTypeConfirm = () => {
		let ruleList = {};
		if(state.formData.auditMechanism == 1){//审核人
			const taskAuditors = {
				taskAuditors: {rules: [{required: true,errorMessage: '请选择审核人'}]}
			}
			ruleList = {...rules.value,...taskAuditors};
		}else{
			ruleList = {...rules.value}
		}
		for (const key in ruleList) {
			if (state.formData?.[key] === "" || state.formData?.[key] === null || state.formData?.[key] && state.formData?.[key]?.length === 0) {
				const errorMessage = ruleList[key].rules[0].errorMessage;
				uni.showToast({
					title: errorMessage,
					icon: 'none'
				})
				return false
			}
		}
		state.loading = true;
		const auditorsData = state.auditorsData.filter(item=>state.formData.taskAuditors.includes(item.teacherId));
		const taskAuditors = auditorsData.map(item=>({
			auditorId:item.teacherId,
			auditorName:item.teacherName
		}))
		let params = {
			schoolId: state.formData.schoolId,
			schoolYearId: state.formData.schoolYearId,
			schoolYearCode: state.formData.schoolYearCode,
			departmentId: state.formData.departmentId,
			materialCategory: state.formData.materialCategory,
			taskName: state.formData.taskName,
			collectionRequire: state.formData.collectionRequire,
			startTime: state.formData.taskTime[0],
			endTime: state.formData.taskTime[1],
			targetType: state.formData.targetType,
			auditMechanism: state.formData.auditMechanism,//审核机制 0-无需审核 1-需要审核
			taskAuditors: taskAuditors,//审核人
			taskTargets: state.formData.taskTargets//采集对象明细
		}
		if (state.taskId) {
			params.id = state.taskId;
			UpdateCollectionTask(params).then(res => {
				if (res.code == 200) {
					uni.showToast({
						title: '编辑成功！',
						icon: 'none'
					})
					uni.setStorageSync('isLoadCollectTaskOverview', true); //返回列表页是否重新加载列表
					GoBack();
				}
			}).finally(() => {
				state.loading = false;
			})
		} else { //新建
			insertCollectionTask(params).then(res => {
				if (res.code == 200) {
					uni.showToast({
						title: '新建成功！',
						icon: 'none'
					})
					uni.setStorageSync('isLoadCollectTaskOverview', true); //返回列表页是否重新加载列表
					GoBack();
				}
			}).finally(() => {
				state.loading = false;
			})
		}
	}
	//人员列表
	const GoPersonList = () => {
		uni.setStorageSync('taskTargetsTreeData',{
			targetType:state.formData.targetType,
			taskTargets:state.formData.taskTargets,//已选中
		});
		uni.navigateTo({
			url: `/pages/materialCollection/taskOverview/personList`
		});
	}
	
	//选择采集对象
	const SelectCollectionObject = () => {
		const schoolYearId = state.formData.schoolYearId;
		const targetType = state.formData.targetType;
		const type = state.taskId?'edit':'add';
		uni.setStorageSync('taskTargetsTreeData',{
			targetType:targetType,
			taskTargets:state.formData.taskTargets,//已选中
			taskTargetsTree:state.taskTargetsTree//tree
		});
		uni.navigateTo({
			url: `/pages/materialCollection/taskOverview/selectObjectNoDedup?schoolYearId=${schoolYearId}&targetType=${targetType}&type=${type}`
		});
	}
	const GoBack = () => {
		uni.navigateBack({
			delta: 1
		});
	}
</script>

<style lang="scss" scoped>
	.page_body {
		height: 100%;
		min-height: auto;
		overflow: hidden;
	}

	.page_content {
		height: calc(100% - 250rpx);
		overflow: auto;
	}

	.forms_style {
		:deep(.uni-forms-item) {
			&.uni-forms-item--border {
				border-top: 0;
				border-bottom: 2rpx solid #F3F3F3;
				align-items: center;
				&.item_textarea{
					align-items: flex-start;
				}
			}
			.forms_target{
				display: flex;
				align-items: center;
				justify-content: space-between;
				.target_left{
					flex:1;
					font-weight: 400;
					font-size: 28rpx;
					color: #2E64FA;
					.left_text{
						flex-shrink: 0;
						&:last-child{
							margin-left: 8rpx;
						}
					}
				}
				.target_right{
					flex-shrink: 0;
					font-weight: 400;
					font-size: 28rpx;
					color: #2E64FA;
					display: inline-flex;
					align-items: center;
					gap:8rpx;
					.right_icon{
						font-size: 24rpx;
						color: #2E64FA !important;
					}
				}
			}
		}
	}

	.page_foot {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		padding: 20rpx 24rpx;
		background-color: #FFFFFF;

		.btn_submit {
			width: 100%;
			height: 88rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			background-color: #2E64FA !important;
			border-radius: 20rpx;
			color: #FFFFFF;
			font-size: 28rpx;
		}
	}
</style>