<template>
  <div id="PrintElementOptionSetting" style="display:none;"></div>
  <div id="BarcodePrintElementOptionSetting" style="display:none;"></div>

  <!-- 添加全屏加载遮罩 -->
  <div
v-loading.fullscreen.lock="fullscreenLoading" 
       element-loading-text="正在导入数据，请勿关闭页面..."
       element-loading-background="rgba(0, 0, 0, 0.8)">
  </div>

  <ContentWrap style="height: 120px; display: flex; align-items: center; padding: 20px 0;">
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
      style="width: 100%;"
    >
      <el-form-item label="体检编号" prop="medicalSn">
        <el-input
          v-model="queryParams.medicalSn"
          placeholder="请输入体检编号"
          clearable
          class="!w-200px"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="pname">
        <el-input
          v-model="queryParams.pname"
          placeholder="请输入姓名"
          clearable
          class="!w-200px"
        />
      </el-form-item>
      <el-form-item label="身份证号" prop="cardId">
        <el-input
          v-model="queryParams.cardId"
          placeholder="请输入身份证号"
          clearable
          class="!w-200px"
        />
      </el-form-item>
      <el-form-item  prop="cardId">
        <IDCardReader 
          v-model:cardId="queryParams.cardId" 
          @success="handleIdCardSuccess"
        />
      </el-form-item>
      <el-form-item label="打印日期" prop="printTimeRange">
        <el-date-picker
          v-model="queryParams.printTimeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD HH:mm:ss"
          class="!w-300px"
          @change="handleDateChange"
        />
      </el-form-item>
      <el-form-item label="状态" prop="isprint">
        <el-select v-model="queryParams.isprint" placeholder="请选择状态" clearable class="!w-200px">
          <el-option label="已打印" value="1" />
          <el-option label="未打印" value="0" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 查询
        </el-button>
        <el-button type="success" :loading="importLoading" @click="handleImport">
          <Icon icon="ep:upload" class="mr-5px" /> 导入Excel文件  
        </el-button>
        <el-button type="primary" @click="handleAdd()">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <input
          type="file"
          ref="fileInputRef"
          accept=".xlsx,.xls" 
          style="display: none"
          @change="uploadFile"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleExport">
          <Icon icon="ep:download" class="mr-5px" /> 导出Excel
        </el-button>
      </el-form-item>
      
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      :header-cell-style="{ background: 'rgb(235, 241, 250)', height: '56px',color:'#333333' }"
      :row-style="{ height: '56px' }"
    >
      <el-table-column label="体检编号" align="center" prop="medicalSn" />
      <el-table-column label="姓名" align="center" prop="pname" />
      <el-table-column label="性别" align="center" prop="gender" />
      <el-table-column label="身份证号" align="center" prop="cardId" />
      <el-table-column label="联系电话" align="center" prop="phoneNum" />
      <el-table-column label="住址" align="center" prop="domicileaddress" />
      <el-table-column label="状态" align="center" prop="isprint" :formatter="statusFormatter" />
      <el-table-column label="操作" align="center" fixed="right" width="240px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handlePrint(scope.row)"
          >
            打印导检单
          </el-button>
          <el-button
            link
            type="primary"
            @click="handlePrintBarcode(scope.row)"
          >
            打印条形码
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <DepartmentForm ref="formRef" @success="getList" />
  
  <!-- 新增信息对话框 -->
  <el-dialog
    v-model="dialogVisible"
    title="新增信息"
    width="700px"
    :close-on-click-modal="false"
  >
    <el-form
      :model="addForm"
      ref="addFormRef"
      label-width="100px"
      :rules="addFormRules"
    >
      <el-form-item label="姓名" prop="name">
        <el-input v-model="addForm.name" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="身份证号" prop="cardId">
        <div style="display: flex; align-items: center;">
          <el-input v-model="addForm.cardId" placeholder="请输入身份证号" @blur="handleCardIdBlur" style="width: 75%;" />
          <el-button type="primary" @click="handleGwPatientInfo" style="margin-left: 10px;">获取公卫患者信息</el-button>
          <el-button type="primary" @click="handleReadIdCard" style="margin-left: 10px;">读取身份证</el-button>
        </div>
      </el-form-item>
      <el-form-item label="出生日期" prop="birthDate">
        <el-date-picker
          v-model="addForm.birthDate"
          type="date"
          placeholder="根据身份证自动生成"
          style="width: 100%"
          disabled
        />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-input v-model="addForm.gender" placeholder="根据身份证自动生成" disabled />
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="addForm.phone" placeholder="请输入联系电话" />
      </el-form-item>
      <el-form-item label="住址" prop="address">
        <el-input v-model="addForm.address" placeholder="请输入住址" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { PatientApi, type PatientVO } from '@/api/inspect/inspectpatient'
