<template>
	<el-dialog v-model="visible" title="借用申请单" width="75%" :close-on-click-modal="false" @close="onCancel">
		<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="请输入学号/工号"  :disabled="isView" @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="请输入联系电话" :disabled="isView" />
					</el-form-item>
					<el-form-item label="联系电话" prop="external_borrower_phone" v-if="form.borrower_type == 2">
						<el-input v-model="form.external_borrower_phone" placeholder="请输入联系电话"  :disabled="isView"/>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="借用部门" prop="borrower_dept">
						<el-input v-model="form.borrower_dept" placeholder="请输入借用部门" :disabled="isView" />
					</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%"  :disabled="isView"/>
					</el-form-item>
				</el-col>
				<el-col :span="24" v-if="!isView">
					<el-alert
						v-if="matchedWorkflowName"
						type="info"
						:closable="false"
						show-icon
					>
						<template #title>将使用审批流程：{{ matchedWorkflowName }}</template>
					</el-alert>
					<el-alert
						v-else-if="workflowsLoadDone && form.expected_end_time"
						type="warning"
						:closable="false"
						show-icon
						title="当前条件未匹配到启用中的审批流程，提交后将由后台默认规则处理；请检查流程管理中的天数区间、借用类型（含特殊借用）等配置"
					/>
				</el-col>
				<el-col :span="4">
					<el-form-item label="个人/团队" prop="team_type" >
						<el-select v-model="form.team_type" placeholder="请选择" :disabled="isView">
							<el-option label="个人" :value="0" />
							<el-option label="团队" :value="1" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="4" v-show="form.team_type===1">
					<el-form-item label="团队人数" prop="team_members_count">
						<el-input v-model="form.team_members_count" placeholder="请输入"  :disabled="isView"/>
					</el-form-item>
				</el-col>
				<el-col :span="16" v-show="form.team_type===1">
					<el-form-item label="团队其他人员名单" prop="team_members">
						<el-input v-model="form.team_members" placeholder="请输入团队其他人员名单"  :disabled="isView"/>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="借用原因" prop="purpose">
						<el-input v-model="form.purpose" type="textarea" placeholder="请输入借用原因" :disabled="isView" />
					</el-form-item>
				</el-col>
				<el-col :span="4">
					<el-form-item label="审批人" prop="applicant_remark_type">
						<el-select v-model="form.applicant_remark_type" placeholder="请选择" :disabled="isView" >
							<el-option label="管理员" value="1"/>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="20">
					<el-form-item label="备注" prop="applicant_remark">
						<el-input v-model="form.applicant_remark" placeholder="请输入备注"  :disabled="isView"/>
					</el-form-item>
				</el-col>
			</el-row>
			<div style="margin: 16px 0 8px 0; font-weight: bold">借用列表</div>
			<!-- {{ isEdit }} -->
			<el-table :data="!isEdit ? form.items : form.items.filter(item => item.device === null)" border style="width: 50%; margin-bottom: 12px">
				<el-table-column type="index" label="序号" width="60" />
				<el-table-column prop="device_category_name" label="设备分类" />
				<!-- <el-table-column prop="quantity" label="借用数量" /> -->
				<el-table-column label="借用数量">
				<template #default="{ row }">
				<el-input v-model="row.quantity" type="number" :min="1" prop="quantity" size="small" :disabled="isView" />
				</template>
				</el-table-column>
				<!-- <el-table-column prop="location" label="存放仓库" /> -->
				<el-table-column label="操作" width="80">
					<template #default="{ $index }">
						<el-button type="text" style="color: red" @click="removeItem($index)" :disabled="isView">移除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-button type="primary" @click="addItem" v-if="!isView">选择设备分类</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>
			<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>
		<!-- 审批信息流程展示 -->
		<div v-if="isView"  style="margin-top: 24px; padding: 0 12px">
		<div style="font-weight: bold; margin-bottom: 12px">审批流程进度</div>
		<el-steps :active="steps.length" align-center>
			<el-step
				v-for="(step, index) in steps"
				:key="index"
				:title="step.title"
				:description="step.description"
				icon="CircleCheck"
				:status="step.status"
			/>
			</el-steps>

		</div>

		<template #footer>
			<el-button @click="onCancel">关闭</el-button>
			<el-button type="primary" @click="onSubmit" v-if="!isView">提交</el-button>
		</template>
	</el-dialog>
	 <el-dialog v-model="dialogVisible">
		<img w-full :src="dialogImageUrl" alt="Preview Image" />
	</el-dialog>
	<!-- <SelectDeviceDialog v-model:visible="showSelectDeviceDialog" @confirm="onDeviceSelected" /> -->
	<SelectCatgory 
		v-model:visible="showSelectDeviceDialog" 
		@confirm="onDeviceSelected" 
		:disabled-ids="form.items.map((item) => item.device_category).filter(Boolean)"
	/>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, computed } from 'vue';
