<template>
  <div id="PrintElementOptionSetting" 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="handleQuery"
        />
      </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>
  </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="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handlePrint(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>
        </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 IDCardReader from '@/components/IDCardReader.vue';
defineOptions({ name: 'Department' })

const message = useMessage() // 消息弹窗
const loading = ref(true) // 列表的加载中
const importLoading = ref(false) // 导入Excel的加载状态
const fullscreenLoading = ref(false) // 全屏加载状态
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 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 formRef = ref()
/** 初始化 **/
onMounted(() => {
  getList()
})

/** 打印报告按钮操作 */
const handlePrint = async (row: PatientVO) => {
  try {
    await PatientApi.bindPatientProject(row.medicalSn)
    await PatientApi.syncinspectApplyTj(row.medicalSn)
    await createPrint(row.medicalSn)
    // 打印完成后更新状态，添加当前时间戳
    await PatientApi.updatePrintStatus(row.medicalSn, new Date())
    // 刷新列表
    await getList()
    message.success('打印成功')
  } catch (error: any) {
    console.error('打印失败:', error)
    message.error(`打印失败: ${error.message || '未知错误'}`)
  }
}
/** 打印导检单 */
const createPrint = async (medicalSn) => {
  try {
 
    // 使用SummaryApi打印导检单
    const dataPrint = await SummaryApi.printInfoOfMedicalSn(medicalSn);
    console.log('获取到的打印数据:', dataPrint);
    
    // 创建打印模板 - 修改这里，使用固定的模板名称而不是动态获取
    const hiprintTemplate = newHiprintPrintTemplate("InspectionChecklist", {
      template: template,
      settingContainer: "#PrintElementOptionSetting",
    });
    console.log('打印模板创建成功');
    
    // 打印设置
    const options = {leftOffset: -1, topOffset: -1};
    
    // 扩展配置
    const ext = {
      callback: () => {
        console.log("浏览器打印窗口已打开");
      },
      styleHandler: () => {
        return "<style>.hiprint-printElement-text{color:black !important;}</style>";
      },
    };
    
    // 调用浏览器打印
    hiprintTemplate.print(dataPrint, options, ext);
  } catch (error) {
    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) {
        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 = new Date(`${year}-${month}-${day}`)
    } catch (error) {
      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) {
    message.error('获取公卫患者信息失败: ' + (error.message || '未知错误'))
  } finally {
    loading.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
  }
}
</script>