import * as SummaryApi from "@/api/summary";
import { newHiprintPrintTemplate } from "@/views/summary/utils/template-helper";
import template from "@/views/summary/print/template";
import barcode from "@/views/summary/print/barcode";
import IDCardReader from '@/components/IDCardReader.vue';
import sdk from '@/components/IDCardReader/sdk';
import download from '@/utils/download'  // 添加下载工具导入
import { ElMessageBox } from 'element-plus'  // 添加 ElMessageBox 导入
import { InspectOrgApi, InspectOrgVO } from '@/api/inspect/inspectorg/index'
import * as UserApi from '@/api/system/user'
import { getUserProfile } from '@/api/system/user/profile'

defineOptions({ name: 'Department' })

const message = useMessage() // 消息弹窗
const loading = ref(true) // 列表的加载中
const importLoading = ref(false) // 导入Excel的加载状态
const fullscreenLoading = ref(false) // 全屏加载状态
const exportLoading = ref(false) // 导出Excel的加载状态
const list = ref<PatientVO[]>([]) // 用于展示的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  medicalSn: undefined as string | undefined,
  pname: undefined as string | undefined,
  cardId: undefined as string | undefined,
  phoneNum: undefined as string | undefined,
  domicileaddress: undefined as string | undefined,
  isprint: undefined as string | undefined,
  printTimeRange: undefined as [string, string] | undefined
})
const queryFormRef = ref() // 搜索的表单
const fileInputRef = ref<HTMLInputElement | null>(null) // 文件输入引用
const idCardReading = ref(false) // 身份证读取状态

// 新增对话框相关变量
const dialogVisible = ref(false)
const addFormRef = ref()
const addForm = reactive({
  name: '',
  cardId: '',
  birthDate: '',
  gender: '',
  phone: '',
  address: ''
})

// 表单验证规则
const addFormRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  cardId: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  address: [{  message: '请输入住址', trigger: 'blur' }]
}

/** 获取列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await PatientApi.getPatientPage({
      ...queryParams,
      pName: queryParams.pname?.trim() || undefined,
      isprint: queryParams.isprint || undefined,
      printTimeRange: queryParams.printTimeRange
    })
    
    list.value = data.list
    total.value = data.total
  } catch (error) {
    console.error('查询出错:', error)
  } finally {
    loading.value = false
  }
}

/** 搜索操作 */
const handleQuery = () => {
  queryParams.pageNo = 1 // 重置页码到第一页
  getList()
}

/** 处理身份证读卡成功事件 */
const handleIdCardSuccess = (cardInfo) => {
  // 将身份证号赋值给搜索框
  queryParams.cardId = cardInfo.idNumber;
  // 执行查询操作
  handleQuery();
}

/** 添加/修改操作 */
const formRef = ref()
/** 初始化 **/
onMounted(() => {
  getList()
})

