<template>
	<el-dialog v-model="visible" title="课堂借用申请单" width="80%" :close-on-click-modal="false" @close="onCancel">
		<div style="margin-bottom: 16px">
			<div style="font-weight: bold; font-size: 18px; margin-bottom: 8px">课程信息</div>
			<el-row :gutter="8" style="margin-bottom: 8px; align-items: center">
				<el-col :span="6">
					<el-select v-model="form.purpose" placeholder="请选择课程" @change="onCourseChange">
						<el-option
							v-for="course in weeklyCourses"
							:key="course.id"
							:label="`${course.classdetail} - ${course.teacher_name} - ${course.classroom} - ${course.time_label}`"
							:value="course.classdetail"
						/>
					</el-select>
				</el-col>
				
			</el-row>
			<div style="max-height: 400px; overflow-y: auto; border: 1px solid #eee; padding: 8px; margin-bottom:0px">
				<timetablemanage />
			</div>
		</div>
		<el-form :model="form" label-width="110px" label-position="top" :rules="rules" ref="formRef">
			<el-row :gutter="16">
				<el-col :span="8">
					<el-form-item label="借用单编号" prop="application_no">
						<el-input v-model="form.application_no" placeholder="自动生成" disabled />
					</el-form-item>
				</el-col>
				<el-col :span="8">
					
					<el-form-item label="借用人类型" prop="borrower_type">
						<el-select v-model="form.borrower_type" placeholder="请选择借用人角色" >
							<el-option label="管理员用户" :value=0 />
							<el-option label="应用用户" :value=1 />
							<el-option label="外部用户" :value=2 />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="8" >
					<el-form-item label="借用人" prop="admin_borrower" v-if="form.borrower_type == 0">
						<el-select 
							v-model="form.admin_borrower" 
							placeholder="请选择或搜索管理员" 
							filterable
							allow-create
							:filter-method="filterAdmins"
							:loading="adminSearchLoading"
							@create="createNewAdmin"
							@focus="onAdminSelectFocus"
							clearable
							style="width: 100%"
						>
							<el-option 
								v-for="item in filteredAdminList"  
								:key="item.id" 
								:label="item.name" 
								:value="item.id" 
							/>
						</el-select>
					</el-form-item>
					<el-form-item label="借用人" prop="app_user_borrower" v-if="form.borrower_type == 1">
						<el-select 
							v-model="form.app_user_borrower" 
							placeholder="请选择或搜索借用人" 
							filterable
							allow-create
							:filter-method="filterUsers"
							:loading="userSearchLoading"
							@create="createNewUser"
							@focus="onUserSelectFocus"
							clearable
							style="width: 100%"
						>
							<el-option 
								v-for="item in filteredUserList"  
								:key="item.id" 
								:label="item.name" 
								:value="item.id" 
							/>
						</el-select>
					</el-form-item>
					<el-form-item label="借用人" prop="external_borrower_name" v-if="form.borrower_type == 2">
						<el-input v-model="form.external_borrower_name" placeholder="请输入借用人"  />
					</el-form-item>
				</el-col>
				<el-col :span="8" v-if="form.borrower_type !== 2">
					<el-form-item label="学号/工号" prop="user_code">
						<el-input v-model="form.user_code" placeholder="请输入学号/工号"  @blur="onUserCodeBlur" />
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="联系电话" prop="mobile" v-if="form.borrower_type !== 2">
						<el-input v-model="form.mobile" placeholder="请输入联系电话"  />
					</el-form-item>
					<el-form-item label="联系电话" prop="mobile" v-if="form.borrower_type == 2">
						<el-input v-model="form.external_borrower_phone" placeholder="请输入联系电话"  />
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="借用部门" prop="borrower_dept">
						<el-input v-model="form.borrower_dept" placeholder="请输入借用部门"  />
					</el-form-item>
				</el-col>
				<el-col :span="4">
					<el-form-item label="团队人数" prop="team_members_count">
						<el-input v-model="form.team_members_count" placeholder="请输入" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="团队其他人员名单" prop="team_members">
						<el-input v-model="form.team_members" placeholder="请输入团队其他人员名单" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="备注" prop="applicant_remark">
						<el-input v-model="form.applicant_remark" placeholder="请输入备注" />
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="预计归还时间" prop="expected_end_time">
						<el-date-picker v-model="form.expected_end_time" type="date" 
                                format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD"
                                :disabledDate="disabledDate" placeholder="请选择预计归还时间" style="width: 100%" />
					</el-form-item>
				</el-col>
			</el-row>
			<div style="margin: 16px 0 8px 0; font-weight: bold">借用列表</div>
			<el-table :data="form.items" border style="width: 50%; margin-bottom: 12px">
				<el-table-column type="index" label="序号" width="60" />
				<el-table-column prop="remark" label="设备分类" />
				<el-table-column label="借用数量">
				<template #default="{ row }">
				<el-input v-model="row.quantity" type="number" :min="1" prop="quantity" size="small" />
				</template>
				</el-table-column>
			<!-- 	<el-table-column prop="location" label="存放仓库" /> -->
				<el-table-column label="操作" width="80">
					<template #default="{ row, $index }">
						<el-button type="text" style="color: red" @click="removeItem($index)">移除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-button type="primary" @click="addItem">添加设备分类</el-button>

			<div style="margin: 16px 0 8px 0; font-weight: bold">预借配件信息</div>
			<el-input v-model="form.accessories" placeholder="请输入预借配件信息"  :disabled="isView"/>


			<!-- <div style="margin: 16px 0 8px 0; font-weight: bold">附件</div>
			<el-upload
			drag
			list-type="picture"
			:show-file-list="true"
			:http-request="handleCustomUpload"
			>
			<i class="el-icon-upload"></i>
			<div class="el-upload__text">将文件拖到此处，或 <em>点击上传</em></div>
			</el-upload> -->
			<div style="margin: 16px 0 8px 0; font-weight: bold">附件</div>
			<div>
				<el-upload
				list-type="picture-card"
				:show-file-list="true"
				:http-request="handleCustomUpload"
				:file-list="fileList"
				:on-preview="handlePictureCardPreview"
				style="margin-top: 10px;"
				>
				<el-icon><Plus /></el-icon>
				</el-upload>
		    </div>


		</el-form>


		<template #footer>
			<el-button @click="onCancel">关闭</el-button>
			<el-button v-if="!isViewMode" type="primary" @click="onSave">提交</el-button>
		</template>
		<!-- <SelectDeviceDialog v-model:visible="showSelectDeviceDialog" @confirm="onDeviceSelected" /> -->
		<SelectCatgory
			v-model:visible="showSelectDeviceDialog"
			:disabled-ids="selectedDeviceCategoryIds"
			@confirm="onDeviceSelected"
		/>
	</el-dialog>
	 <el-dialog v-model="dialogVisible">
		<img w-full :src="dialogImageUrl" alt="Preview Image" />
	</el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, defineProps, defineEmits, onMounted, computed,inject,Ref, } from 'vue';
