import { AddReq, CreateCrudOptionsProps, CreateCrudOptionsRet, dict, UserPageQuery, compute, InfoReq, EditReq, DelReq } from '@fast-crud/fast-crud';
import * as api from './api';
import { auth } from '/@/utils/authFunction';

// 全局变量存储组织树数据，供 valueBuilder 使用
let organizationTreeData: any[] = [];

// 初始化时获取组织树数据
const initOrganizationTree = async () => {
	try {
		const res = await api.GetTree();
		if (res && (res.code === 200 || res.code === 2000 || !res.code)) {
			const data = res.data || res.results || res;
			if (Array.isArray(data)) {
				organizationTreeData = data;
			}
		}
	} catch (error) {
		console.error('获取组织架构数据失败:', error);
		organizationTreeData = [];
	}
};

// 通过名称在组织树中查找节点的辅助函数（在整个树中递归搜索）
function findNodeByName(name: string, tree: any[], depth: number = 0, maxDepth: number = 10): any {
	if (!name || !tree || depth > maxDepth) return undefined;
	
	for (const node of tree) {
		if (node.name === name) {
			return node;
		}
		if (Array.isArray(node.children)) {
			const found = findNodeByName(name, node.children, depth + 1, maxDepth);
			if (found) return found;
		}
	}
	return undefined;
}

// 在学院层级中查找节点（跳过学校层）
function findNodeInColleges(name: string, tree: any[]): any {
	if (!name || !tree) return undefined;
	
	// 遍历所有学校
	for (const school of tree) {
		if (Array.isArray(school.children)) {
			// 在每个学校的子节点（学院）中查找
			for (const college of school.children) {
				if (college.name === name) {
					return college;
				}
			}
		}
	}
	return undefined;
}

