﻿<template>
	<view class="page_body">
		<!-- 头部 -->
		<nav-bar :class="{'item_width':pageType=='edit'}" height="320" title="选择采集对象" :defaultTabBtnValue="targetType" :tabBtns="state.tabBtns" :onlyTitle="false" :showHeadSearchInput="false" :showFilterPicker="false" :showTabs="false" :showTabBtns="true" rightWidth="0rpx" @CommonFilterData="CommonFilterData" @GoBack="GoBack">
			<template #tabs_bottom_content>
				<!-- 搜索框单独一行 -->
				<view class="nav_head row_search_box">
					<uni-easyinput class="search_box" v-model="state.searchWord" trim="all" :styles="state.searchInputStyles"
						:placeholderStyle="state.searchInputPlaceholderStyle" placeholder="请输入关键字搜索">
						<template #left>
							<image src="@/static/image/overview/search.png" class="search_icon"></image>
						</template>
					</uni-easyinput>
				</view>
			</template>
		</nav-bar>
		<!-- https://ofreshman.github.io/uni-tree-view/guide/quick-start -->
		<!-- expand-on-click-node: 点击整行是否展开/收起-->
		<view class="tree_node">
			<uni-tree-view
			    selectable
			    multiple
				ref="treeRef"
				theme-color="#2E64FA"
				v-model="state.defaultCheckedKeys"
				:default-expand-all="true"
				:expand-on-click-node="true"
				:checked-disabled="true"
				:filter-value="state.searchWord"
				highlight-filter
			    :data="state.treeData"
				@check-change="HandleCheckChange"
			>
			<template #append="{ data,node }">
			    <!-- data 是你传入的原始数据项，可读任意业务字段 -->
			    <text v-if="data?.children?.length" style="color:#87918b; font-size:17rpx;">
				  <uni-icons :type="node.expanded?'down':'right'" style="font-size: 28rpx;color: #999999;"></uni-icons>
			    </text>
			  </template>
			</uni-tree-view>
		</view>
		<view class="foot_btn">
			<view class="btn_submit" @click="SaveCheckedTreeData">确定{{state.checkedValue.length?`（已选${state.checkedValue.length}人）`:''}}</view>
		</view>
	</view>
</template>