import SelectDeviceDialog from '../SpecialBorrow/SelectDeviceDialog/index.vue';
import SelectCatgory from '../SelectCatgory/index.vue';
import timetablemanage from '../../../timetablemanage/index.vue';
import * as apis from '../../../timetablemanage/api';
import * as api from '../../api';
import { provide } from 'vue';
import dayjs from 'dayjs';
import { ElMessage,UploadProps, UploadUserFile } from 'element-plus';
import { cloneDeep } from 'lodash-es';
import Cookies from 'js-cookie';
import { request } from '/@/utils/service';
import { Plus } from '@element-plus/icons-vue';
import { getUserInfo } from '../../../login/api';

// 定义用户和管理员接口
interface User {
  id: number | string;
  name: string;
  user_code?: string;
  mobile?: string;
  isNew?: boolean;
}

interface Admin {
  id: number | string;
  name: string;
  isNew?: boolean;
}

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
// 禁止选择今天之前的日期
const disabledDate = (time: Date) => {
  // 获取今天的开始时间（准确到日）
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  // 返回true表示禁用，禁用今天之前的所有日期
  return time.getTime() < today.getTime()
}
/* 获取管理员列表 */
const adminList = ref<Admin[]>([]);
const filteredAdminList = ref<Admin[]>([]);
const adminSearchLoading = ref(false);
const adminSearchQuery = ref('');