export const createCrudOptions = function ({ crudExpose }: CreateCrudOptionsProps): CreateCrudOptionsRet {
	// 初始化组织树数据（异步执行，不阻塞返回）
	initOrganizationTree();
	const pageRequest = async (query: UserPageQuery) => {
		return await api.GetList(query);
	
	};

		const getDetail = async ({ row }: InfoReq) => {
		return await api.GetObj(row.id);
	};

	const editRequest = async ({ form, row }: EditReq) => {
		form.id = row.id;
		return await api.UpdateObj(form);
	};
	const delRequest = async ({ row }: DelReq) => {
		return await api.DelObj(row.id);
	};
	const addRequest = async ({ form }: AddReq) => {
		return await api.AddObj(form);
	};


	return {
		crudOptions: {
			request: {
				pageRequest,
				editRequest,
				delRequest,
				addRequest,
				getDetail,
			},
			toolbar:{
				show:false,
			},
			form:{
				wrapper: {
					buttons: {
						ok:{
							text:'提交',
							show:compute((row) => {
								return row.mode !=='view'
							})
						}
					}
				}
			},
			actionbar: {
				buttons: {
					add: {
						show: false,// auth('area:Create'),
					},
				},
			},
			pagination: {
				show: true,
			},		
			columns: {
				_index: {
					title: '序号',
					form: { show: false },
					column: {
						type: 'index',
						align: 'center',
						width: '70px',
						columnSetDisabled: true, //禁止在列设置中选择
					},
				},
				search:{
					title: '关键字搜索',
					search: { show: true,type: 'input', },
					type: 'input',
					form: {
						component: { placeholder: '请输入' },
						show:false},
					column: {show:false}
				},
				user_code:{
					title:'工号',
					type:'input',
					column: {
						minWidth: 120,
					},
					form: {
						component: { placeholder: '请填写工号' },
						rules: [{ required: true, message: '请填写工号' }],
					},
				},
				username:{
					title:'用户名',
					type:'input',
					column: {
						show: false,
						minWidth: 120,
					},
					form: {
						component: { placeholder: '请填写用户名' },
						rules: [{ required: true, message: '请填写用户名' }],
					},
					viewForm:{
						component: { placeholder: '' },
					}
				},
				name: {
					title: '姓名',
					search: {
						show: true,
					},
					treeNode: true,
					type: 'input',
					column: {
						minWidth: 120,
					},
					form: {
						rules: [
							// 表单校验规则
							{ required: true, message: '姓名必填项' },
						],
						component: {
							placeholder: '请输入姓名',
						},
					},
				},
				password:{
					title: '密码',
					type: 'password',
					column: {
						minWidth: 120,
						show: false,
					},
					form: {
						component: { placeholder: '请填写密码' },
						/* rules: [
							{ required: true, message: '请填写密码' },
							
						], */
						
					},
					addForm:{ 
						component:{placeholder: '请填写密码'} ,
						rules: [{ required: true, message: '请填写密码' },
							{
								validator: (rule: any, value: string, callback: Function) => {
									if (!value) {
										callback();
										return;
									}
									// 检查密码长度不少于8位
									if (value.length < 8) {
										callback(new Error('密码长度不能少于8位'));
										return;
									}
									// 检查是否包含字母
									const hasLetter = /[a-zA-Z]/.test(value);
									// 检查是否包含数字
									const hasNumber = /[0-9]/.test(value);
									// 检查是否包含特殊符号
									const hasSpecial = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?`~]/.test(value);
									
									if (!hasLetter || !hasNumber || !hasSpecial) {
										callback(new Error('密码必须包含字母、数字和特殊符号'));
										return;
									}
									callback();
								},
								trigger: 'blur'
							}
						],}, 
					editForm:{
						show:true,
						component: {
							placeholder: '留空则不修改密码',
							type: 'password',
							showPassword: true
						},
						rules: [
							{
								validator: (rule: any, value: string, callback: Function) => {
									// 如果密码为空，则通过验证（非必填）
									if (!value || value.trim() === '') {
										callback();
										return;
									}
									
									// 如果填写了密码，则进行格式校验
									const minLength = 8;
									const hasLetter = /[a-zA-Z]/.test(value);
									const hasNumber = /\d/.test(value);
									const hasSpecialChar = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(value);
									
									if (value.length < minLength) {
										callback(new Error('密码长度不能少于8位'));
										return;
									}
									
									if (!hasLetter) {
										callback(new Error('密码必须包含字母'));
										return;
									}
									
									if (!hasNumber) {
										callback(new Error('密码必须包含数字'));
										return;
									}
									
									if (!hasSpecialChar) {
										callback(new Error('密码必须包含特殊符号'));
										return;
									}
									
									callback();
								},
								trigger: 'blur'
							}
						]
					},
					viewForm:{
						show:false,
					}
				},
				email:{
					title: '邮箱',
					type: 'input',
					column: {
						show: false,
						minWidth: 120,
					},
					form: {
						component: { placeholder: '请填写邮箱' },
						rules: [{ required: false, message: '请填写邮箱' }],
					},
					viewForm:{
						component: { placeholder: '' },
					},
					valueBuilder({ form, value }) {
						// 在打开编辑/查看表单时，将 "nan" 转换为空字符串
						const isValidValue = (val: any) => {
							return val !== null && val !== undefined && val !== '' && val !== 'nan' && !Number.isNaN(val);
						};
						form.email = isValidValue(value) ? value : '';
					},
					valueResolve({ form, value }) {
						// 提交时，如果为空字符串，可以保持为空或转换为 null
						form.email = value === '' ? null : value;
					}
				},
				mobile:{
					title: '手机号',
					type: 'input',
					column: {
						show: false,
						minWidth: 120,
					},
					form: {
						component: { placeholder: '请填写手机号' },
						rules: [{ required: true, message: '请填写手机号' }],
					},
					viewForm:{
						component: { placeholder: '' },
					},
					valueBuilder({ form, value }) {
						// 在打开编辑/查看表单时，将 "nan" 转换为空字符串
						const isValidValue = (val: any) => {
							return val !== null && val !== undefined && val !== '' && val !== 'nan' && !Number.isNaN(val);
						};
						form.mobile = isValidValue(value) ? value : '';
					},
					valueResolve({ form, value }) {
						// 提交时，如果为空字符串，可以保持为空或转换为 null
						form.mobile = value === '' ? null : value;
					}
				},
				gender:{
					title: '性别',
					type: 'dict-select',
					column: {
						show: true,
						minWidth: 120,
					},
					dict: dict({
						data: [
							{ label: '男', value: 1 },
							{ label: '女', value: 2 },
						],
					}),
					form: {
						component: { placeholder: '请选择性别' },
						rules: [{ required: true, message: '请选择性别' }],
					},
					viewForm:{
						component: { placeholder: '' },
					}
				},
				user_type:{
					title: '用户类型',
					type: 'dict-select',
					search: {
						show: true,
					},
					column: {
						minWidth: 120,
					},
					dict: dict({
						data: [
							/* { label: '学生', value: 0 }, */
							{ label: '教师', value: 1 },
							/* { label: '校外团体', value: 2 }, */
							{ label: '学院领导', value: 3 },
						],
					}),
					form: {
						value:1,
						component: { placeholder: '请选择用户类型' },
						rules: [{ required: false, message: '请选择用户类型' }],
					},
				},
			organization_ref:{
				title: '学院',
				type: "dict-cascader",
				column: {
					show: false,
				},
				// 教师和学院领导的级联选择
				valueBuilder({ form, value }) {
					// 保留后端原始值
					form.organization_ref = value;
					// 教师/学院领导：直接以当前组织ID为学院选择
					const od = (form as any).organization_detail;
					
					if (od && od.id) {
						// 有 organization_detail，直接使用其 id
						(form as any).organization_ref = od.id;
					} else if (!od && organizationTreeData.length > 0) {
						// organization_detail 为 null 时，根据 organization 文本名称查找并回显
						const orgName = (form as any).organization; // 学院名称
						
						if (orgName) {
							// 在学院层级中查找节点（跳过学校层）
							const collegeNode = findNodeInColleges(orgName, organizationTreeData);
							if (collegeNode && collegeNode.id) {
								(form as any).organization_ref = collegeNode.id;
							}
						}
					}
					
					// 如果组织树数据未加载，尝试加载（异步，不阻塞）
					if (organizationTreeData.length === 0) {
						initOrganizationTree();
					}
				},
				valueResolve({ form, value }) {
					// 教师/学院领导：提交学院ID
					(form as any).organization_ref = value ?? (form as any).organization_ref;
				}
			},
				organization:{
					title: '学院',
					type: 'input',
					search:{
						show:false
					},
					column: {
						show: true,
						minWidth: 200,
						formatter: ({ row, value }: { row: any; value: any }) => {
							// 检查值是否为无效值（包括 'nan' 字符串）
							const isValidValue = (val: any) => {
								return val !== null && val !== undefined && val !== '' && val !== 'nan' && !Number.isNaN(val);
							};
							// 教师、学院领导：显示学院名称
							if (row.organization_detail && row.organization_detail.name) {
								return row.organization_detail.name;
							}
							// 否则显示原始值
						return isValidValue(value) ? value : '';
						},
					},
					form: {
						show: compute((row:any)=>{
							// 教师、学院领导：在表单中显示"学院"
							return row.user_type === 1 || row.user_type === 3
						}),
						component: { placeholder: '请选择学院' },
						rules: [{ required: false, message: '请选择学院' }],
					},
					viewForm:{
						component: { placeholder: '' },
					}
				},
				sub_organization:{
					title: '专业',
					type: 'input',
					column: {
						show: false,
						minWidth: 120,
					},
					form: {
						show: false,
						component: { placeholder: '请填写专业' },
						rules: [{ required: false, message: '请填写专业' }],
					},
					viewForm:{
						component: { placeholder: '' },
					}
				},
				grade_or_level:{
					title: '年级',
					type: 'input',
					column: {
						show: false,
						minWidth: 120,
					},
					form: {
						show:false,
						component: { placeholder: '请填写年级' },
						rules: [{ required: false, message: '请填写年级' }],
					},
					viewForm:{
						component: { placeholder: '' },
					}
				},
				class_or_group:{
					title: '班级',
					type: 'input',
					column: {
						show: false,
						minWidth: 120,
					},
					form: {
						show: false,
						component: { placeholder: '请填写班级' },
						rules: [{ required: false, message: '请填写班级' }],
					},
					viewForm:{
						component: { placeholder: '' },
					}
				},



			},
		},
	};
};
