<template>
	<fs-page>
		<fs-crud ref="crudRef" v-bind="crudBinding">
			<template #form_organization_ref="scope">
				<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>
		</fs-crud>
	</fs-page>
</template>

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

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 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();
});
</script>