async function getAdminList() {
	adminSearchLoading.value = true;
	try {
		const res = await getUserInfo();
		adminList.value = res.data;
		filteredAdminList.value = res.data;
		console.log("adminList.value:::",adminList.value)	
	} finally {
		adminSearchLoading.value = false;
	}
}

// 管理员搜索过滤方法
function filterAdmins(query: string) {
	adminSearchQuery.value = query;
	if (!query) {
		filteredAdminList.value = adminList.value;
		return;
	}
	
	// 根据姓名进行模糊搜索
	filteredAdminList.value = adminList.value.filter(admin => 
		admin.name.toLowerCase().includes(query.toLowerCase())
	);
}

// 创建新管理员
function createNewAdmin(query: string) {
	// 检查是否已存在相同姓名的管理员
	const existingAdmin = adminList.value.find(admin => 
		admin.name.toLowerCase() === query.toLowerCase()
	);
	
	if (existingAdmin) {
		ElMessage.warning('该管理员已存在，请选择现有管理员');
		form.value.admin_borrower = Number(existingAdmin.id);
		return;
	}
	
	// 创建新管理员对象
	const newAdmin: Admin = {
		id: `new_admin_${Date.now()}`, // 临时ID
		name: query,
		isNew: true // 标记为新创建的管理员
	};
	
	// 添加到管理员列表
	adminList.value.unshift(newAdmin);
	filteredAdminList.value = adminList.value;
	form.value.admin_borrower = Number(newAdmin.id);
	
	ElMessage.success(`已创建新管理员: ${query}`);
}

// 管理员选择框获得焦点时的处理
function onAdminSelectFocus() {
	if (!adminSearchQuery.value) {
		filteredAdminList.value = adminList.value;
	}
}
/*  */
/* 获取所有用户 */
const allUserList = ref<User[]>([]);
const filteredUserList = ref<User[]>([]);
const userSearchLoading = ref(false);
const userSearchQuery = ref('');
let allUserLoaded = false;

async function getAllUserList() {
	if (allUserLoaded || userSearchLoading.value) return;
	userSearchLoading.value = true;
	try {
		const pageSize = 100;
		let page = 1;
		const users: User[] = [];
		while (true) {
			const res: any = await api.GetAllUser({ page, limit: pageSize });
			const list: User[] = Array.isArray(res?.data) ? res.data : [];
			users.push(...list);
			if (list.length < pageSize) break;
			page += 1;
		}
		allUserList.value = users;
		filteredUserList.value = users;
		// 默认选择：仅在当前未选择时赋值，并同步学号/电话用于回显
		if (!form.value.app_user_borrower && allUserList.value.length > 0) {
			/* const first = allUserList.value[0] as any;
			form.value.app_user_borrower = Number(first.id);
			form.value.user_code = first.user_code || '';
			form.value.mobile = first.mobile || ''; */
		}
		// 控制台调试
		console.log("allUserList.value:::", allUserList.value);
		allUserLoaded = true;
	} finally {
		userSearchLoading.value = false;
	}
}

// 用户搜索过滤方法
function filterUsers(query: string) {
	userSearchQuery.value = query;
	if (!query) {
		filteredUserList.value = allUserList.value;
		return;
	}
	
	// 根据姓名进行模糊搜索
	filteredUserList.value = allUserList.value.filter(user => 
		user.name.toLowerCase().includes(query.toLowerCase()) ||
		(user.user_code && user.user_code.toLowerCase().includes(query.toLowerCase()))
	);
}

