<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="登记来源" prop="regSource">
        <el-select
          v-model="queryParams.regSource"
          placeholder="请选择来源"
          clearable
          class="!w-200px"
        >
          <el-option label="门诊" value="门诊" />
          <el-option label="住院" value="住院" />
          <el-option label="体检" value="体检" />
        </el-select>
      </el-form-item>

      <el-form-item label="患者姓名" prop="pName">
        <el-input
          v-model="queryParams.pname"
          placeholder="请输入患者姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-150px"
        />
      </el-form-item>

      <el-form-item label="登记时间" prop="regDate">
        <el-date-picker
          v-model="queryParams.regDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-200px"
        />
      </el-form-item>
      <el-form-item label="分检时间" prop="sortDate">
        <el-date-picker
          v-model="queryParams.sortDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-200px"
        />
      </el-form-item>

      <el-form-item label="登记单号" prop="regId">
        <el-input
          v-model="queryParams.regId"
          placeholder="请输入登记单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-150px"
        />
      </el-form-item>

      <el-form-item label="检查单号" prop="examId">
        <el-input
          v-model="queryParams.examId"
          placeholder="请输入检查单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-150px"
        />
      </el-form-item>

      <!--  <el-form-item label="检查日期" prop="examDate">
        <el-date-picker
          v-model="queryParams.examDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item> -->
      <!--  <el-form-item label="检查项目名称" prop="examItemName">
        <el-input
          v-model="queryParams.examItemName"
          placeholder="请输入检查项目名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item> -->
      <el-form-item label="检查状态" prop="examStatus">
        <el-select
          v-model="queryParams.examStatus"
          placeholder="请选择检查状态"
          clearable
          class="!w-200px"
        >
          <el-option label="未分检" value="未分检" />
          <el-option label="未检查" value="未检查" />
          <el-option label="已检查" value="已检查" />
          <el-option label="已放弃" value="已放弃" />
        </el-select>
      </el-form-item>

      <el-form-item label="执行科室" prop="deviceDepartment">
        <el-select
          v-model="queryParams.deviceDepartment"
          placeholder="请选择执行科室"
          clearable
          class="!w-200px"
        >
        <el-option v-for="item in fordepartementData" :key="item.id" :label="item.departmentName" :value="item.departmentName" />
          <!-- <el-option label="影像科" value="影像科" /> -->
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <!--  <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['applyregistration:applyform:create']"
          v-if="false"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button> -->
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['applyregistration:applyform:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="success"
          plain
          @click="batchhandle(Profilevo.username)"
          v-hasPermi="['applyregistration:applyform:update']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 批量分检
        </el-button>
        <el-button @click="resetQuery" type="primary"
          ><Icon icon="ep:refresh" class="mr-5px" /> 同步</el-button
        >
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="主键" align="center" prop="id" v-if="false" />
      <el-table-column label="登记单号" align="center" prop="regId" width="100px" />
      <el-table-column label="登记来源" align="center" prop="regSource" width="100px" />
      <el-table-column label="检查单号" align="center" prop="examId" />
      <el-table-column label="患者姓名" align="center" prop="pname" width="100px" />
      <el-table-column label="性别" align="center" prop="gender" width="100px" />
      <el-table-column
        label="出生日期"
        align="center"
        prop="birthday"
        :formatter="dateFormatter"
        width="160px"
        v-if="false"
      />
      <el-table-column
        label="检查日期"
        align="center"
        prop="examDate"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="检查项目名称" align="center" prop="examItemName" width="140px" />
      <el-table-column label="检查设备ID" align="center" prop="deviceId" v-if="false" />
      <el-table-column label="检查设备" align="center" prop="deviceName" width="130px" />
      <el-table-column label="联系电话" align="center" prop="contactTel" />
      <el-table-column
        label="登记时间"
        align="center"
        prop="regDate"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="分检时间"
        align="center"
        prop="sortDate"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="开单医生" align="center" prop="billgDoctor" width="100px" />
      <el-table-column label="检查状态" align="center" prop="examStatus" width="100px" />
      <el-table-column
        label="开单医生科室"
        align="center"
        prop="billDoctorDepartment"
        :label-class-name="'no-wrap'"
        v-if="false"
      />
      <el-table-column
        label="此条记录的创建时间"
        align="center"
        prop="createDate"
        :formatter="dateFormatter"
        width="180px"
        v-if="false"
      />
      <el-table-column label="检查项目代码" align="center" prop="examItemCode" v-if="false" />
      <el-table-column label="机构ID" align="center" prop="orgId" v-if="false" />
      <el-table-column label="分检医生" align="center" prop="sortDoctor" width="100px" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="
              openForm('分检', scope.row.pname, scope.row.orgId, scope.row.id, scope.row.examStatus)
            "
            v-hasPermi="['applyregistration:applyform:update']"
          >
            分检
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id, scope.row.examStatus)"
            v-hasPermi="['applyregistration:applyform:delete']"
          >
            作废
          </el-button>

          <el-button link type="danger" @click="openPrintForm(scope.row.id)"> 导引单 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ApplyformForm ref="formRef" @success="getList" />
  <!-- 表单弹窗：打印导引单 -->
  <GuidePrint ref="Print" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { ApplyformApi, ApplyformVO, UPFJApplyformVO } from '@/api/applyregistration/applyform'