import SelectDeviceDialog from './SelectDeviceDialog/index.vue';
import dayjs from 'dayjs';
import { ElMessage ,UploadProps, UploadUserFile } from 'element-plus';
import * as api from '../../api';
import Cookies from 'js-cookie';
import { request } from '/@/utils/service';
import { Plus } from '@element-plus/icons-vue';
import SelectCatgory from '../SelectCatgory/index.vue';
import { getUserInfo } from '../../../login/api';
import * as workflowApi from '../../workflow/api';
import {
	pickWorkflowIdForSpecialBorrow,
	findWorkflowNameById,
	type SpecialBorrowMatchInput,
} from '../../utils/matchBorrowWorkflow';

// 定义用户和管理员接口
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('');

async function getAllUserList() {
	userSearchLoading.value = true;
	try {
		const res = await api.GetAllUser({page:1,limit:999});
		allUserList.value = res.data;
		filteredUserList.value = res.data;
		// 设置默认选择第一个用户
		/* if (allUserList.value.length > 0) {
			form.value.app_user_borrower = allUserList.value[0].id;
		} */
		console.log("allUserList.value:::",allUserList.value)	
	} 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 now = dayjs().format('YYYY-MM-DD HH:mm:ss');


const props = defineProps<{ visible: boolean; modelValue?: any }>();

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

const emit = defineEmits(['update:visible', 'update:modelValue', 'submit']);
const visible = ref(props.visible);
const formRef = ref();


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);
  }
};

// import { ElSteps } from 'element-plus';
const steps = ref<any[]>([]);
// 仓库映射（id -> name）
const warehouseMap = ref<Record<string, string>>({});

async function loadWarehouses() {
	try {
		const res = await request({
			url: '/api/system/warehouse/',
			method: 'get',
			params: { page: 1, limit: 999 }
		});
		if (res?.code === 2000 && Array.isArray(res.data)) {
			warehouseMap.value = Object.fromEntries(
				res.data.map((w: any) => [String(w.id), w.name])
			);
		}
	} catch (e) {
		/* empty */
	}
}

function getWarehouseName(id: any) {
	const key = id != null ? String(id) : '';
	return warehouseMap.value[key] ?? id;
}
const timeline = ref({
	setpstatus:0,
	create: '',
	approve: '',
	approver: '',
	approvemsg:''
});


function buildSteps(data: any) {
  steps.value = [
    {
      title: '创建申请',
      description: `创建时间：${data.create_datetime}`,
      status: 'finish'
    },
    {
      title: '待审批',
      description: '待审批人审批',
      status: data.status >= 2 ? 'finish' : 'process'
    }
  ];

  if (data.status >= 2&&data.status!=3) {
    steps.value.push({
      title: '审批通过',
      description: `审批人：${data.approver_info.name}，时间：${data.approve_time},仓库:${getWarehouseName(data.warehouse)||'暂无仓库'}`,
      status: 'finish'
    });
  } else if (data.status === 3) {
    steps.value.push({
      title: '审批拒绝',
      description: `审批人：${data.approver_info.name}，拒绝原因: ${data.approve_remark},时间：${data.approve_time}`,
      status: 'error'
    });
  }

  if (data.status >= 4) {
    steps.value.push({
      title: '流程完成',
      description: '流程已结束',
      status: 'finish'
    });
  }
}

// const activeStep = ref(1);



const form = ref({
	borrower_type: 1,
	application_no: '',
	external_borrower_name:"",
	external_borrower_phone:"",
	emergency_contact: '111',
	emergency_phone: '11111',
	app_user_borrower: null as number | null,
	admin_borrower: null as number | null,
	team_type: 0,
	team_members_count: 2,
	team_members: '',
	expected_start_time:'',
	expected_end_time: '',
	borrower_dept: '',
	purpose: '',
	applicant_remark_type: "1",
	applicant_remark: '',
	items: [] as any[],
	accessories: '',
	borrow_type: 2,
	return_location:'',
	attachments:'',
	user_code: '',
	mobile: '',
	mode: '' as 'add' | 'edit' | 'view' | '',
});
const showSelectDeviceDialog = ref(false);

/** 用于按「流程管理」中的条件自动匹配 workflow id */
const workflowsForMatch = ref<Record<string, any>[]>([]);
const workflowsLoadDone = ref(false);