// 创建新用户
function createNewUser(query: string) {
	// 检查是否已存在相同姓名的用户
	const existingUser = allUserList.value.find(user => 
		user.name.toLowerCase() === query.toLowerCase()
	);
	
	if (existingUser) {
		ElMessage.warning('该用户已存在，请选择现有用户');
		form.value.app_user_borrower = Number(existingUser.id);
		return;
	}
	
	// 创建新用户对象
	const newUser: User = {
		id: `new_${Date.now()}`, // 临时ID，实际应该调用API创建
		name: query,
		user_code: '',
		mobile: '',
		isNew: true // 标记为新创建的用户
	};
	
	// 添加到用户列表
	allUserList.value.unshift(newUser);
	filteredUserList.value = allUserList.value;
	form.value.app_user_borrower = Number(newUser.id);
	
	ElMessage.success(`已创建新用户: ${query}`);
}

// 用户选择框获得焦点时的处理
function onUserSelectFocus() {
	if (!userSearchQuery.value) {
		filteredUserList.value = allUserList.value;
	}
}
const fileList = ref([]);

// const fileList = ref([]);
const handleCustomUpload = async ({ file, onProgress, onSuccess, onError }: any) => {
  const token = Cookies.get('token'); 
  const formData = new FormData();
  formData.append('file', file);
  console.log("token::::",token);

  try {
    const res = await request({
		url: `/api/system/upload/`,
		method: 'post',
		headers: {
			'Content-Type': 'multipart/form-data',
			Authorization: 'JWT '+ token,
		},
		data: formData,
		timeout: 60000,
		onUploadProgress: (p: any) => {
                            onProgress({percent: Math.round((p.loaded / p.total) * 100)});
		}
    });

	// 构造 Element Plus 需要的 file 对象
	const fileObj = {
      name: res.data.name,
      url: res.data.url,
      status: 'success',
      response: res.data
    };

    // 添加到附件列表
	form.value.attachments = fileObj.url; 

    ElMessage.success('上传成功');
    onSuccess(fileObj); 
  } catch (error) {
    ElMessage.error('上传失败');
    onError(error);
  }
};


provide('isEmbedded', true);
provide('onCourseSelected', handleCourseSelected);

const props = defineProps<{ visible: boolean; modelValue?: any ; lastFormSnapshot: Record<string, any>;}>();
const emit = defineEmits(['update:visible', 'update:modelValue', 'submit','update:lastFormSnapshot']);
const visible = ref(props.visible);
const formRef = ref();

const isEdit = computed(() => props.modelValue?.mode === 'edit');
const isView = computed(() => props.modelValue?.mode === 'view');
const isAdd = computed(() => props.modelValue?.mode === 'add');



function handleCourseSelected({ course_id, course_Name, expected_start_time }: any) {
	// eslint-disable-next-line no-console
  console.log("kebiao=form.value.expected_start_time:::",form.value.expected_start_time)
  form.value.purpose = course_Name;
  form.value.expected_start_time = expected_start_time;
}


const weeklyCourses = ref<any[]>([]);

async function fetchWeeklySchedule() {
  const res = await apis.GetCurrentWeekList();
  	// eslint-disable-next-line no-console
	// console.log("res.data:::",res.data)
  const schedule = res.data.schedule;

  const courseMap = new Map<string, any>();

  for (const dayKey in schedule) {
    const daySchedule = schedule[dayKey];
    for (const timeKey in daySchedule) {
      const courses = daySchedule[timeKey];
      for (const course of courses) {
        if (!courseMap.has(course.classdetail)) {
          courseMap.set(course.classdetail, course);
        }
      }
    }
  }

  weeklyCourses.value = Array.from(courseMap.values());
}

function onCourseChange(selectedName: string) {
  const selectedCourse = weeklyCourses.value.find(c => c.classdetail === selectedName);
  if (selectedCourse) {
    form.value.expected_start_time = `${selectedCourse.class_date} ${getStartTime(selectedCourse.time)}`;
    form.value.teacher_name = selectedCourse.teacher_name;
    form.value.classroom = selectedCourse.classroom;
  }
  console.log("form.value.expected_start_time ::",form.value.expected_start_time );
}

function getStartTime(time: number): string {
  const timeMap: { [key: number]: string } = {
    1: '09:00:00',
    2: '14:00:00',
    3: '19:00:00'
  };
  return timeMap[time] || '09:00:00';
}




