<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="请选择借用人角色"  :disabled="isView" >
						<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="请选择借用人"  :disabled="isView" >
						<el-option  :label="adminList.name" :value="adminList.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="请选择借用人"  :disabled="isView" >
						<el-option v-for="item in allUserList"  :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="请输入借用人"  :disabled="isView"/>
					</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"/>
					</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" placeholder="请选择预计归还时间" style="width: 100%"  :disabled="isView"/>
					</el-form-item>
				</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-input :model-value="displayApproverName" placeholder="-" :disabled="true" />
					</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="{ row, $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
			:disabled="true"
			list-type="picture-card"
			:show-file-list="true"
			:on-preview="handlePictureCardPreview"
			:http-request="handleCustomUpload"
			:file-list="fileList"
			style="margin-top: 10px;"
			>
			<el-icon><Plus /></el-icon>
			</el-upload>
			<!-- <el-upload
				:disabled="true"
				class="avatar-uploader"
				action="#"
				:show-file-list="false"
				:on-success="handleUploadSuccess"
			>
				<img v-if="form.attachments" :src="form.attachments" class="avatar" />
				<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
			</el-upload> -->
		    </div>

			<!-- 续借信息（仅查看模式展示） -->
			<div v-if="isView && form.latest_renewal" style="margin-top: 8px;">
				<div style="font-weight: bold; margin-bottom: 8px">续借信息</div>
				<el-row :gutter="16">
					<el-col :span="4">
						<el-form-item label="续借天数">
							<el-input :model-value="form.latest_renewal?.renewal_days" :disabled="true">
								<template #append>天</template>
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="21">
						<el-form-item label="续借理由">
							<el-input :model-value="form.latest_renewal?.renewal_reason" type="textarea" :disabled="true" />
						</el-form-item>
					</el-col>
				</el-row>
			</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 type="success" @click="onSucess">通过</el-button>
			<el-button  type="danger"  @click="onDanger(form.id)">拒绝</el-button>
			<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>
	<SelectDeviceDialogApp v-model:visible="showSelectDeviceDialog" @confirm="onDeviceSelected" />
	<!-- <SelectCatgory v-model:visible="showSelectDeviceDialog" @confirm="onDeviceSelected" /> -->
	<RefuseNotification/>
	<WarehouseSelectDialog 
		v-model="showWarehouseDialog"
		:formId="currentApprovalFormId"
		@confirm="handleWarehouseConfirm"
	/>
</template>

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

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const showRejectDialog = ref(false);
const rejectReason = ref('');
const currentFormId = ref<number | null>(null);

provide('showRejectDialog', showRejectDialog);
provide('rejectReason', rejectReason);
provide('currentFormId', currentFormId);
provide('closeDialog', onCancel);

const crudExpose = inject('crudExpose') as any;
provide('crudExpose', crudExpose); 


/* 获取管理员列表 */
const adminList = ref([]);

async function getAdminList() {
	const res = await getUserInfo();
	adminList.value = res.data;
	console.log("adminList.value:::",adminList.value)	
}