async function loadWorkflowsForMatch() {
	workflowsLoadDone.value = false;
	try {
		const res: any = await workflowApi.GetList({ page: 1, limit: 999 } as any);
		workflowsForMatch.value = Array.isArray(res?.data) ? res.data : [];
	} catch {
		workflowsForMatch.value = [];
	} finally {
		workflowsLoadDone.value = true;
	}
}

const resolvedAppUserType = computed(() => {
	if (form.value.borrower_type !== 1 || form.value.app_user_borrower == null) return null;
	const u = allUserList.value.find((x) => Number(x.id) === Number(form.value.app_user_borrower));
	return u != null ? (u as any).user_type ?? null : null;
});

const specialBorrowMatchInput = computed((): SpecialBorrowMatchInput => ({
	borrow_type: 2,
	borrower_type: form.value.borrower_type,
	team_type: form.value.team_type,
	expected_start_time: form.value.expected_start_time || undefined,
	expected_end_time: form.value.expected_end_time || undefined,
	app_user_type: resolvedAppUserType.value,
}));

const matchedWorkflowId = computed(() => {
	if (!workflowsForMatch.value.length) return null;
	return pickWorkflowIdForSpecialBorrow(workflowsForMatch.value, specialBorrowMatchInput.value);
});

const matchedWorkflowName = computed(() =>
	findWorkflowNameById(workflowsForMatch.value, matchedWorkflowId.value)
);

watch(
	() => props.visible,
	(v) => {
		if (v && !isView.value) {
			void loadWorkflowsForMatch();
		}
	}
);

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' },
  ],
/*   borrower_dept: [
    { required: true, message: '请输入借用部门', trigger: 'change' },
  ], */
  expected_end_time: [
    { required: true, message: '请输选择归还时间', trigger: 'change' },
  ],
  team_type: [
    { required: true, message: '请选择个人或者团队', trigger: 'change' },
  ],
  purpose: [
    { required: true, message: '请输入借用原因', trigger: 'change' },
  ],
  applicant_remark_type: [
    { required: true, message: '请选择审批人', trigger: 'change' },
  ],
  applicant_remark: [
    { required: false, message: '请输入备注', trigger: 'change' },
  ],
};


// 自动填充用户信息
onMounted(() => {
	loadWarehouses()
	getAdminList()
	getAllUserList()
	try {
		// const userInfo = JSON.parse(sessionStorage.getItem('userInfo') || '{}');
		// if (userInfo) {
		// 	form.value.borrower_type = 1;
		// 	form.value.external_borrower_name =  '';/* userInfo.username || */
		// 	form.value.app_user_borrower =  null;/* Number(userInfo.dept_info?.dept_id )|| */
		// 	form.value.external_borrower_phone = '';/* userInfo.mobile ||  */
		// 	form.value.items =  [];
		// }
	} catch (e) {
		/* empty */
	}
});

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;
      }
    }

    // 远端查询：尽量使用通用查询参数，兼容不同实现|| res.data[0]
    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()) ;
        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 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);
}

watch(
	() => props.visible,
	(v) => (visible.value = v)
);