const form = ref({
	application_no: '',
	borrower_type:1,
	external_borrower_name:"",
	external_borrower_phone:"",
	purpose:'',
	emergency_contact: '111',
	emergency_phone: '1111',
	app_user_borrower: null as number | null,
	admin_borrower: 1,
	borrower_dept: '',
	team_type: 1,
	team_members_count: 2,
	team_members: '',
	expected_start_time:'',
    expected_end_time: "",
	applicant_remark: '',
	return_location:'',
	items: [] as any[],
	borrow_type:1,
	course_input: '',
	attachments:'',
	accessories:'',
	user_code: '',
	mobile: '',
	teacher_name: '',
	classroom: ''
});
const showSelectDeviceDialog = ref(false);
/** 详情回填后的应用用户借用人 id；编辑态下仅在与该 id 一致时不从用户列表覆盖 borrower_dept（列表侧组织字段可能不准） */
const lastHydratedAppUserBorrowerId = ref<number | null>(null);

function normalizeAppUserBorrowerId(raw: any): number | null {
	if (raw == null || raw === '') return null;
	if (typeof raw === 'object' && raw.id != null && raw.id !== '') {
		const n = Number(raw.id);
		return Number.isFinite(n) ? n : null;
	}
	const n = Number(raw);
	return Number.isFinite(n) ? n : null;
}

/** 与用户列表项、详情 borrower_info 等结构对齐，从组织字段推导展示用借用部门 */
function computeBorrowerDeptFromUserLike(selectedUser: any): string {
	if (!selectedUser || typeof selectedUser !== 'object') return '';
	let deptName = '';
	const orgDetail: any = selectedUser.organization_detail || {};
	const parentChain: any[] = Array.isArray(orgDetail.parent_chain) ? orgDetail.parent_chain : [];
	const isValid = (val: any) => {
		const s = String(val).trim();
		return val !== null && val !== undefined && s !== '' && s.toLowerCase() !== 'nan' && !Number.isNaN(val);
	};
	if (selectedUser.user_type === 0) {
		const chainNames: string[] = parentChain
			.filter((n: any) => Number(n?.type) !== 1)
			.map((n: any) => n?.name)
			.filter((n: any) => isValid(n));
		const college = chainNames[1] || '';
		const major = chainNames[2] || selectedUser.sub_organization || '';
		const clazz = orgDetail.name || selectedUser.class_or_group || '';
		const parts = [college, major, clazz].filter((p) => isValid(p));
		deptName = parts.join('/');
		if (!deptName) {
			const full = selectedUser.full_organization_name || '';
			deptName = full.replace(/^学校\s*\/\s*/, '');
			deptName = deptName
				.split('/')
				.map((s: string) => s.trim())
				.filter((s: string) => isValid(s))
				.join('/');
		}
		deptName = deptName
			.split('/')
			.map((s: string) => s.trim())
			.filter((s: string) => isValid(s))
			.join('/');
	} else if (selectedUser.user_type === 1 || selectedUser.user_type === 3) {
		deptName = orgDetail?.name || selectedUser.organization || selectedUser.full_organization_name || '';
	} else {
		deptName = selectedUser.full_organization_name || '';
	}
	return isValid(deptName) ? deptName : '';
}

/** 详情接口有时不落 borrower_dept 字段，仅从 borrower_info 带组织；不能用当前登录人部门回填否则会误显「Admin团队」等 */
function applyBorrowerDeptFromDetailPayload(data: any) {
	const f: any = form.value;
	const root = data?.borrower_dept;
	if (root != null && String(root).trim() !== '') {
		f.borrower_dept = String(root).trim();
		return;
	}
	const bi = data?.borrower_info;
	if (!bi || typeof bi !== 'object') return;
	const nestedDept = bi.dept_info?.dept_name;
	if (nestedDept != null && String(nestedDept).trim() !== '') {
		f.borrower_dept = String(nestedDept).trim();
		return;
	}
	const fromProfile = computeBorrowerDeptFromUserLike(bi);
	if (fromProfile) f.borrower_dept = fromProfile;
}