import ApplyformForm from './ApplyformForm.vue'
import { fa } from 'element-plus/es/locale'
import GuidePrint from './GuidePrint.vue'
import { getUserProfile, ProfileVO } from '@/api/system/user/profile'
import { DepartmentApi, DepartmentVO } from '@/api/system/department'

/** 申请登记记录 列表 */
defineOptions({ name: 'Applyform' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const loading = ref(true) // 列表的加载中
const list = ref<ApplyformVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
//科室数据
const fordepartementData = ref<any[]>([])
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  regId: undefined,
  regSource: undefined,
  examId: undefined,
  pname: undefined,
  gender: undefined,
  birthday: undefined,
  examDate: [],
  examItemName: undefined,
  deviceId: undefined,
  deviceName: undefined,
  contactTel: undefined,
  regDate: [],
  sortDate: [],
  billgDoctor: undefined,
  examStatus: undefined,
  billDoctorDepartment: undefined,
  createDate: [],
  examItemCode: undefined,
  orgId: undefined,
  sortDoctor: undefined,
  deviceDepartment: undefined,
  departmentCode: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const Profilevo = ref<ProfileVO>({} as ProfileVO) //当前登录人信息
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ApplyformApi.getApplyformPage(queryParams)
    list.value = data.list
    total.value = data.total
    //科室字典
    fordepartementData.value=await DepartmentApi.getDepartmentList()
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, pname: string, orgid: string, ID: number, status: string) => {
  if (status == '未分检') {
    formRef.value.open(type, orgid, pname, ID, Profilevo.value.username, [])
  } else {
    message.warning('只有未分检才可以进行分检操作')
  }
}

/** 打印导引单 */
const Print = ref()
const openPrintForm = (ID: number) => {
  Print.value.open(ID)
}

//批量相关
const selectedRows = ref<any[]>([]) // 存储当前选中的行
const previouslySelectedRows = ref<any[]>([]) // 存储先前选中的行
const handleSelectionChange = (selection) => {
  // 更新当前选中的行
  selectedRows.value = selection

  // 检查哪些行被取消勾选
  const unselectedRows = previouslySelectedRows.value.filter(
    (prevRow) => !selection.some((newRow) => newRow.id === prevRow.id)
  )

  // 输出取消勾选的行
  unselectedRows.forEach((row) => {
    console.log(`Row ${row.id} was unselected.`)
    // 这里可以添加你的逻辑来处理取消勾选的行
  })

  // 更新先前选中的行为当前选中的行，以备下次比较
  previouslySelectedRows.value = selection
  console.log(previouslySelectedRows.value)
}

/** 批量分检按钮操作 */
const batchhandle = async (username: string) => {
  try {
    let orgid: string = ''

    previouslySelectedRows.value.forEach((row) => {
      if (row.examStatus != '未分检') {
        message.warning('存在已经分检数据,重新选择')
        throw new Error('End Loop')
      }
      orgid = row.orgId
    })
    if (previouslySelectedRows.value.length <= 0) {
      message.warning('请选择需要分检的患者')
      return
    }
    console.log(`orgid ${orgid} was unselected.`)
    console.log(`username ${username} was unselected.`)
    formRef.value.open('批量', orgid, '', 0, username, previouslySelectedRows.value)
  } catch {}
}

/** 作废按钮操作 */
const handleDelete = async (id: number, status: string) => {
  try {
    if (status == '已检查') {
      message.warning('已进行检查,不允许进行作废操作')
      return
    }
    if (status == '已放弃') {
      message.warning('已作废,无需再次作废')
      return
    }
    // 作废的二次确认
    await message.delConfirm('是否作废选择内容')
    // 发起作废
    await ApplyformApi.cancelApplyform(id)
    message.success('作废成功')
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ApplyformApi.exportApplyform(queryParams)
    download.excel(data, '申请登记记录.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
//获取当前登录人信息
const getlogininfo = async () => {
  Profilevo.value = await getUserProfile()
}

/** 初始化 **/
onMounted(() => {
  getlogininfo()
  getList()
})
</script>