/* 获取所有用户 */
const allUserList = ref([]);
async function getAllUserList() {
	const res = await apis.GetAllUser({page:1,limit: 999});
	allUserList.value = res.data||[];
	/* const adminRes = await getAdminUserInfo();
	const adminUser = adminRes.data; */
	// // 设置默认选择第一个用户
	// if (allUserList.value.length > 0) {
	// 	form.value.app_user_borrower = allUserList.value[0].id;
	// }

    // 检查是否已存在该用户，避免重复添加
  /*   const exists = allUserList.value.some(user => user.id === adminUser.id);
    if (!exists) {
      allUserList.value.push(adminUser);
    } */
	console.log("allUserList.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 showWarehouseDialog = ref(false);
const currentApprovalFormId = ref<number | null>(null);

function openWarehouseDialog() {
	currentApprovalFormId.value = props.modelValue?.id ?? null;
	showWarehouseDialog.value = true;
}

async function handleWarehouseConfirm(data: { formId: number; warehouseId: number }) {
	await api.BorrowingReview(data.formId, "approve", "同意借用", data.warehouseId);
	ElMessage.success("审批通过");
	emit('update:visible', false);
	crudExpose?.doRefresh();
}
const visible = ref(props.visible);
const formRef = ref();


const fileList = ref<UploadUserFile[]>([]);

function handleUploadSuccess(response: any, file: any, fileList: any) {
	// eslint-disable-next-line no-console
  console.log('上传成功:', file.name);
}
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
// 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;
}

// 获取待审批人显示名称（与 buildSteps 中逻辑一致）
// 待审批时显示当前环节审批人；审批完成后显示全部环节（老师、学院领导、管理员）的审批人
function getPendingApproverDisplay(data: any): string {
  if (!data) return '';
  const adminInfo = data.admin_approver_info;
  const status = data.status;

  // 审批完成后：按实际审批顺序（老师→学院领导→管理员）显示
  if (status >= 2 && status !== 3) {
    const approvedRecords = data.approval_records?.filter((r: any) => r.status === 1) || [];
    if (approvedRecords.length) {
      const sorted = [...approvedRecords].sort(
        (a: any, b: any) => (a.step_order ?? 0) - (b.step_order ?? 0)
      );
      const names = sorted
        .map((r: any) => (r.approver_name || r.app_user_approver_name || r.name || '').trim())
        .filter(Boolean);
      if (names.length) return names.join('、');
    }
    if (adminInfo?.all_steps_status?.length) {
      const allNames: string[] = [];
      const seen = new Set<string>();
      const sortedSteps = [...adminInfo.all_steps_status].sort(
        (a: any, b: any) => (a.step_order ?? 0) - (b.step_order ?? 0)
      );
      for (const step of sortedSteps) {
        if (step.approvers?.length) {
          for (const a of step.approvers) {
            const name = (a.name || '').trim();
            if (name && !seen.has(name)) {
              seen.add(name);
              allNames.push(name);
            }
          }
        }
      }
      if (allNames.length) return allNames.join('、');
    }
  }

  // 待审批时：取当前待审批环节，排除已通过的步骤（API 可能将已通过步骤仍标为 is_current）
  const isApproved = (s: any) => s.status === 'approved' || s.status_label === '已通过';
  const isPendingOrCurrent = (s: any) =>
    !isApproved(s) && (
      s.status === 'pending' || s.status_label === '待审核' ||
      s.status === 'current' || s.status_label === '当前步骤' || s.is_current === true
    );
  const candidateSteps = adminInfo?.all_steps_status?.filter(isPendingOrCurrent) || [];
  const sortedCandidates = [...candidateSteps].sort((a: any, b: any) => (a.step_order ?? 0) - (b.step_order ?? 0));
  const pendingStep = sortedCandidates[0];
  if (pendingStep?.approvers?.length) {
    const stepName = pendingStep.step_name || '';
    let approvers = pendingStep.approvers;
    if (stepName.includes('老师')) {
      // 老师环节：仅显示 type 为 app_user 的审批人（老师姓名）
      approvers = approvers.filter((a: any) => a.type === 'app_user');
    } else if (stepName.includes('管理员')) {
      // 二级管理员/管理员环节：仅显示 type 为 admin 的审批人（超级管理员）
      approvers = approvers.filter((a: any) => a.type === 'admin');
    }
    const names = approvers.map((a: any) => a.name).filter((n: string) => n && n.trim());
    if (names.length) return names.join('、');
  }
  const currentApprovers = adminInfo?.current_step?.approvers;
  if (Array.isArray(currentApprovers) && currentApprovers.length) {
    const names = currentApprovers.map((a: any) => a.name).filter((n: string) => n && n.trim());
    if (names.length) return names.join('、');
  }
  const currentStep = adminInfo?.all_steps_status?.find((s: any) => s.is_current);
  if (currentStep?.approvers?.length) {
    const names = currentStep.approvers.map((a: any) => a.name).filter((n: string) => n && n.trim());
    if (names.length) return names.join('、');
  }
  if (data.approval_records?.length) {
    const pendingRecords = data.approval_records.filter(
      (item: any) => (status === 1 ? item.status !== 1 : item.status !== 0)
    );
    const names = pendingRecords
      .map((item: any) => item.approver_name || item.app_user_approver_name || item.name)
      .filter((name: string) => name && name.trim());
    if (names.length) return names.join('、');
  }
  return data.approver_info?.name || '未知';
}

const timeline = ref({
	setpstatus:0,
	create: '',
	approve: '',
	approver: '',
	approvemsg:''
});


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

  const approverinfo = data.approver_info ?? data.admin_approver_info


  if (data.status >= 2&&data.status!=3 && data.borrow_type!=1) {
    /*   // 将审批记录倒序排列
    const reversedApprovalRecords = [...data.approval_records]
    reversedApprovalRecords.forEach((item:any,index:number) => {
      if(item.status === 1){
        if(index == 1){
        steps.value.push({
          title: '审批通过',
            description: `审批人：${item.app_user_approver_name}，时 间：${item.approve_time}`,
            status: 'finish'
          });
        }else{
          steps.value.push({
            title: '审批通过',
            description: `审批人：${item.approver_name}，时 间：${item.create_datetime},领取仓库:${getWarehouseName(data.warehouse)||'暂无仓库'}`,
            status: 'finish'
          });
        }
      }
    }); */
	// 将审批记录倒序排列
    const reversedApprovalRecords = [...data.approval_records]
    // 先找出所有审批通过的记录
    const approvedRecords = reversedApprovalRecords.filter((item:any) => item.status === 1)
    const lastApprovedIndex = approvedRecords.length - 1
    
    reversedApprovalRecords.forEach((item:any,index:number) => {
      if(item.status === 1){
        // 找到当前记录在审批通过记录中的索引
        const currentApprovedIndex = approvedRecords.findIndex((record:any) => record === item)
        // 判断是否是最后一个审批通过的记录
        const isLastApproved = currentApprovedIndex === lastApprovedIndex
        
       /*  if(index == 1){1
        steps.value.push({
          title: '审批通过',
            description: `审批人：${item.approver_name||item.app_user_approver_name}，时 间：${item.approve_time}`,
            status: 'finish'
          });
        }else{ */
          // 只在最后一个审批通过的记录中显示领取仓库
          const warehouseInfo = isLastApproved ? `,领取仓库:${getWarehouseName(data.warehouse)||'暂无仓库'}` : ''
          steps.value.push({
            title: '审批通过',
            description: `审批人：${item.approver_name||item.app_user_approver_name}，时 间：${item.create_datetime ? dayjs(item.create_datetime).format('YYYY-MM-DD HH:mm:ss') : ''}${warehouseInfo}`,
            status: 'finish'
          });
        /* } */
      }
    });
  } else if (data.status === 3) {
    // console.log("data.approver_name:::",data.approver_info.name)
    const rejectNames = data.approval_records
      .filter((item:any) => item.status === 2)
      .map((item:any) => item.approver_name || item.app_user_approver_name || item.name)
      .filter((name:any) => name && name.trim());
    const rejectReason = data.approval_records
      .filter((item:any) => item.status === 2)
      .map((item:any) => item.approve_remark)
      .filter((reason:any) => reason && reason.trim());
    const rejectTime = data.approval_records
      .filter((item:any) => item.status === 2)
      .map((item:any) => item.approve_time)
      .filter((time:any) => time && time.trim());
    steps.value.push({
      title: '审批拒绝',
      description: `审批人：${rejectNames.join('、')}，拒绝原因: ${rejectReason.join('、')},时间：${rejectTime.join('、')}`,
      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: 1,
	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: [],
	accessories: '',
	mobile:'',
	user_code:'',
	borrow_type: 2,
	return_location:'',
	attachments:'',
	admin_borrower:'',
	latest_renewal: {
		renewal_days: '',
		renewal_reason: ''
	}
});

// 表单审批人显示：待审批时与流程步骤一致，审批完成后显示管理员
const displayApproverName = computed(() => {
  const data = form.value as any;
  if (!data?.id) return '';
  const status = data.status;
  if (status >= 2 && status !== 3) return '管理员'; // 审批通过
  if (status >= 4) return '管理员'; // 流程完成
  if (status === 1) return getPendingApproverDisplay(data); // 待审批
  if (status === 3) {
    const rejectNames = data.approval_records
      ?.filter((item: any) => item.status === 2)
      ?.map((item: any) => item.approver_name || item.app_user_approver_name || item.name)
      ?.filter((name: string) => name && name.trim()) || [];
    return rejectNames.join('、') || data.approver_info?.name || '未知';
  }
  return data.approver_info?.name || data.admin_approver_info?.name || '';
});

const showSelectDeviceDialog = ref(false);


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: true, message: '请输入备注', trigger: 'change' },
  ],
};