/** 将详情中的借用人统一为 el-select 可用的数字 id，并同步 lastHydratedAppUserBorrowerId */
function normalizeBorrowerFieldsAfterDetailAssign(data: any) {
	const f: any = form.value;
	let bid = normalizeAppUserBorrowerId(f.app_user_borrower);
	if (bid == null && data?.borrower_info?.id != null) {
		f.app_user_borrower = Number(data.borrower_info.id);
		bid = normalizeAppUserBorrowerId(f.app_user_borrower);
	} else if (bid != null) {
		f.app_user_borrower = bid;
	}
	lastHydratedAppUserBorrowerId.value = normalizeAppUserBorrowerId(f.app_user_borrower);
	applyBorrowerDeptFromDetailPayload(data);
}

/** 已在借用列表中的设备分类 id，选择弹窗中不可重复勾选 */
const selectedDeviceCategoryIds = computed(() =>
	(form.value.items || [])
		.map((it: any) => it.device_category ?? it.device)
		.filter((id: any) => id !== null && id !== undefined && id !== '')
);
const isViewMode = computed(() => props.modelValue?.mode === 'view');


const rules = {
	external_borrower_name: [
    { required: true, message: '请输入借用人', trigger: 'change' },
  ],
  app_user_borrower: [
    { required: true, message: '请选择借用人', trigger: 'change' },
  ],
  external_borrower_phone: [
    { required: true, message: '请输入联系电话', trigger: 'change' },
  ],
  team_members_count: [
	{ required: true, message: '请输入团队人数', trigger: 'change' },
	{
		validator: (_rule: any, value: any, callback: any) => {
		if (value <= 1) {
			callback(new Error('团队人数必须大于 1'));
		} else {
			callback();
		}
		},
		trigger: 'change'
	}
	],
 /*  borrower_dept: [
    { required: true, message: '请输入借用部门', trigger: 'change' },
  ], */
  expected_end_time: [
    { required: true, message: '请输选择归还时间', trigger: 'change' },
  ],
  /* team_members:[
    { required: true, message: '请输入团队其他人员名单', trigger: 'change' },
  ], */
  team_type: [
    { required: true, message: '请选择个人或者团队', trigger: 'change' },
  ],
  purpose: [
    { required: true, message: '请输入借用原因', trigger: 'change' },
  ],
  applicant_remark: [
    { required: false, message: '请输入备注', trigger: 'change' },
  ],
};

onMounted(() => {
	try {
		const userInfo = JSON.parse(sessionStorage.getItem('userInfo') || '{}');
		if (userInfo) {
			form.value.borrower_type = 1;
			form.value.external_borrower_name = userInfo.username || '';
			// app_user_borrower 初始化不选择，由用户手动选择
			form.value.external_borrower_phone = userInfo.mobile || '';
			// 不写入 borrower_dept：操作员（如管理员）的 dept_name 常为「Admin团队」，详情接口若未带 borrower_dept 会残留误显
		}
	} catch (e) {console.error(e)}
	fetchWeeklySchedule();
	getAdminList()
	getAllUserList()
});

// 监听借用人选择变化
watch(() => form.value.app_user_borrower, (newValue) => {
  // 查看态：借用部门、学号等一律以详情接口为准，避免用户列表组织信息不完整覆盖已保存值（如误显「admin团队」等）
  if (isView.value) return;
  const nid = normalizeAppUserBorrowerId(newValue);
  if (nid == null || !allUserList.value.length) return;
  const selectedUser = allUserList.value.find(user => Number(user.id) === nid);
  if (!selectedUser) return;

  form.value.user_code = selectedUser.user_code || '';
  form.value.mobile = selectedUser.mobile || '';

  // 编辑态且仍为详情刚回填的同一借用人：若已从详情得到非空部门则不再用列表覆盖（列表组织字段可能不准）
  const hasDeptFromDetail = String(form.value.borrower_dept || '').trim() !== '';
  const skipDeptFromUserList =
    isEdit.value && nid === lastHydratedAppUserBorrowerId.value && hasDeptFromDetail;
  if (skipDeptFromUserList) {
    if (selectedUser.isNew) {
      ElMessage.info('请为新用户填写学号/工号和联系电话');
    }
    return;
  }

  form.value.borrower_dept = computeBorrowerDeptFromUserLike(selectedUser);

  if (selectedUser.isNew) {
    ElMessage.info('请为新用户填写学号/工号和联系电话');
  }
});