/** 打印报告按钮操作 */
const handlePrint = async (row: PatientVO) => {
  try {
    const patientInfo = await PatientApi.getPatientInfo(row.medicalSn)
    if (patientInfo.status == 1 && patientInfo.medicalDateTime) {
      const lastMedicalDate = new Date(patientInfo.medicalDateTime)
      const currentDate = new Date()
      // 计算日期之间的差距（毫秒）
      const timeDiff = currentDate.getTime() - lastMedicalDate.getTime()
      // 转换为天数
      const daysDiff = Math.floor(timeDiff / (1000 * 3600 * 24))
      // 如果不到365天（一年）
      if (daysDiff < 365) {
        // 显示警告消息
        message.error(`该患者上次体检距今不满一年`)
        return
      }
    }
    const userInfo = await getUserProfile()
    const deptInfo = await InspectOrgApi.getInspectOrg(userInfo.deptId)
    await PatientApi.updatePatientOrg(row.medicalSn,deptInfo.orgid,deptInfo.orgName)
    await PatientApi.bindPatientProject(row.medicalSn)
    await PatientApi.syncinspectApplyTj(row.medicalSn)
    await createPrint(row.medicalSn)
    // 打印完成后更新状态，添加当前时间戳
    await PatientApi.updatePrintStatus(row.medicalSn, new Date())
    await PatientApi.updateMedicalDateTime(row.medicalSn, new Date())
    // 刷新列表
    await getList()
    message.success('打印成功')
    // 更新患者补充信息
    PatientApi.updatePatientSupplement(row.medicalSn,row.cardId)
  } catch (error: any) {
    console.error('打印失败:', error)
    message.error(`打印失败: ${error.message || '未知错误'}`)
  }
}
/** 打印导检单 */
const createPrint = async (medicalSn) => {
  try {
    // 使用SummaryApi打印导检单
    const dataPrint = await SummaryApi.printInfoOfMedicalSn(medicalSn);
    // 创建打印模板 - 修改这里，使用固定的模板名称而不是动态获取
    const hiprintTemplate = newHiprintPrintTemplate("InspectionChecklist", {
      template: template,
      settingContainer: "#PrintElementOptionSetting",
    });
    // 打印设置
    const options = {leftOffset: -1, topOffset: -1};
    
    // 扩展配置
    const ext = {
      callback: () => {
      },
      styleHandler: () => {
        return "<style>.hiprint-printElement-text{color:black !important;}</style>";
      },
    };
    
    // 调用浏览器打印
    hiprintTemplate.print(dataPrint, options, ext);
  } catch (error: any) {
    console.error('打印导检单失败，详细错误:', error);
    message.error(`打印导检单失败: ${error.message || '未知错误'}`);
  }
}
/** 打印条形码 */
const handlePrintBarcode = async (row: PatientVO) => {
  try {
    // 获取最新的患者信息
    const patientInfo = await PatientApi.getPatientInfo(row.medicalSn)
    if (patientInfo.status == 1 && patientInfo.medicalDateTime) {
      const lastMedicalDate = new Date(patientInfo.medicalDateTime)
      const currentDate = new Date()
      // 计算日期之间的差距（毫秒）
      const timeDiff = currentDate.getTime() - lastMedicalDate.getTime()
      // 转换为天数
      const daysDiff = Math.floor(timeDiff / (1000 * 3600 * 24))
      // 如果不到365天（一年）
      if (daysDiff < 365) {
        // 显示警告消息
        message.error(`该患者上次体检距今不满一年`)
        return
      }
    }
    // 检查是否存在条形码打印时间
    if(patientInfo.barcodetime){
      // 格式化上次打印时间，显示中文年月日格式
      const date = new Date(patientInfo.barcodetime)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const lastPrintTime = `${year}年${month}月${day}日`

      // 格式化报告打印时间
      let reportPrintTime = ''
      if (patientInfo.medicalDateTime && patientInfo.status == 1) {
        const reportDate = new Date(patientInfo.medicalDateTime)
        const reportYear = reportDate.getFullYear()
        const reportMonth = String(reportDate.getMonth() + 1).padStart(2, '0')
        const reportDay = String(reportDate.getDate()).padStart(2, '0')
        reportPrintTime = `${reportYear}年${reportMonth}月${reportDay}日`
      }

      try {
        // 显示只有确定按钮的提示框
        await ElMessageBox.alert(
          `<div style="margin-bottom: 10px">该条形码已于 <span style="color: #f56c6c; font-weight: bold;">${lastPrintTime}</span> 打印。</div>` +
          (reportPrintTime ? `<div>该患者报告于 <span style="color: #f56c6c; font-weight: bold;">${reportPrintTime}</span> 打印。</div>` : ''),
          '提示',
          {
            confirmButtonText: '确定',
            type: 'warning',
            dangerouslyUseHTMLString: true
          }
        )
      } catch (error) {
        // 用户点击确定后继续执行
        console.log('用户确认重新打印')
      }
    }
    
    // 获取条形码数据
    const databarcodePrint = await PatientApi.GetbarcodeInfo(row.medicalSn)
    
    // 检查是否存在条形码数据
    if (!databarcodePrint || !databarcodePrint.barcodes || databarcodePrint.barcodes.length === 0) {
      message.warning('条形码不存在，无法打印')
      return
    }
    
    // 基础打印数据 - 患者基本信息
    const baseData = {
      patientName: databarcodePrint.name || row.pname,
      patientGender: databarcodePrint.gender || row.gender,
      patientAge: databarcodePrint.age || '',
      checkTypeId: '体检',
      sampleTypeId: '',
      sampleSource: '体检',
      billingTime: databarcodePrint.examinationDate || new Date().toLocaleDateString(),
      medicalSn: row.medicalSn
    };
    
    // 准备批量打印数据数组
    const batchPrintData: any[] = [];
    
    // 添加体检编号条码（第1页）
    batchPrintData.push({
      ...baseData,
      barCode: row.medicalSn,
      billingItem: '体检编号',
      checkTypeId: '体检',
      count: '1/4' // 页码标记
    });
    
    // 添加项目条码
    if (databarcodePrint.barcodes && databarcodePrint.barcodes.length > 0) {
      databarcodePrint.barcodes.forEach((item, index) => {
        // 处理项目名称
        let itemName = item.name || '检查项目';
        let checkType = itemName; // 默认检验类别与项目名称相同
        
        // 特殊情况处理：如果是"生化"
        if (itemName === '生化') {
          itemName = '生化全项';  // 项目名称显示为"生化全项"
          checkType = '生化';     // 但检验类别保持为"生化"
        }
        
        batchPrintData.push({
          ...baseData,
          barCode: item.code,
          billingItem: itemName,
          checkTypeId: checkType,
          count: `${index+2}/4` // 页码标记
        });
      });
    }
    // 创建打印模板
    const hiprintTemplate = newHiprintPrintTemplate("Barcode", {
      template: barcode,
      settingContainer: "#BarcodePrintElementOptionSetting",
    });
    
    // 打印设置 - 根据barcode.js的配置设置纸张大小和边距
    const options = {
      leftOffset: 0, 
      topOffset: 0,
      printMode: 'popup',
      paperType: 'A7',       // 纸张类型：A7
      height: 30,            // 纸张高度：30mm
      width: 50,             // 纸张宽度：50mm
      paperHeader: -6,       // 纸张上边距：-6mm
      paperFooter: 85.03937007874016  // 纸张下边距
    };
    
    // 增强样式
    const ext = {
      callback: () => {
      },
      styleHandler: () => {
        return `<style>
          /* 条形码打印特定样式 */
          @page {
            size: ${options.width}mm ${options.height}mm;
            margin: 0;
            @top-center { content: none; }
            @bottom-center { content: none; }
          }
          @media print {
            body {
              margin: 0;
              padding: 0;
            }
            .hiprint-printPanel {
              border: none !important;
              padding: 0 !important;
              margin: 0 !important;
            }
            /* 隐藏页眉页脚页码 */
            .hiprint-printPanel-header,
            .hiprint-printPanel-footer,
            .hiprint-printPanel-pageNumber {
              display: none !important;
            }
          }
        </style>`;
      },
    };
    
    // 执行批量打印 - 直接传入数组数据
    hiprintTemplate.print(batchPrintData, options, ext);
    
    // 打印成功后更新条形码打印时间
    await PatientApi.updateBarcodeTime(row.medicalSn, new Date())
    
    // 刷新列表
    await getList()
    message.success('打印成功')
  } catch (error: any) {
    console.error('打印条形码失败，详细错误:', error);
    message.error(`打印条形码失败: ${error.message || '未知错误'}`);
  }
}
/** 状态格式化 */
const statusFormatter = (row: any) => {
  return row.isprint === 1 ? '已打印' : '未打印'
}