watch(() => props.modelValue, async (val) => {
	console.log("val+++",val && val.id && isView.value,val&& isEdit.value);
  if (val && val.id && isView.value) {
			try {
			const res = await api.GetApplicationDetail(val.id);
			if (res.code === 2000 && res.data) {
				const data = res.data;
				Object.assign(form.value, data);
				buildSteps(data);
				// console.log("data:::",data);

			}
			} catch (e) {
			ElMessage.error('获取审批信息失败');
			}
	}else if(val&& isEdit.value){
		try {
			const res = await api.GetApplicationDetail(val.id);
	
			if (res.code === 2000 && res.data) {
				const data = res.data;
			/* 	if(isEdit.value){
					data.app_user_borrower = data.borrower_info.id;
				} */
					console.log(data);
				Object.assign(form.value, data);
				console.log("form.value:::",form.value);
			}
			} catch (e) {
			ElMessage.error('获取审批信息失败');
			}
	}
}, { immediate: true });
// 监听借用人选择变化
watch(() => form.value.app_user_borrower, (newValue) => {
  if (newValue && allUserList.value.length > 0) {
    const selectedUser = allUserList.value.find(user => Number(user.id) === newValue);
    if (selectedUser) {
      form.value.user_code = selectedUser.user_code || '';
	  form.value.mobile = selectedUser.mobile || '';
	  // 根据用户类型动态设置借用部门：
	  // 学生(user_type===0)：学院/专业/班级；教师或领导(user_type===1或3)：学院
	  let deptName: string = '';
	  const orgDetail: any = (selectedUser as any).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 as any).user_type === 0) {
		// 学生：优先按 parent_chain 顺序拼接“学院/专业/班级”，过滤掉“学校”层级
		const chainNames: string[] = parentChain
		  .filter((n: any) => Number(n?.type) !== 1) // 1=学校，过滤
		  .map((n: any) => n?.name)
		  .filter((n: any) => isValid(n));
		// 取前3级：学院(0)/专业(1)/班级(2)
		const college = chainNames[1] || '';
		const major = chainNames[2] || (selectedUser as any).sub_organization || '';
		const clazz = orgDetail.name || (selectedUser as any).class_or_group || '';
		const parts = [college, major, clazz].filter((p) => isValid(p));
		deptName = parts.join('/');
		if (!deptName) {
		  // 兜底：若 parent_chain 不可用，则使用已有汇总字段但尽量去掉“学校/”前缀
		  const full = (selectedUser as any).full_organization_name || '';
		  deptName = full.replace(/^学校\s*\/\s*/,'');
		  // 兜底后继续清洗 'nan' 与空白段
		  deptName = deptName
		    .split('/')
		    .map((s: string) => s.trim())
		    .filter((s: string) => isValid(s))
		    .join('/');
		}
		// 最终统一清洗，避免出现重复斜杠或 'nan'
		deptName = deptName
		  .split('/')
		  .map((s: string) => s.trim())
		  .filter((s: string) => isValid(s))
		  .join('/');
	  } else if ((selectedUser as any).user_type === 1 || (selectedUser as any).user_type === 3) {
		// 教师或学院领导：显示学院名称
		deptName = orgDetail?.name || (selectedUser as any).organization || (selectedUser as any).full_organization_name || '';
	  } else {
		// 其他类型兜底
		deptName = (selectedUser as any).full_organization_name || '';
	  }
	  form.value.borrower_dept = isValid(deptName)?deptName:'';
	  // 如果是新创建的用户，提示用户填写完整信息
	  if (selectedUser.isNew) {
		ElMessage.info('请为新用户填写学号/工号和联系电话');
	  }
    }
  }
});

// watch(
// 	() => props.modelValue,
// 	(v) => {
// 		if (v) {
// 			// eslint-disable-next-line no-console
// 			console.log("val:::::",v);
// 			Object.assign(form.value, v);
// 		}
// 	}, { immediate: true }
// );

function addItem() {
	showSelectDeviceDialog.value = true;
}
function onDeviceSelected(devices: any[]) {
	console.log("devices:::",devices);
	// 获取已存在的设备分类ID列表
	const existingIds = new Set(form.value.items.map((item: any) => item.device_category).filter(Boolean));
	
	// 过滤掉已存在的设备分类，只添加新的
	const newDevices = devices.filter((d: any) => !existingIds.has(d.id));
	
	if (newDevices.length === 0) {
		ElMessage.warning('所选设备分类已存在，未添加重复项');
		return;
	}
	
	// 如果有部分重复，提示用户
	if (newDevices.length < devices.length) {
		ElMessage.warning(`已过滤 ${devices.length - newDevices.length} 个重复的设备分类`);
	}
	
	form.value.items.push(
		...newDevices.map((d: any) => ({
			device_category: d.id,
			remark: d.name,
			quantity: 1,
			location: d.warehouse,
			device_category_name: d.name,
		}))
	);
}
function removeItem(index: number) {
	form.value.items.splice(index, 1);
}
function onCancel() {
	emit('update:visible', false);
}
function onSubmit() {
	formRef.value.validate(async (valid: boolean) => {
		if (!valid) return;
		if (!workflowsForMatch.value.length) {
			await loadWorkflowsForMatch();
		}
		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 = now;
		const endDay = form.value.expected_end_time;
		form.value.expected_end_time = endDay
			? dayjs(endDay).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) || 1;
		form.value.mode = isEdit.value ? 'edit' : 'add';
		form.value.borrow_type = 2;

		const matchPayload: SpecialBorrowMatchInput = {
			borrow_type: 2,
			borrower_type: form.value.borrower_type,
			team_type: form.value.team_type,
			expected_start_time: form.value.expected_start_time,
			expected_end_time: endDay || undefined,
			app_user_type: resolvedAppUserType.value,
		};
		const workflowId = pickWorkflowIdForSpecialBorrow(workflowsForMatch.value, matchPayload);

		const submitBody: Record<string, any> = { ...form.value };
		if (workflowId != null) {
			submitBody.workflow = workflowId;
		}
		emit('submit', submitBody);
		emit('update:visible', false);
	});
}

</script>