function resetForm() {
  form.value = {
    application_no: '',
	borrower_type:1,
	external_borrower_name:"",
	external_borrower_phone:"",
    emergency_contact: '111',
    purpose: '',
    emergency_phone: '1111',
    app_user_borrower: null as number | null,
    admin_borrower: 1,
    borrower_dept: '',
    team_type: 1,
    team_members_count: 2,
    team_members: '',
    expected_start_time: '',
    expected_end_time: '',
    applicant_remark: '',
    return_location: '',
    items: [] as any[],
    borrow_type: 1,
    course_input: '',
	attachments:'',
	accessories:'',
	user_code: '',
	mobile: '',
	teacher_name: '',
	classroom: ''
  };
}

function onUserCodeBlur() {
  const userCode = String(form.value.user_code || '').trim();
  if (!userCode || userCode.length < 2) return;
  if (form.value.borrower_type === 2) return; // 外部用户不查
  if (isView.value) return; // 查看态不查
  queryUserByCode(userCode);
}

function hasDraftSnapshot(snap: Record<string, any> | undefined | null): boolean {
	return !!(snap && typeof snap === 'object' && Object.keys(snap).length > 0);
}

watch(() => props.visible, (v) => {
	visible.value = v;
	if (!v) return;
	lastHydratedAppUserBorrowerId.value = null;
	const mode = props.modelValue?.mode;
	// 编辑/查看：表单以详情接口为准，不合并 lastFormSnapshot，避免上次新增草稿或编辑数据混入
	if (mode === 'edit' || mode === 'view') {
		resetForm();
		return;
	}
	// 仅新增：有非空快照时恢复用户未提交前填写的内容（空对象 {} 不再误判为「有快照」）
	if (hasDraftSnapshot(props.lastFormSnapshot as Record<string, any>)) {
		Object.assign(form.value as any, props.lastFormSnapshot as any);
	} else {
		resetForm();
	}
}, { immediate: true });



watch(() => props.modelValue, async (val, oldVal) => {
	// 新增且无 id：不拉详情；若刚从带 id 的查看/编辑上下文切过来，清掉误注入的详情（父组件曾晚一帧更新 modelValue 时的兜底）
	if (val && typeof val === 'object' && val.mode === 'add' && !val.id) {
		lastHydratedAppUserBorrowerId.value = null;
		const ov: any = oldVal;
		const wasDetailContext = !!(
			ov &&
			typeof ov === 'object' &&
			(ov.id || ov.mode === 'view' || ov.mode === 'edit')
		);
		if (wasDetailContext) {
			if (hasDraftSnapshot(props.lastFormSnapshot as Record<string, any>)) {
				resetForm();
				Object.assign(form.value as any, props.lastFormSnapshot as any);
			} else {
				resetForm();
			}
		}
		return;
	}

	if (val && val.id && isView.value) {
		const expectId = val.id;
		const expectMode = val.mode;
		try {
			const res = await api.GetApplicationDetail(val.id);
			const mv: any = props.modelValue;
			if (!mv || mv.id !== expectId || mv.mode !== expectMode) return;
			if (res.code === 2000 && res.data) {
				Object.assign(form.value, res.data);
				normalizeBorrowerFieldsAfterDetailAssign(res.data);
			}
		} catch (e) {
			ElMessage.error('获取详细信息失败');
		}
	} else if (val && isEdit.value && val.id) {
		const expectId = val.id;
		const expectMode = val.mode;
		try {
			const res = await api.GetApplicationDetail(val.id);
			const mv: any = props.modelValue;
			if (!mv || mv.id !== expectId || mv.mode !== expectMode) return;
			if (res.code === 2000 && res.data) {
				Object.assign(form.value, res.data);
				normalizeBorrowerFieldsAfterDetailAssign(res.data);
			}
		} catch (e) {
			ElMessage.error('获取详细信息失败');
		}
	}
}, { immediate: true });