<script setup>
	import navBar from '@/components/navBar.vue';
	import {findDepartContainUser,findCollectPersonalInfo} from '@/reqApi/notification.js';
	import {getDeptTreeData,subjectTreeData,gradTreeData,permTreeData} from '@/common/common.js';
	import {onLoad} from '@dcloudio/uni-app';
	import {reactive,ref,onUnmounted,nextTick} from 'vue';
	const state = reactive({
		tabBtns:[{
			label:'按部门',
			value:1,
		},{
			label:'按学科',
			value:2,
		},{
			label:'按年级',
			value:3,
		},{
			label:'按权限',
			value:4,
		}],
		defaultCheckedKeys:[],//初始选中key
		checkedDisabled:[],
		checkedValue:[],//勾选的项
		treeData:[],
		deptTreeData:[],//部门tree
		gradeTreeList:[],//年级tree
		permissionTreeList:[],//权限tree
		subjectTreeList:[]//学科tree
	});
	const schoolYearId = ref('');//学年学期id
	const targetType = ref('');//采集对象 1-按部门，2-按学科，3-按年级，4-按权限，5-按学生
	const pageType = ref('');//添加或修改
	const treeRef = ref('');
	onLoad((option) => {
		schoolYearId.value = option.schoolYearId;
		targetType.value = Number(option.targetType);
		pageType.value = option.type;
		const taskTargetsTreeData = uni.getStorageSync('taskTargetsTreeData');
		const taskTargets = taskTargetsTreeData?.taskTargets || [];
		state.checkedValue = taskTargets;
		state.defaultCheckedKeys = taskTargets?.map(item=>item.id) || [];
		state.checkedDisabled = taskTargets.filter(item=>item.disabled && item.checked=='checked');
		if(pageType.value == 'add'){
			GetDepartContainUser();
			GetCollectPersonalInfo();
		}else{//编辑
			state.tabBtns = state.tabBtns.filter(item=>item.value == targetType.value);
			state.treeData = taskTargetsTreeData?.taskTargetsTree || [];
		}
	})
	//查询本学校下的当前学年的所有部门及部门下的人
	const GetDepartContainUser = () => {
		findDepartContainUser(schoolYearId.value).then(res=>{
			if(res.code == 200){
				const resData = res.data || [];
				state.deptTreeData = getDeptTreeData(resData);
				CurrentTreeData();
			}
		})
	}
	//查询本学校下的当前学年的所有学科、年级、权限数据及下的人
	const GetCollectPersonalInfo = async () => {
		const res = await findCollectPersonalInfo(schoolYearId.value);
		const { collectGradePersonVos, collectPermissionPersonVos, subjectPersonVoList } = res.data;
		state.gradeTreeList = gradTreeData(collectGradePersonVos);
		state.permissionTreeList = permTreeData(collectPermissionPersonVos);
		state.subjectTreeList = subjectTreeData(subjectPersonVoList);
		CurrentTreeData();
	}
	const CommonFilterData = (filterOptions,type) => {
		if(type=='tabBtns' && pageType.value == 'add'){
			targetType.value = filterOptions.tabBtnSelected;
			CurrentTreeData();
		}
	}
	const CurrentTreeData = () => {
		// 1-按部门，2-按学科，3-按年级，4-按权限，5-按学生
		if(targetType.value == 1){
			state.treeData = [...state.deptTreeData];
		}else if(targetType.value == 2){
			state.treeData = [...state.subjectTreeList];
		}else if(targetType.value == 3){
			state.treeData = state.gradeTreeList;
		}else if(targetType.value == 4){
			state.treeData = state.permissionTreeList;
		}else{
			state.treeData = [];
		}
	}
	//选择的值
	const HandleCheckChange = ({keys,node,nodes,value}) => {
		// 不可取消的节点 key 列表
		const lockedKeys = state.checkedDisabled.map(el=>el.id)
		const merged = [...new Set([...keys, ...lockedKeys])];//去重
		state.defaultCheckedKeys = merged;
		const nodesList = nodes.filter(item => item.isLeaf).map(el => ({ ...el.source }));
		//去重
		state.checkedValue = [...new Map([...nodesList, ...state.checkedDisabled].map(item => [item.id, item])).values()];
	}
	//保存选择值
	const SaveCheckedTreeData = () => {
		if(state.checkedValue.length == 0){
			uni.showToast({
				title: '请选择采集对象！',
				icon: 'none'
			})
			return false
		}
		uni.setStorageSync('taskTargetsTreeData',{
			targetType:targetType.value,
			taskTargets:state.checkedValue//采集对象
		});//返回上一页并传值
		GoBack()
	}
	//返回
	const GoBack = () => {
		uni.navigateBack({
			delta: 1
		});
	}
</script>

<style scoped lang="scss">
	:deep(.item_width){
		.scroll_tab_btn{
			.tab_item{
				width: 122rpx;
				flex: 0;
			}	
		}
	}
	:deep(.scroll_tab_btn){
		margin-top: 24rpx;
		.tab_item{
			&.selected{
				background-color: #2E64FA;
				color: #FFFFFF;
			}
		}
	}
	.page_body{
		display: flex;
		flex-direction: column;
		height: 100%;
		min-width: auto;
		.row_search_box{
			height: 96rpx;
			align-items: flex-start;
		}
		.tree_node{
			display: flex;
			width: 100%;
			padding: 0 24rpx;
			box-sizing: border-box;
			flex:1;
			overflow: auto;
			:deep(.utv-tree-item__arrow-icon){
				display: none;
			}
		}
		.foot_btn{
			width: 100%;
			padding: 40rpx 24rpx;
			flex-shrink: 0;
			box-sizing: border-box;
			.btn_submit{
				background-color: #2E64FA;
				border-radius: 8rpx;
				width: 100%;
				height: 90rpx;
				font-weight: 500;
				font-size: 28rpx;
				color: #FFFFFF;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
	}
</style>