/** 处理导入按钮点击 */
const handleImport = () => {
  fileInputRef.value?.click()
}

/** 处理文件上传 */
const uploadFile = async (event: Event) => {
  const target = event.target as HTMLInputElement
  if (!target.files || target.files.length === 0) {
    return
  }
  
  const file = target.files[0]
  if (!file.name.endsWith('.xlsx') && !file.name.endsWith('.xls')) {
    message.error('请上传Excel文件(.xlsx或.xls格式)')
    return
  }
  
  try {
    importLoading.value = true // 设置导入按钮加载状态为true
    fullscreenLoading.value = true // 设置全屏加载状态为true
    console.log('全屏加载状态已设置为:', fullscreenLoading.value) // 调试日志
    
    const formData = new FormData()
    formData.append('file', file)
    
    await PatientApi.uploadExcel(formData)
    message.success('导入成功')
    // 重置文件输入
    if (fileInputRef.value) {
      fileInputRef.value.value = ''
    }
    // 刷新列表
    await getList()
  } catch (error) {
    console.error('导入失败:', error)
    message.error('导入失败，请检查文件格式是否正确')
  } finally {
    importLoading.value = false // 设置导入按钮加载状态为false
    fullscreenLoading.value = false // 设置全屏加载状态为false
    console.log('全屏加载状态已重置为:', fullscreenLoading.value) // 调试日志
  }
}

