<template>
	<el-dialog v-model="visible" :title="isView ? '查看' : isCollect ? '领取' : '归还'" width="75%" :close-on-click-modal="false" @close="onCancel">
        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
            <el-tab-pane label="借用单信息" name="first">       
                <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="isView?'':'请选择借用人角色'"  :disabled="true">
                              <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="external_borrower_name"  v-if="form.borrower_type !== 2">
                            <el-input v-model="form.borrower_info.name" placeholder="请输入借用人" :disabled="true" />
                          </el-form-item> -->
                          <el-form-item label="借用人" prop="admin_borrower" v-if="form.borrower_type == 0">
                            <el-select v-model="form.admin_borrower" :placeholder="isView?'':'请选择借用人'" :disabled="true" >
                              <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.id" :placeholder="isView?'':'请选择借用人'" :disabled="true" >
                              <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="isView?'':'请输入借用人'" :disabled="true" />
                          </el-form-item>
                        </el-col>
                        <el-col :span="8" v-if="form.borrower_type !== 2">
                            <el-form-item label="学号/工号" prop="user_code" >
                       <!--      {{ form.borrower_info.user_code }} -->
                                <el-input v-model="form.app_user_borrower.user_code" :placeholder="isView?'':'请输入学号/工号'"  :disabled="true"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="联系电话" v-if="form.borrower_type !== 2">
                                <el-input v-model="form.app_user_borrower.mobile" :placeholder="isView?'':'请输入联系电话'" :disabled="true" />
                            </el-form-item>
                            <el-form-item label="联系电话" v-if="form.borrower_type == 2">
                                <el-input v-model="form.external_borrower_phone" :placeholder="isView?'':'请输入联系电话'" :disabled="true" />
                            </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="true" />
                            </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="datetime" placeholder="请选择预计归还时间" style="width: 100%"  :disabled="true"/>
                            </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="true">
                                    <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="isView?'':'请输入'"  :disabled="true"/>
                            </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="isView?'':'请输入团队其他人员名单'"  :disabled="true"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="借用原因" prop="purpose">
                                <el-input v-model="form.purpose" type="textarea" :placeholder="isView?'':'请输入借用原因'" :disabled="true" />
                            </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="true" >
                                    <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="isView?'':'请输入备注'"  :disabled="true"/>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <div style="margin: 16px 0 8px 0; font-weight: bold"> {{ isCollect ? '借用列表' : '归还列表' }}</div>
                    <el-table :data="form.items.filter(item => item.device === null)" border style="width: 100%; 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="isCollect ? '借用数量' : '归还数量'">
                        <template #default="{ row }">
                        <el-input v-model="row.quantity" type="number" :min="1" prop="quantity" size="small" :disabled="true" />
                        </template>
                        </el-table-column>
                        <el-table-column prop="condition" label="归还备注" v-if="isReturn">
                            <template #default="{ row }">
                                <el-input v-model="row.condition" :placeholder="isView?'':'请输入备注'"  :disabled="true" />
                            </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="true">移除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-button type="primary" @click="addItem" v-if="!isView" :disabled="true">添加设备</el-button>
                    <div style="margin: 16px 0 8px 0; font-weight: bold">配件信息</div>
                    <el-input v-model="form.accessories" :placeholder="isView?'':'请输入配件信息'"  :disabled="true"/>

                    <div style="margin: 16px 0 8px 0; font-weight: bold" >附件</div>
                    <el-upload
                    action="#"
                    drag
                    list-type="text"
                    accept=".bmp,.gif,.jpeg,.jpg,.png,‌.webp,.svg"
                    multiple
                    :show-file-list="true"
                    :on-success="handleUploadSuccess"
                    :on-error="handleUploadError"
                    :disabled="true"
                    >
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或 <em>点击上传</em></div>
                    </el-upload>
                </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="activeStep" align-center>
                        <el-step
                        title="创建申请"
                        :description="`创建时间：${ timeline.create }`"
                        icon="CircleCheck"
                        :status="activeStep >= 1 ? 'finish' : 'wait'"
                        />
                        <el-step
                        title="待审批"
                        description="待超级管理员审批"
                        icon="CircleCheck"
                        :status="activeStep >= 2 ? 'finish' : 'wait'"
                        />
                        <el-step
                        title="审批通过"
                        :description="`审批人：${timeline.approver}，时间：${timeline.approve}`"
                        icon="CircleCheck"
                        :status="activeStep >= 3 ? 'finish' : 'wait'"
                        />
                        <el-step
                        title="流程完成"
                        description="流程已结束"
                        icon="CircleCheck"
                        :status="activeStep >= 4 ? 'finish' : 'wait'"
                        />
                    </el-steps>
                </div> -->
                <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>
            </el-tab-pane>
        <el-tab-pane v-if="isCollect" label="设备清单" name="second">
            <el-form :model="form" label-width="110px">
                <el-row :gutter="16">
                    <el-col :span="24">
                        <div style="margin: 8px 0">
                            <el-input v-model="searchText" placeholder="请扫描设备条码添加" style="width: 300px" @keyup.enter="handleScanSearch" />
                            <el-button type="primary" style="margin-left: 16px" @click="handleAdd">手动借用</el-button>
                        </div>
                        <el-table :data="deviceList" border style="width: 100%">
                            <el-table-column type="index" label="序号" width="60" align="center" />
                            <el-table-column prop="device_no" label="设备编号" align="center" />
                            <el-table-column prop="device_type" label="设备分类" align="center" />
                            <el-table-column prop="device_name" label="设备名称" align="center" />
                            <el-table-column prop="borrow_count" label="借用数量" align="center" width="150">
                                <template #default="{ row }">
                                    <el-input-number v-model="row.borrow_count" :disabled="isView" :min="1" :max="999" size="small" />
                                </template>
                            </el-table-column>
                            <el-table-column prop="brand" label="品牌" align="center" />
                            <el-table-column prop="model" label="现货型号" align="center" />
                            <el-table-column prop="warehouse" label="存放仓库" align="center" />
                            <el-table-column label="操作" width="80" align="center">
                                <template #default="{ $index }">
                                    <el-button type="text" style="color: red" :disabled="isView" @click="handleRemove($index)">移除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-col>
                </el-row>
                <el-row :gutter="16" style="margin-top: 16px">
                    <el-col :span="24">
                        <div style="font-weight: bold; margin-bottom: 8px">配件信息</div>
                        <el-input v-model="form.accessories" :disabled="isView" type="textarea" :placeholder="isView?'':'请输入配件信息'" />
                    </el-col>
                    <el-col :span="24" style="margin-top: 16px">
                        <div style="font-weight: bold; margin-bottom: 8px">备注</div>
                        <el-input v-model="remark" type="textarea" :disabled="isView" :placeholder="isView?'':'请输入备注'" />
                    </el-col>
                </el-row>
                <el-row :gutter="16" style="margin-top: 16px">
                    <el-col :span="24">
                      <div style="font-weight: bold; margin-bottom: 8px">异常记录 <span>{{ 
                          abnormalList?.length ? 
                          abnormalList.reduce((sum, item) => sum + (Number(item?.condition) || 0), 0)
                          : 0 
                        }}</span> 次</div>
                        <el-table v-if="abnormalList.length > 0" :data="abnormalList" border style="width: 100%">
                          <!-- <el-table-column type="index" label="序号" width="60" align="center" />
                            <el-table-column prop="application_no" label="借用单编号" align="center" /> -->
                            <el-table-column prop="operator_name" label="借用人" align="center" />
                            <el-table-column prop="user_code" label="学号" align="center" />
                            <el-table-column prop="emergency_phone" label="借用人电话" align="center" />
                           <!--  <el-table-column prop="time" label="发生时间" align="center" /> -->
                            <el-table-column prop="type" label="异常" align="center">
                                <template #default="{ row }">
                                    {{ row.type }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="condition" label="数量" align="center">
                              <template #default="{ row }">
                                {{ row.condition }}
                              </template>
                            </el-table-column>
                        </el-table>
                    </el-col>
                </el-row>
            </el-form>
        </el-tab-pane>
        <el-tab-pane v-else label="设备清单" name="third">
            <el-form :model="form" label-width="110px">
                <el-row :gutter="16">
                    <el-col :span="24">
                        <div style="margin: 8px 0" v-if="!isView" >
                            <el-input :disabled="isView" v-model="returnSearchText" placeholder="请扫描设备条码添加" style="width: 300px" @keyup.enter="handleReturnScanSearch" />
                            <el-button type="primary" style="margin-left: 16px" @click="handleAdd" :disabled="isView">手动归还</el-button>
                        </div>
                        <el-table :data="returnDeviceList" border style="width: 100%" >
                            <!-- <el-table-column type="selection" width="55" align="center" />@selection-change="handleSelectionChange" -->
                            <el-table-column type="index" label="序号" width="60" align="center" />
                            <el-table-column prop="device_no" label="设备编号" align="center" />
                            <el-table-column prop="device_type" label="设备分类" align="center" />
                            <el-table-column prop="device_name" label="设备名称" align="center" />
                            <el-table-column prop="borrow_count" label="借用数量" align="center" width="150">
                                <template #default="{ row }">
                                    <el-input-number v-model="row.borrow_count" :min="1" :max="999" size="small" :disabled="true" />
                                </template>
                            </el-table-column>
                            <el-table-column prop="brand" label="品牌" align="center" />
                            <el-table-column prop="model" label="规格型号" align="center" />
                            <el-table-column prop="warehouse" label="存放仓库" align="center" />
                            <el-table-column prop="status" label="状态" align="center">
                                <template #default="{ row }">
                                  {{ row.return_status.label }}
                                   <!--  <el-tag v-if="!isView" :type="row.status === '已归还' ? 'success' : 'warning'">{{ row.status }}</el-tag>
                                    <el-tag v-else-if="['已领取', '已归还'].includes(form.status_label)">{{ form.status_label }}</el-tag> -->
                                    <!-- <span v-else>{{ form.status_label }}</span> -->
                                </template>
                            </el-table-column>
                            <el-table-column prop="status" label="归还时间" align="center">
                              <template #default="{ row }">
                                {{ row.return_time ? dayjs(row.return_time).format('YYYY-MM-DD HH:mm:ss') : (row.return_status?.label === '已归还' ? dayjs().format('YYYY-MM-DD HH:mm:ss') : '') }}
                              </template>
                            </el-table-column>
                            <el-table-column label="操作" width="150" align="center">
                                <template #default="{ $index,row }">
                                 
                                  <el-button :disabled="isView" type="text" style="color: red"  
                                   v-if="!isView && (!returnDeviceList[$index]?.condition || returnDeviceList[$index]?.photos?.length==0)&& row.problem_records?.length ==0"
                                  @click="handleAbnormal($index)">异常操作</el-button>
                                  <el-button 
                                    
                                    type="text" 
                                    style="color: #409EFF" 
                                    @click="handleViewAbnormal($index)"
                                    v-if="row.problem_records?.length || (returnDeviceList[$index]?.condition || returnDeviceList[$index]?.photos?.length)"
                                  >查看异常</el-button>
                                    <!-- <el-button type="text" v-if="!isView" :disabled="isView" style="color: red" @click="handleReturnRemove($index)">移除</el-button> -->
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-col>
                </el-row>
                <el-row :gutter="16" style="margin-top: 16px">
                    <el-col :span="16">
                        <div style="font-weight: bold; margin-bottom: 8px">配件信息</div>
                        <el-input v-model="form.accessories" :disabled="isView" :placeholder="isView?'':'请输入配件信息'" />
                    </el-col>
                    <el-col :span="8">
                        <div style="font-weight: bold; margin-bottom: 8px">当前状态</div>
                        <el-input v-model="returnStatus" v-if="!isView"  :disabled="true" placeholder="" style="width: 150px" />
                        <el-input value="已归还" v-else  :disabled="true" placeholder="" style="width: 150px" />
                      <el-button type="primary" v-if="!isView"  style="margin-left: 16px" @click="clickReturn"
                       :disabled="returnStatus=='已归还'||isView">归还</el-button>
                    </el-col>
                    <el-col :span="24" style="margin-top: 16px">
                        <div style="font-weight: bold; margin-bottom: 8px">备注</div>
                        <el-input v-model="returnRemark" type="textarea" :disabled="isView" :placeholder="isView?'':'请输入备注'" />
                    </el-col>
                </el-row>
                <el-row :gutter="16" style="margin-top: 16px">
                    <el-col :span="24">
                        <div style="font-weight: bold; margin-bottom: 8px">异常记录 <span>{{ 
                          returnAbnormalList?.length ? 
                          returnAbnormalList.reduce((sum, item) => sum + (Number(item?.condition) || 0), 0)
                          : 0 
                        }}</span> 次</div>
                        <el-table v-if="returnAbnormalList?.length > 0" :data="returnAbnormalList" border style="width: 100%">
                           <!--  <el-table-column type="index" label="序号" width="60" align="center" />
                            <el-table-column prop="application_no" label="借用单编号" align="center" /> -->
                            <el-table-column prop="operator_name" label="借用人" align="center" />
                            <el-table-column prop="user_code" label="学号" align="center" />
                            <el-table-column prop="emergency_phone" label="借用人电话" align="center" />
                           <!--  <el-table-column prop="time" label="发生时间" align="center" /> -->
                            <el-table-column prop="type" label="异常" align="center">
                                <template #default="{ row }">
                                    {{ row.type }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="condition" label="数量" align="center">
                              <template #default="{ row }">
                                {{ row.condition }}
                              </template>
                            </el-table-column>
                        </el-table>
                    </el-col>
                </el-row>
            </el-form>
        </el-tab-pane>
        </el-tabs>
		<template #footer>
			<el-button @click="onCancel">关闭</el-button>
			<el-button type="primary" @click="onSubmit" v-if="!isView"> {{ isCollect ? '提交' : '确认' }}</el-button>
		</template>
	</el-dialog>
	<SelectDeviceDialog 
    v-model:visible="showSelectDeviceDialog"  
    @confirm="onDeviceSelected" 
    :device-ids="returnDeviceList.filter(item => item.return_status.label !== '已归还').map(item => item.device_no)"
/>
	<SettlementDialog v-model:visible="showSettlementDialog" :settlement-data="settlementData" />
    <AbnormalDialog v-model:visible="showAbnormalDialog" @confirm="onAbnormalConfirm" />
    <ViewAbnormalDialog 
      v-model:visible="showViewAbnormalDialog" 
      :abnormal-data="currentAbnormalData" 
    />
</template>

<script setup lang="ts">
import { ref, watch, defineProps, defineEmits, onMounted, computed, nextTick } from 'vue';
import SelectDeviceDialog from './SelectDeviceDialog/index.vue';
import SettlementDialog from './SettlementDialog.vue';
import AbnormalDialog from './AbnormalDialog/index.vue';
import ViewAbnormalDialog from './ViewAbnormalDialog/index.vue';
import dayjs from 'dayjs';
import { ElMessage } from 'element-plus';
import * as api from '../../api';
import * as deviceApi from '../../../device/api';
import { CollectEquipment, ReturnEquipment } from '../../api';
import type { TabsPaneContext } from 'element-plus';
import { getUserInfo } from '../../../login/api';


/* 获取管理员列表 */
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 api.GetAllUser();
	allUserList.value = res.data;
	// 设置默认选择第一个用户
	if (allUserList.value.length > 0) {
		form.value.app_user_borrower = allUserList.value[0].id;
	}
	console.log("allUserList.value:::",allUserList.value)	
}

interface ApiResponse {
  code: number;
  data?: any;
  message?: string;
}

// 定义接口
interface Device {
  id: string | number;
  category_name: string;
  name?: string;
  brand?: string;
  model?: string;
  warehouse: string;
  device_specification?: string;
  device_name?: string;
}

interface DeviceListItem {
  device_no: string | number;
  device_type: string;
  device_name?: string;  // 改为可选
  borrow_count: number;
  brand: string;
  model?: string;  // 改为可选
  warehouse: string;
  status?: string;
  condition?: string;
  photos?: Array<{
    filename: string;
    data: string;
  }>;
  device_specification?: string;
}

interface FormItem {
  device: string | number;
  remark: string;
  quantity: number;
  location: string;
  device_name?: string;
  device_specification?: string;
  condition?: string;
  photos?: Array<{
    filename: string;
    data: string;
  }>;
}

interface FormData {
  application_no: string;
  emergency_contact: string;
  emergency_phone: string;
  app_user_borrower: number;
  team_type: number;
  team_members_count: number;
  team_members: string;
  expected_start_time: string;
  expected_end_time: string;
  borrower_dept: string;
  purpose: string;
  applicant_remark_type: string;
  applicant_remark: string;
  items: FormItem[];
  accessory_info: string;
  borrow_type: number;
  return_location: string;
  status_label?: string;
  id?: number;
  records?: any[];
  borrower_info?: {
    user_code: string;
  };
  borrower_damage_count?: number;
  accessories?: string;
}

interface AbnormalData {
  condition: string;
  photos: Array<{
    filename: string;
    data: string;
  }>;
}

interface AbnormalRecord {
  application_no: string;
  operator_name: string;
  user_code: string;
  emergency_phone: string;
  type: '损坏' | '逾期';
  condition: number;
  create_time: string;
}

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 isCollect = computed(() => props.modelValue?.mode === 'collect');
const isReturn = computed(() => props.modelValue?.mode === 'return');

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

const timeline = ref({
  create: '',
  approve: '',
  approver: ''
});
// const activeStep = ref(1);

const activeName = ref('first');
const returnStatus = ref('未归还'); // 添加独立的状态变量

// 借用列表相关数据
const searchText = ref('');
const deviceList = ref<DeviceListItem[]>([]);
const accessoryInfo = ref('');
const remark = ref('');

// 归还设备相关数据
const returnSearchText = ref('');
const returnDeviceList = ref<DeviceListItem[]>([]);
const returnAccessoryInfo = ref('');
const returnRemark = ref('');
const selectedDevices = ref<DeviceListItem[]>([]); // 添加选中设备列表

//审批步骤
const steps = ref<any[]>([]);

// 添加结算单相关的状态
const showSettlementDialog = ref(false);
const settlementData = ref<any>(null);

// 添加异常操作相关的状态
const showAbnormalDialog = ref(false);
const currentAbnormalIndex = ref(-1);

// 添加查看异常相关的状态
const showViewAbnormalDialog = ref(false);
const currentAbnormalData = ref<AbnormalData>({
  condition: '',
  photos: []
});

//审批
function buildSteps(data: any) {
  steps.value = [
    {
      title: '创建申请',
      description: `创建时间：${data.create_datetime}`,
      status: 'finish'
    },
    {
      title: '待审批',
      description: '待超级管理员审批',
      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) {
    steps.value.push({
      title: '审批通过',
      description: `审批人：${approverinfo.name}，时间：${data.approve_time}`,
      status: 'finish'
    });
  } else if (data.status === 3) {
    // console.log("data.approver_name:::",data.approver_info.name)
    steps.value.push({
      title: '审批拒绝',
      description: `审批人：${approverinfo.name}，拒绝原因: ${data.approve_remark},时间：${data.approve_time}`,
      status: 'error'
    });
  }

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

// 处理异常操作
const handleAbnormal = (index: number) => {
  currentAbnormalIndex.value = index;
  showAbnormalDialog.value = true;
  console.log("showAbnormalDialog:::", showAbnormalDialog.value, "currentAbnormalIndex:::", currentAbnormalIndex.value);
};

// 处理异常操作确认
const onAbnormalConfirm = (data: { condition: string; photos: any[] }) => {
  console.log("异常操作确认数据：", data);
  if (currentAbnormalIndex.value !== -1) {
    const device = returnDeviceList.value[currentAbnormalIndex.value];
    device.condition = data.condition;
    device.photos = data.photos;
    ElMessage.success('异常信息已保存');
  }
};

// 处理查看异常
const handleViewAbnormal = (index: number) => {
  const device = returnDeviceList.value[index];
  console.log("device:::",device);
  if (device) {
    if(device.problem_records?.length){
      currentAbnormalData.value = {
        condition: device.problem_records?.[0].device_condition_after ||'',
        photos: device.problem_records?.[0].returned_images.map((item:any)=>item.image_url) ||[]
      };
    }else{
      currentAbnormalData.value = {
        condition: device.condition ||'',
        photos: device.photos ||[]
      };
    }
    showViewAbnormalDialog.value = true;
  }
};

// 处理扫码搜索
const handleScanSearch = async () => {
    if (!searchText.value.trim()) return;
    
    try {
        const res = await deviceApi.GetList({ 
            page: 1, 
            limit: 1, 
            code: searchText.value.trim(),
            status: 1 
        });
        
        if (res.data && res.data.length > 0) {
            const device = res.data[0];
            if (device.available_quantity <= 0) {
                ElMessage.warning('该设备当前无可用数量');
                return;
            }
            
            // 检查是否已存在
            const existingDevice = deviceList.value.find(d => d.device_no === device.id);
            if (existingDevice) {
                existingDevice.borrow_count++;
                ElMessage.success('设备数量已更新');
            } else {
                // 添加新设备到列表
                deviceList.value.push({
                    device_no: device.id,
                    device_type: device.category_name,
                    device_name: device.name || '',
                    borrow_count: 1,
                    brand: device.brand || '',
                    model: device.model || '',
                    warehouse: device.warehouse
                });
                ElMessage.success('设备已添加到列表');
            }
        } else {
            ElMessage.warning('未找到对应的设备');
        }
    } catch (error) {
        ElMessage.error('搜索设备失败');
    } finally {
        searchText.value = ''; // 清空搜索框
    }
};

// 处理归还扫码搜索
const handleReturnScanSearch = async () => {
    if (!returnSearchText.value.trim()) return;
    
    try {
        const res = await deviceApi.GetList({ 
            page: 1, 
            limit: 1, 
            code: returnSearchText.value.trim(),
            status: 1 
        });
        
        if (res.data && res.data.length > 0) {
            const device = res.data[0];
            
            // 检查是否已存在
            const existingDeviceIndex = returnDeviceList.value.findIndex(d => d.device_no === device.id);
            if (existingDeviceIndex !== -1) {
                // 如果设备已存在，更新其状态
                returnDeviceList.value[existingDeviceIndex].status = '已归还';
                ElMessage.success(`设备 ${device.category_name} 状态已更新为已归还`);
            } else {
                // 添加新设备到列表
                returnDeviceList.value.push({
                    device_no: device.id,
                    device_type: device.category_name,
                    device_name: device.name || '',
                    borrow_count: 1,
                    brand: device.brand || '',
                    model: device.model || '',
                    warehouse: device.warehouse,
                    return_status:device.return_status,
                    return_time:device.return_times
                });
                ElMessage.success('设备已添加到列表');
            }
        } else {
            ElMessage.warning('未找到对应的设备');
        }
    } catch (error) {
        ElMessage.error('搜索设备失败');
    } finally {
        returnSearchText.value = ''; // 清空搜索框
    }
};

// 异常记录列表数据
const abnormalList = ref([
    /* {
        borrowNo: '202409002',
        borrower: '张同学',
        time: '2024-09-12 10:21:32',
        type: '逾期'
    },
    {
        borrowNo: '202505013',
        borrower: '张同学',
        time: '2025-05-13 15:12:35',
        type: '损坏'
    } */
]);
/* 归还设备异常记录 */
const returnAbnormalList = ref([
    
]);

// 查看异常记录详情
const handleView = (row: any) => {
    console.log('查看异常记录:', row);
    // 这里可以添加查看详情的逻辑
};

// 借用列表相关方法
const handleAdd = () => {
  showSelectDeviceDialog.value = true;
};

const handleRemove = (index: number) => {
  deviceList.value.splice(index, 1);
};
const handleReturnRemove = (index: number) => {
  returnDeviceList.value.splice(index, 1);
};

// 处理表格多选变化
const handleSelectionChange = (selection: DeviceListItem[]) => {
  selectedDevices.value = selection;
};

// 设备选择处理
function onDeviceSelected(devices: Device[]) {
  console.log("devices:::",devices,"activeName:::",activeName.value);
  if (activeName.value === 'first') {
    form.value.items.push(
      ...devices.map((d) => ({
        device: d.id,
        remark: d.category_name,
        quantity: 1,
        location: d.warehouse,
        device_name: d.name,
        device_specification: d.device_specification
      }))
    );
  } else if (activeName.value === 'second') {
    deviceList.value.push(
      ...devices.map(d => ({
        device_no: d.id,
        device_type: d.category_name,
        device_name: d.name || '',
        borrow_count: 1,
        brand: d.brand || '',
        model: d.model,
        device_specification: d.device_specification,
        warehouse: d.warehouse
      }))
    );
  }else if(activeName.value === 'third'){
    // 在添加前检查每个设备是否已存在
    devices.forEach(d => {
      const existingDeviceIndex = returnDeviceList.value.findIndex(item => item.device_no === d.id);
      if (existingDeviceIndex !== -1) {
        // 如果设备已存在，更新其状态
        returnDeviceList.value[existingDeviceIndex].return_status.value = 2;
        returnDeviceList.value[existingDeviceIndex].return_status.label = '已归还';
        returnDeviceList.value[existingDeviceIndex].is_return = true;
        returnDeviceList.value[existingDeviceIndex].return_time = dayjs().format('YYYY-MM-DD HH:mm:ss');
        ElMessage.success(`设备 ${d.category_name} 状态已更新为已归还`);
      } else {
        // 如果设备不存在，添加新记录
        /* returnDeviceList.value.push({
          device_no: d.id,
          device_type: d.category_name,
          device_name: d.name || '',
          borrow_count: 1,
          brand: d.brand || '',
          model: d.model || '',
          warehouse: d.warehouse,
          status: '已归还'
        }); */
        /* ElMessage.success(`设备 ${d.category_name} 已添加到归还列表`); */
      }
    });
  }
}

// 移除同步相关的 watch
// const handleClick = (tab: TabsPaneContext, event: Event) => {
//   if (tab.props.name === 'second') {
//     deviceList.value = form.value.items.map(item => ({
//       device_no: item.device,
//       device_type: item.remark,
//       device_name: '',
//       borrow_count: item.quantity,
//       brand: '',
//       model: '',
//       warehouse: item.location
//     }));
//   }
// }

function handleClick(tab: TabsPaneContext) {
  console.log('Tab clicked:', tab.props.name);
}

function handleUploadSuccess(response: any, file: any, fileList: any) {
	// eslint-disable-next-line no-console
  console.log('上传成功:', file.name);
}

function handleUploadError(err: any, file: any, fileList: any) {
	// eslint-disable-next-line no-console
  console.error('上传失败:', file.name);
}


const form = ref<FormData>({
  borrower_info:{
    user_code:'',
    mobile:''
  },
	application_no: '',
	emergency_contact: '',
	emergency_phone: '',
	app_user_borrower: 1,
	team_type: 0,
	team_members_count: 1,
	team_members: '',
	expected_start_time:'',
	expected_end_time: '',
	borrower_dept: '',
	purpose: '',
	applicant_remark_type: "1",
	applicant_remark: '',
	items: [],
	accessory_info: '',
	borrow_type: 2,
	return_location:''
});
const showSelectDeviceDialog = ref(false);


const rules = {
  emergency_contact: [
    { required: true, message: '请输入借用人', trigger: 'change' },
  ],
  app_user_borrower: [
    { required: true, message: '请输入学号或工号', trigger: 'change' },
  ],
  emergency_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(() => {
	getAdminList()
	getAllUserList()
	try {
		const userInfo = JSON.parse(sessionStorage.getItem('userInfo') || '{}');
		if (userInfo) {
			form.value.emergency_contact = userInfo.username || '';
			form.value.app_user_borrower = Number(userInfo.dept_info?.dept_id )|| 1;
			form.value.emergency_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) => {
  if (val && val.id) {
			try {
			const res = await api.GetApplicationDetail(val.id);
      console.log("res:::::",res)
			if (res.code === 2000 && res.data) {
				const data = res.data;
				Object.assign(form.value, data);
        buildSteps(data);
				timeline.value.create = data.create_datetime || '';
				timeline.value.approve = data.approve_time || '';
        const approverinfo = data.approver_info ?? data.admin_approver_info
        timeline.value.approver = approverinfo?.name || '审批人'

				// timeline.value.approver = data.admin_approver_info?.name || '审批人';
                // console.log("data:::",form.value);
				// activeStep.value = 1; // 创建
				// if (data.status >= 1) activeStep.value = 2; // 待审批
				// if (data.status >= 2) activeStep.value = 3; // 审批通过
				// if (data.status >= 3) activeStep.value = 4; // 完成

                // 同步 form.items 到 returnDeviceList
                if (form.value.items && form.value.items.length > 0) {
                    returnDeviceList.value = form.value.items
                        .filter(item => item.device !== null)
                        .map(item => ({
                            device_no: item.device,
                            device_type: item.remark,
                            device_name: item.device_name,
                            borrow_count: item.quantity,
                            brand: '',
                            model: item.device_specification,
                            warehouse: item.location,
                            problem_records: item.problem_records,
                            /* status: '未归还' */
                            return_status:item.return_status,
                            return_time:item.return_times
                        }));
                }
                // 同步 form.records 到 returnAbnormalList
                if (form.value.records && form.value.records.length > 0) {
                    // 添加损坏类型记录
                    const damageRecord: AbnormalRecord = {
                        application_no: form.value.application_no,
                        operator_name: form.value.external_borrower_name||form.value.app_user_borrower?.name||'',
                        user_code: form.value.borrower_info?.user_code || form.value.app_user_borrower?.user_code||'',
                        emergency_phone: form.value.external_borrower_phone || form.value.app_user_borrower?.mobile||'',
                        type: '损坏',
                        condition: form.value.borrower_damage_count || 0,
                        create_time: dayjs().format('YYYY-MM-DD HH:mm:ss')
                    };

                    // 添加逾期类型记录
                    const overdueRecord: AbnormalRecord = {
                        application_no: form.value.application_no,
                        operator_name: form.value.external_borrower_name||form.value.app_user_borrower?.name||'',
                        user_code: form.value.borrower_info?.user_code || form.value.app_user_borrower?.user_code||'',
                        emergency_phone: form.value.external_borrower_phone || form.value.app_user_borrower?.mobile||'',
                        type: '逾期',
                        condition: form.value.borrower_overdue_count || 0, // 逾期数量设为1
                        create_time: dayjs().format('YYYY-MM-DD HH:mm:ss')
                    };

                    returnAbnormalList.value = [damageRecord, overdueRecord];
                    abnormalList.value = [damageRecord, overdueRecord];
                }
			}
			} catch (e) {
        console.log("审判失败:::",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;
				Object.assign(form.value, data);

                // 同步 form.items 到 returnDeviceList
                if (form.value.items && form.value.items.length > 0) {
                    returnDeviceList.value = form.value.items
                        .filter(item => item.device !== null)
                        .map(item => ({
                            device_no: item.device,
                            device_type: item.remark,
                            device_name: item.device_name,
                            borrow_count: item.quantity,
                            brand: '',
                            model: item.device_specification,
                            warehouse: item.location,
                            problem_records: item.problem_records,
                            return_status:item.return_status,
                            return_time:item.return_times
                        }));
                }
			}
			} catch (e) {
			ElMessage.error('获取审批信息失败');
			}
	}
}, { immediate: true });


// watch(
// 	() => props.modelValue,
// 	(v) => {
// 		if (v) {
// 			// eslint-disable-next-line no-console
// 			console.log("val:::::",v);
// 			Object.assign(form.value, v);
// 		}
// 	}, { 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 || '';
    }
  }
});
function addItem() {
	showSelectDeviceDialog.value = true;
}
function removeItem(index: number) {
	form.value.items.splice(index, 1);
}
function onCancel() {
    // 重置标签页到第一个
    activeName.value = 'first';
    // 清理异常记录列表
    returnAbnormalList.value = [];
    abnormalList.value = [];
    // 清理设备列表
    deviceList.value = [];
    returnDeviceList.value = [];
    // 清理搜索框
    searchText.value = '';
    returnSearchText.value = '';
    // 清理备注
    remark.value = '';
    returnRemark.value = '';
    // 重置状态
    returnStatus.value = '未归还';
    // 清理选中的设备
    selectedDevices.value = [];
    // 关闭所有对话框
    showSelectDeviceDialog.value = false;
    showSettlementDialog.value = false;
    showAbnormalDialog.value = false;
    showViewAbnormalDialog.value = false;
    // 重置当前异常数据
    currentAbnormalData.value = {
        condition: '',
        photos: []
    };
    // 发出关闭事件
    emit('update:visible', false);
}
// 提交时合并数据
function onSubmit() {
  if(isCollect.value){
    // 验证是否有设备信息
    const hasDevicesInFirstTab = form.value.items && form.value.items.length > 0;
    const hasDevicesInSecondTab = deviceList.value && deviceList.value.length > 0;
    
    if (!hasDevicesInFirstTab && !hasDevicesInSecondTab) {
      ElMessage.warning('请添加设备信息后再提交');
      activeName.value = 'second'; // 自动切换到借用列表标签页
      return;
    }

    // 验证设备数量
    const hasInvalidQuantityInFirstTab = form.value.items.some(item => !item.quantity || item.quantity <= 0);
    const hasInvalidQuantityInSecondTab = deviceList.value.some(item => !item.borrow_count || item.borrow_count <= 0);

    if (hasInvalidQuantityInFirstTab || hasInvalidQuantityInSecondTab) {
      ElMessage.warning('请确保所有设备的数量大于0');
      activeName.value = 'second'; // 自动切换到借用列表标签页
      return;
    }

    // 合并两个标签页的设备数据
    const allDevices = [
      ...deviceList.value.map(item => ({
        condition: remark.value,
        quantity: item.borrow_count,
        device_id: Number(item.device_no) || 0
      }))
    ];
    
    const submitData = {
        id:form.value.id,
        item_id:form.value.id,
        device_assignments: allDevices,
        remark:remark.value,
        accessories:form.value.accessories,
    };

    CollectEquipment(submitData).then((res: ApiResponse) => {
      if(res.code===2000){
        ElMessage.success("领取成功");
        // 准备结算单数据
        settlementData.value = {
          ...form.value,
          items: deviceList.value.map(item => ({
            ...item,
            device_category_name: item.device_type,
            device_name: item.device_name,
            device_specification: item.device_specification,
            device_storage_location: item.warehouse,
            remark: item.device_type,
            quantity: item.borrow_count,
            device_id: item.device_no,
            device_category: item.device_type,
            device_code: item.device_no,
            borrow_type: form.value.borrow_type,
            borrower_dept: form.value.borrower_dept,
            emergency_contact: form.value.emergency_contact,
            emergency_phone: form.value.emergency_phone,
            team_type: form.value.team_type,
          })),
          accessory_info: accessoryInfo.value,
          remark: remark.value,
          expected_start_time: dayjs().format('YYYY-MM-DD HH:mm:ss')
        };
        
        // 先触发提交事件进行页面刷新
        emit('submit');
        
        // 关闭当前对话框
        emit('update:visible', false);
        
        // 使用 nextTick 确保在 DOM 更新后再显示结算单
        nextTick(() => {
          showSettlementDialog.value = true;
        });
      }
    });
  } else {
    // 归还逻辑修改
    // 使用所有设备列表而不是选中的设备
    const allDevices = returnDeviceList.value
  .filter(item => item.is_return === true)  // 只选择 return_status 为 2 的设备
  .map(item => ({
      device: item.device_no,
      quantity: item.borrow_count,
      remark: returnRemark.value,
      device_id: Number(item.device_no) || 0,
       // 添加异常相关字段
       condition: item.condition, // 异常说明
       photo_urls: item.photos || [], // 异常照片
    }));
    
    const submitData = {
      id: form.value.id,
      items: allDevices,
      status: returnStatus.value,
      accessories: form.value.accessories,
    };
    
    ReturnEquipment(submitData).then(async (res: ApiResponse) => {
      if(res.code===2000){
        ElMessage.success("归还成功");
        try {
          if (form.value.id) {
            const detailRes = await api.GetApplicationDetail(form.value.id);
            if (detailRes.code === 2000 && detailRes.data) {
              returnStatus.value = detailRes.data.status_label || returnStatus.value;
            }
          }
        } catch (e) {
          ElMessage.error('获取最新状态失败');
        }
        emit('submit');
        emit('update:visible', false);
      }
    });
  }
}

function clickReturn(){
  returnStatus.value = '已归还';
  // 自动选择所有设备
  const tableRef = document.querySelector('.el-table__header-wrapper th.el-table__cell.is-leaf .el-checkbox');
  if (tableRef) {
    (tableRef as HTMLElement).click();
  }
}

	/* 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.team_members_count)||1;
			emit('submit', { ...form.value });
			emit('update:visible', false);
			ElMessage.success("添加成功！");
		}
	}); */
	

</script>
