<template>
	<fs-page>
		<fs-crud ref="crudRef" v-bind="crudBinding">
			<template #form_organization_ref="scope">
				<template v-if="scope.form.user_type === 0">
					<div style="display:flex; gap:8px; width:100%">
						<el-select
							style="flex:1"
							:disabled="scope.mode=='view'"
							v-model="scope.form._college_id"
							placeholder="请选择学院"
							filterable
							clearable
							@change="() => onCollegeChange(scope)"
						>
							<el-option v-for="item in colleges" :key="item.id" :label="item.name" :value="item.id" />
						</el-select>
					</div>
				</template>

				<template v-else-if="scope.form.user_type === 1 || scope.form.user_type === 3">
					<el-select
						:disabled="scope.mode=='view'"
						v-model="scope.form.organization_ref"
						placeholder="请选择学院"
						filterable
						clearable
					>
						<el-option
							v-for="item in colleges"
							:key="item.id"
							:label="item.name"
							:value="item.id"
						/>
					</el-select>
				</template>
				<template v-else>
					<el-select
						:disabled="scope.mode=='view'"
						v-model="scope.form.organization_ref"
						placeholder="请选择学院"
						filterable
						clearable
					>
						<el-option
							v-for="item in colleges"
							:key="item.id"
							:label="item.name"
							:value="item.id"
						/>
					</el-select>
				</template>
			</template>
			<template #form_sub_organization="scope" >
				<el-select
					style="flex:1"
					:disabled="scope.mode=='view' || !scope.form._college_id"
					v-model="scope.form._major_id"
					placeholder="请选择专业"
					filterable
					clearable
					@change="() => onMajorChange(scope)"
				>
					<el-option v-for="item in getMajors(scope.form._college_id)" :key="item.id" :label="item.name" :value="item.id" />
				</el-select>
			</template>
			<template #form_grade_or_level="scope">
				<el-select
					style="flex:1"
					:disabled="scope.mode=='view' || !scope.form._major_id"
					v-model="scope.form._grade_id"
					placeholder="请选择班级"
					filterable
					clearable
					@change="() => onGradeChange(scope)"
				>
					<el-option v-for="item in getGrades(scope.form._major_id)" :key="item.id" :label="item.name" :value="item.id" />
				</el-select>
			</template>
		</fs-crud>
	</fs-page>
</template>

<script lang="ts" setup name="studentInfo">
import { useFs } from '@fast-crud/fast-crud';
import { onMounted, ref, computed } from 'vue';
import { GetPermission, GetTree } from './api';
import { createCrudOptions } from './crud';
import { handleColumnPermission } from '/@/utils/columnPermission';

const { crudBinding, crudRef, crudExpose, crudOptions, resetCrudOptions } = useFs({ createCrudOptions });

const options = ref<any[]>([])
const colleges = computed(() => {
  const list = Array.isArray(options.value) ? options.value : []
  const firstLevel: any[] = []
  list.forEach((node: any) => {
    if (Array.isArray(node?.children)) firstLevel.push(...node.children)
  })
  return firstLevel.map((node: any) => ({ id: node.id, name: node.name }))
})
const props1 = {
  checkStrictly: true,
  label: 'name',
  value: 'id',
  children: 'children',
  emitPath: false // 只返回选中节点的值，不返回完整路径
}

function findNodeById(id: any) {
  if (!id) return undefined
  const stack: any[] = [...(options.value || [])]
  while (stack.length) {
    const node = stack.shift()
    if (node?.id === id) return node
    if (Array.isArray(node?.children) && node.children.length) stack.push(...node.children)
  }
  return undefined
}

function getMajors(collegeId: any) {
  const college = findNodeById(collegeId)
  return Array.isArray(college?.children) ? college.children : []
}

function getGrades(majorId: any) {
  const major = findNodeById(majorId)
  return Array.isArray(major?.children) ? major.children : []
}

function onCollegeChange(scope: any) {
  scope.form._major_id = undefined
  scope.form._grade_id = undefined
  if (scope.form.user_type === 0) {
    scope.form.organization_ref = undefined
  } else {
    scope.form.organization_ref = scope.form._college_id
  }
}

function onMajorChange(scope: any) {
  scope.form._grade_id = undefined
  if (scope.form.user_type === 0) {
    scope.form.organization_ref = undefined
  }
}

function onGradeChange(scope: any) {
  if (scope.form.user_type === 0) {
    scope.form.organization_ref = scope.form._grade_id
  }
}

const init=()=>{
	GetTree().then((res:any) => { 
			console.log('组织架构API响应:', res);
		// 兼容多种响应格式
		if(res && (res.code === 200 || res.code === 2000 || !res.code)){
			// 尝试多种数据结构
			const data = res.data || res.results || res;
			if (Array.isArray(data)) {
				options.value = data;
				console.log('成功赋值组织架构数据:', options.value);
			} else {
				console.warn('返回的数据不是数组格式:', data);
				options.value = [];
			}
		} else {
			console.error('获取组织架构数据失败:', res);
			options.value = [];
		}
	}).catch((error: any) => {
		console.error('请求组织架构数据失败:', error);
		options.value = [];
	});
}

// 页面打开后获取列表数据
onMounted(async () => {
	init()
	// 设置列权限
	const newOptions = await handleColumnPermission(GetPermission, crudOptions);
	//重置crudBinding
	resetCrudOptions(newOptions);
	// 刷新
	crudExpose.doRefresh();
});

defineExpose({
  getMajors,
  getGrades,
  onCollegeChange,
  onMajorChange,
  onGradeChange,
  colleges,
})
</script>