// 处理新增按钮点击
const handleAdd = (row?: PatientVO) => {
  // 可以选择是否预填充一些数据
  dialogVisible.value = true
  
  // 如果传入了行数据，可以预填充表单
  if (row) {
    addForm.name = row.pname || ''
    addForm.cardId = row.cardId || ''
    addForm.gender = row.gender || ''
    addForm.phone = row.phoneNum || ''
    addForm.address = row.domicileaddress || ''
  }
}

// 提交表单
const submitForm = async () => {
  if (!addFormRef.value) return
  
  await addFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 调用API添加患者信息
        const patientData: Partial<PatientVO> = {
          pname: addForm.name,
          cardId: addForm.cardId,
          gender: addForm.gender,
          phoneNum: addForm.phone,
          domicileaddress: addForm.address,
          birthday: addForm.birthDate ? new Date(addForm.birthDate) : undefined
        }
        
        const data=await PatientApi.insertPatinetInfo(patientData as PatientVO)
        if(data){
          message.success('添加成功')
          dialogVisible.value = false
          // 重置表单
          resetForm()
          // 刷新列表
          await getList()
        }else{
          message.error('患者已存在')
        }
      } catch (error: any) {
        console.error('添加失败:', error)
        message.error('添加失败: ' + (error.message || '未知错误'))
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
  Object.assign(addForm, {
    name: '',
    cardId: '',
    birthDate: '',
    gender: '',
    phone: '',
    address: ''
  })
}

// 每次打开弹窗时清理之前的数据
watch(dialogVisible, (newVal) => {
  if (newVal) {
    // 弹窗打开时重置表单
    resetForm()
  }
})

// 处理身份证号失去焦点事件
const handleCardIdBlur = () => {
  const cardId = addForm.cardId
  if (cardId && (cardId.length === 15 || cardId.length === 18)) {
    try {
      // 提取出生日期
      let birthDateStr = ''
      if (cardId.length === 18) {
        birthDateStr = cardId.substring(6, 14)
        // 提取性别 - 18位身份证第17位，奇数为男，偶数为女
        const genderCode = parseInt(cardId.charAt(16))
        addForm.gender = genderCode % 2 === 1 ? '男' : '女'
      } else {
        // 15位身份证
        birthDateStr = '19' + cardId.substring(6, 12)
        // 提取性别 - 15位身份证第15位，奇数为男，偶数为女
        const genderCode = parseInt(cardId.charAt(14))
        addForm.gender = genderCode % 2 === 1 ? '男' : '女'
      }
      
      // 格式化日期 YYYYMMDD -> YYYY-MM-DD
      const year = birthDateStr.substring(0, 4)
      const month = birthDateStr.substring(4, 6)
      const day = birthDateStr.substring(6, 8)
      
      // 设置出生日期
      addForm.birthDate = `${year}-${month}-${day}`
    } catch (error: any) {
      console.error('解析身份证信息出错:', error)
      message.error('身份证号格式不正确，无法提取出生日期和性别')
    }
  } else if (cardId && cardId.length > 0) {
    message.warning('请输入15位或18位身份证号')
  }
}