// 自动填充用户信息
onMounted(() => {
	loadWarehouses()
	try {
		getAllUserList()
		const bortype=props.modelValue.borrower_type;
		if(bortype==0){
			getAdminList()
			
		}else if(bortype==1){
			const userInfo = props.modelValue.borrower_info;
			if (userInfo) {
				form.value.borrower_type = 1;
				form.value.app_user_borrower = userInfo.id || '';
				// form.value.app_user_borrower = Number(userInfo.dept_info?.dept_id )|| 1;
				form.value.user_code=userInfo.user_code||'';
				form.value.mobile=userInfo.mobile||'';
				form.value.borrower_dept = userInfo.dept_info?.dept_name || '';
			}
			console.log("form.value1111:",form.value);
		}else if(bortype==2){
			const userInfo = props.modelValue.borrower_info;
			if (userInfo) {
				form.value.borrower_type =2;
				form.value.external_borrower_name = userInfo.id || '';
				// form.value.app_user_borrower = Number(userInfo.dept_info?.dept_id )|| 1;
				form.value.user_code=userInfo.user_code||'';
				form.value.external_borrower_phone = userInfo.mobile || '';
				form.value.borrower_dept = userInfo.dept_info?.dept_name || '';
			}
		}
		
	} catch (e) {
		/* empty */
	}
});

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 apis.GetApplicationDetail(val.id);
			if (res.code === 2000 && res.data) {
				const data = res.data;
				Object.assign(form.value, data);
				buildSteps(data);
				form.value.app_user_borrower = res.data.app_user_borrower?.id || '';

				// 处理附件回显
				if (data.attachments) {
					if (typeof data.attachments === 'string') {
						// 如果attachments是字符串URL
						fileList.value = [{
							name: data.attachments.split('/').pop() || '附件',
							url: data.attachments,
							status: 'success'
						}];
					} else if (Array.isArray(data.attachments)) {
						// 如果attachments是数组
						fileList.value = data.attachments.map((item: any, index: number) => {
							if (typeof item === 'string') {
								return {
									name: item.split('/').pop() || `附件${index + 1}`,
									url: item,
									status: 'success'
								};
							} else if (typeof item === 'object' && item.url) {
								return {
									name: item.name || item.url.split('/').pop() || `附件${index + 1}`,
									url: item.url,
									status: 'success'
								};
							}
							return null;
						}).filter(Boolean);
					}
				}
       
			}
			} catch (e) {
			  ElMessage.error('获取审批信息失败');
			}
	}else if(val&& isEdit.value){
		try {
			const res = await apis.GetApplicationDetail(val.id);
	
			if (res.code === 2000 && res.data) {
				const data = res.data;
				Object.assign(form.value, data);
				form.value.app_user_borrower = res.data.app_user_borrower?.id || '';

				// 处理附件回显 (编辑模式)
				if (data.attachments) {
					if (typeof data.attachments === 'string') {
						fileList.value = [{
							name: data.attachments.split('/').pop() || '附件',
							url: data.attachments,
							status: 'success'
						}];
					} else if (Array.isArray(data.attachments)) {
						fileList.value = data.attachments.map((item: any, index: number) => {
							if (typeof item === 'string') {
								return {
									name: item.split('/').pop() || `附件${index + 1}`,
									url: item,
									status: 'success'
								};
							} else if (typeof item === 'object' && item.url) {
								return {
									name: item.name || item.url.split('/').pop() || `附件${index + 1}`,
									url: item.url,
									status: 'success'
								};
							}
							return null;
						}).filter(Boolean);
					}
				}
			}
			} 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 => user.id === newValue);
    if (selectedUser) {
      form.value.user_code = selectedUser.user_code || '';
	  form.value.mobile = selectedUser.mobile || '';
    }
  }
});