function addItem() {
	showSelectDeviceDialog.value = true;
}
function onDeviceSelected(devices: any[]) {
	if (!form.value.items) {
    form.value.items = [];
  }
	form.value.items.push(
		...devices.map((d: any) => ({
			device_category: d.id,
			device: d.id,
			remark: d.name,
			quantity: 1,
			location: d.warehouse,
		}))
	);
}
function removeItem(index: number) {
	form.value.items.splice(index, 1);
}
function onCancel() {
	emit('update:visible', false);
}

const now = dayjs().format('YYYY-MM-DD HH:mm:ss');
function onSave() {
	formRef.value.validate((valid: boolean) => {
		if (valid) {
			form.value.items = form.value.items.map((item: any) => ({
                ...item,
                quantity: Number(item.quantity) || 0  
            }));
			const firstLocation = form.value.items[0]?.location || '';
            form.value.return_location = firstLocation;
			form.value.expected_start_time = form.value.expected_start_time ? form.value.expected_start_time : now;
			form.value.expected_end_time = form.value.expected_end_time
				? dayjs(form.value.expected_end_time).endOf('day').format('YYYY-MM-DD HH:mm:ss')
				: dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss');;
			form.value.team_members_count=Number(form.value.team_members_count)||2;
			form.value.borrow_type = 1;
			
			// 添加mode和id信息
			const submitData = {
				...form.value,
				mode: isEdit.value ? 'edit' : 'add',
				id: isEdit.value ? props.modelValue?.id : undefined
			};
			
			emit('submit', submitData);
			emit('update:visible', false);
			// 仅保存「新增」草稿；编辑提交不回写快照，避免下次新增带出编辑单数据
			if (!isEdit.value) {
				emit('update:lastFormSnapshot', cloneDeep(form.value));
			}
		}
	});
}

// —— 按学号/工号回显借用人信息（防抖，不影响现有交互） ——
let userCodeDebounceTimer: any = null;
async function queryUserByCode(userCode: string) {
  try {
    // 先在已加载的全量列表中查找，避免重复请求
    if (allUserList.value && allUserList.value.length > 0) {
      const local = allUserList.value.find((u: any) => String(u.user_code || '').trim() === String(userCode).trim());
      if (local) {
        form.value.app_user_borrower = Number(local.id);
        form.value.user_code = local.user_code || '';
        form.value.mobile = local.mobile || '';
        return;
      }
    }

    // 远端查询：尽量使用通用查询参数，兼容不同实现
    const tryParamsList = [
      { user_code: userCode, page: 1, limit: 20 },
      { search: userCode, page: 1, limit: 20 },
      { code: userCode, page: 1, limit: 20 },
    ];

    let found: any = null;
    for (const params of tryParamsList) {
      const res: any = await api.GetAllUser(params);
      if (res && (res.code === 2000 || res.status === 200) && Array.isArray(res.data) && res.data.length > 0) {
        // 仅精确匹配学号/工号，搜索不到时不回显其他用户
        found = res.data.find((u: any) => String(u.user_code || '').trim() === String(userCode).trim());
        if (found) break;
      }
    }

    if (found) {
      form.value.app_user_borrower = Number(found.id);
      form.value.user_code = found.user_code || '';
      form.value.mobile = found.mobile || '';
      // 部门信息将由现有的 app_user_borrower 监听逻辑自动回填
    } else {
      // 未找到时不覆盖已有填写，给出轻提示
      ElMessage.warning('未找到匹配的借用人');
    }
  } catch (e) {
    /* empty */
  }
}

/*function scheduleQueryUserByCode(userCode: string) {
  if (userCodeDebounceTimer) clearTimeout(userCodeDebounceTimer);
  userCodeDebounceTimer = setTimeout(() => {
    if (!userCode || String(userCode).trim().length < 2) return;
    if (form.value.borrower_type === 2) return; // 外部用户不查
    if (isView.value) return; // 查看态不查
    queryUserByCode(String(userCode).trim());
  }, 300);
}

 watch(() => form.value.user_code, (nv) => {
  scheduleQueryUserByCode(nv as any);
}); */

</script>