// 处理获取公卫患者信息
const handleGwPatientInfo = async () => {
  if (!addForm.cardId) {
    message.warning('请先输入身份证号')
    return
  }
  
  try {
    loading.value = true
    // 调用API获取公卫患者信息
    const result = await PatientApi.getGwPatientInfo(addForm.cardId)
    if (result) {
      // 填充表单数据
      addForm.name = result.name || ''
      addForm.phone = result.telephone || ''
      addForm.address = result.addree || ''
      message.success('成功获取公卫患者信息')
    } else {
      message.warning('未找到该患者的公卫信息')
    }
  } catch (error: any) {
    message.error('获取公卫患者信息失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 处理读取身份证
const handleReadIdCard = async () => {
  if (idCardReading.value) {
    message.warning('正在读取身份证，请稍候...')
    return
  }
  
  idCardReading.value = true
  
  try {
    // 初始化SDK
    sdk.init_sdk()
    
    // 连接设备
    await sdk.open_device()
    message.success('读卡器连接成功')
    
    // 读取身份证信息
    const result = await sdk.read_card()
    
    if (result) {
      
      // 填充表单数据
      addForm.cardId = result.idNumber || ''
      addForm.name = result.name || ''
      addForm.address = result.address || ''
      
      // 设置性别
      addForm.gender = result.gender || ''
      
      // 设置出生日期
      if (result.birthday) {
        addForm.birthDate = result.birthday
      } else {
        // 如果没有生日信息，尝试从身份证号解析
        handleCardIdBlur()
      }
      
      message.success('读取身份证成功')
    } else {
      throw new Error('读取身份证失败')
    }
  } catch (error: any) {
    console.error('读卡失败:', error)
    message.error(error instanceof Error ? error.message : '读取身份证失败')
  } finally {
    // 无论成功或失败，都断开连接
    try {
      await sdk.close_device()
    } catch (e) {
      console.error('断开连接失败:', e)
    }
    
    idCardReading.value = false
  }
}

// 处理日期变化
const handleDateChange = (val: [string, string] | null) => {
  if (val) {
    // 设置开始时间为当天的 00:00:00
    const startTime = `${val[0].split(' ')[0]} 00:00:00`
    // 设置结束时间为当天的 23:59:59
    const endTime = `${val[1].split(' ')[0]} 23:59:59`
    queryParams.printTimeRange = [startTime, endTime]
  } else {
    queryParams.printTimeRange = undefined
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 使用 ElMessageBox 实现确认对话框
    await ElMessageBox.confirm(
      `是否导出当前<span style="color: #f56c6c; font-weight: bold; font-size: 18px;">${total.value}</span>条患者数据？`,
      '导出确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true  // 允许使用 HTML 标签
      }
    )
    // 发起导出
    exportLoading.value = true
    const data = await PatientApi.exportPatient({
      ...queryParams,
      pName: queryParams.pname?.trim() || undefined,
      isprint: queryParams.isprint || undefined,
      printTimeRange: queryParams.printTimeRange
    })
    download.excel(data, '患者信息.xls')
  } catch (error: any) {
    // 只有当错误不是用户取消操作时才显示错误提示
    if (error !== 'cancel') {
      console.error('导出失败:', error)
      message.error(`导出失败: ${error.message || '未知错误'}`)
    }
  } finally {
    exportLoading.value = false
  }
}
</script>