// 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) {
	console.log("devices:::",devices);
	form.value.items.push(
		...devices.map((d) => ({
			device_category: d.id,
			remark: d.name,
			quantity: 1,
			location: d.warehouse,
		}))
	);
}
function removeItem(index: number) {
	form.value.items.splice(index, 1);
}

async function onDanger(formId: number){
	currentFormId.value = formId;
	showRejectDialog.value = true;
}

async function onSucess(){
	// 检查是否为续借待审批状态（状态值为9）
	if (form.value.status === 9) {
		// 续借审批不需要选择仓库，直接审批通过
		await api.BorrowingReview(form.value.id, "approve", "同意续借");
		ElMessage.success("续借审批通过");
		emit('update:visible', false);
		crudExpose?.doRefresh();
	} else {
		// 普通审批需要选择仓库
		openWarehouseDialog();
	}
}




function onCancel() {
	// 清空附件列表
	fileList.value = [];
	emit('update:visible', false);
}
function onSubmit() {
	
	formRef.value.validate((valid: boolean) => {
		if (valid) {
			form.value.items = form.value.items.map(item => ({
                ...item,
                quantity: Number(item.quantity) || 0  
            }));
			const firstLocation = form.value.items[0]?.location || '';
            form.value.return_location = firstLocation;
			form.value.expected_start_time = now;
			form.value.expected_end_time = dayjs(form.value.expected_end_time).format('YYYY-MM-DD HH:mm:ss')|| now;
			form.team_members_count=Number(form.value.team_members_count)||1;
			form.value.mode = isEdit.value ? 'edit' : 'add';
			console.log(form.value);
			// return
			emit('submit', { ...form.value });
			emit('update:visible', false);
			// ElMessage.success("添加成功！");
		}
	});
	
}

</script>
