<template>
  <ContentWrap title="设备清单">
    <!-- 锅炉设备展示 -->
    <template v-if="equipMainType === 200">
      <el-table
        ref="orderItemsTableRef"
        :data="taskOrderDetail.orderItems"
        border
        stripe
        empty-text="暂无设备信息"
        @selection-change="handleEquipSelectionChange"
      >
        <el-table-column type="selection" width="60" fixed="left" />
        <el-table-column label="操作" fixed="left" align="center" width="100">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button
                v-if="scope.row.taskStatus === PressureCheckerMyTaskStatus.REPORT_END"
                link
                type="primary"
                size="small"
                :disabled="isTaskCancelled"
                @click="handlePreviewReport(scope.row)"
              >查看报告</el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="区域" align="center" min-width="120">
          <template #default="scope">
            <div>{{ scope.row.equipDistrictName || '-' }}</div>
            <div class="text-gray-400 text-sm">{{ scope.row.equipStreetName || '' }}</div>
          </template>
        </el-table-column>
        <el-table-column label="设备注册代码" align="center" min-width="190">
          <template #default="scope">
            <el-button link type="success" @click="handleEquipCodeFn(scope.row.equipId)">
              {{ scope.row.equipCode || '-' }}
            </el-button>
            <div class="mt-2px mb-2px">
              <el-tag v-if="scope.row.productNo" type="success">
                {{ scope.row.productNo }}
              </el-tag>
            </div>
            <el-tag v-if="scope.row.editType === 'reject'" type="danger" size="small" class="ml-1"
              >拒绝约检</el-tag>
            <el-tag v-if="scope.row.editType === 'add'" type="success" size="small" class="ml-1"
              >新增设备</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否租借" align="center" prop="isRent" min-width="80">
          <template #default="scope">
            {{ scope.row.isRent ? '是' : '否' }}
          </template>
        </el-table-column>
        <el-table-column label="使用证编号" align="center" prop="useRegisterNo" min-width="120" />
        <el-table-column label="出厂编号" align="center" prop="factoryNo" min-width="120" />
        <el-table-column label="约检联系人" align="center" prop="contact" min-width="120" />
        <el-table-column label="约检联系人电话" align="center" prop="contactPhone" min-width="140" />
        <el-table-column label="蒸发量" align="center" prop="maxContinueEvapor" min-width="80" />
        <el-table-column label="型号" align="center" prop="boilerModel" min-width="120" />
        <el-table-column prop="taskStatus" label="主报告状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getTypeColor(scope.row.taskStatus)">
              {{ PressureTaskOrderTaskStatusMap[scope.row.taskStatus] || '-' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="检验结论" align="center" prop="mainConclusion" min-width="120px">
          <template #default="scope">
            <div v-if="scope.row.mainConclusion">
              <el-tag
                v-if="['符合要求', '基本符合要求'].includes(scope.row.mainConclusion)"
                type="success"
              >{{ scope.row.mainConclusion }}</el-tag>
              <el-tag v-else type="danger">{{ scope.row.mainConclusion }}</el-tag>
            </div>
            <div v-else>-</div>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!-- 管道设备展示 -->
    <template v-else-if="equipMainType === 300">
      <el-table
        ref="orderItemsTableRef"
        :data="taskOrderDetail.orderItems"
        border
        stripe
        empty-text="暂无设备信息"
        row-key="id"
        @selection-change="handleEquipSelectionChange"
      >
        <el-table-column type="selection" width="60" fixed="left" />
        <el-table-column label="操作" fixed="left" align="center" width="100">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button
                v-if="scope.row.taskStatus === PressureCheckerMyTaskStatus.REPORT_END"
                link
                type="primary"
                size="small"
                :disabled="isTaskCancelled"
                @click="handlePreviewReport(scope.row)"
              >查看报告</el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column type="expand" width="1">
          <template #default="scope">
            <div class="ml-15px mr-15px">
              <el-table :data="scope.row.detailDOS || []" border>
                <el-table-column label="注册代码" prop="pipeRegCode" min-width="120" show-overflow-tooltip />
                <el-table-column label="管道名称" prop="pipeName" min-width="120" show-overflow-tooltip />
                <el-table-column label="管道编号" prop="pipeNo" min-width="120" show-overflow-tooltip />
                <el-table-column label="管道级别" prop="pipeLevel" min-width="120" show-overflow-tooltip />
                <el-table-column label="管道品种" prop="pipeType" min-width="120" show-overflow-tooltip />
                <el-table-column label="长度" prop="pipeLength" min-width="100" show-overflow-tooltip />
                <el-table-column label="管道材质" prop="pipeMaterial" min-width="120" show-overflow-tooltip />
                <el-table-column label="材料标准" prop="materialStandard" min-width="120" show-overflow-tooltip />
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="工程号" align="center" prop="projectNo" min-width="120" />
        <el-table-column label="使用证编号" align="center" prop="useNo" min-width="120" show-overflow-tooltip />
        <el-table-column label="工程名称" align="center" prop="projectName" min-width="120" show-overflow-tooltip />
        <el-table-column label="区域/街道" align="center" min-width="120" show-overflow-tooltip>
          <template #default="scope">
            <span class="text-xs">{{ scope.row.equipStreetName ?? scope.row.equipDistrictName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="约检联系人" align="center" prop="contact" min-width="120" show-overflow-tooltip />
        <el-table-column label="约检联系人电话" align="center" prop="contactPhone" min-width="140" />
        <el-table-column prop="taskStatus" label="主报告状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getTypeColor(scope.row.taskStatus)">
              {{ PressureTaskOrderTaskStatusMap[scope.row.taskStatus] || '-' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="检验结论" align="center" prop="mainConclusion" min-width="120px">
          <template #default="scope">
            <div v-if="scope.row.mainConclusion">
              <el-tag
                v-if="['符合要求', '基本符合要求'].includes(scope.row.mainConclusion)"
                type="success"
              >{{ scope.row.mainConclusion }}</el-tag>
              <el-tag v-else type="danger">{{ scope.row.mainConclusion }}</el-tag>
            </div>
            <div v-else>-</div>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!-- 默认展示 -->
    <template v-else>
      <el-table
        ref="orderItemsTableRef"
        :data="taskOrderDetail.orderItems"
        border
        stripe
        empty-text="暂无设备信息"
        @selection-change="handleEquipSelectionChange"
      >
        <el-table-column type="selection" width="60" fixed="left" />
        <el-table-column label="操作" fixed="left" align="center" width="100">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button
                v-if="scope.row.taskStatus === PressureCheckerMyTaskStatus.REPORT_END"
                link
                type="primary"
                size="small"
                :disabled="isTaskCancelled"
                @click="handlePreviewReport(scope.row)"
              >查看报告</el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="equipName" label="设备名称" width="100" align="center" />
        <el-table-column prop="fee" label="收费金额" width="100" align="center" />
        <el-table-column prop="equipCode" label="设备注册代码" width="195" align="center">
          <template #default="scope">
            <el-button link type="success" @click="handleEquipCodeFn(scope.row.equipId)">{{
              scope.row.equipCode
            }}</el-button>
            <div class="mt-2px mb-2px">
              <el-tag v-if="scope.row.productNo" type="success">
                {{ scope.row.productNo }}
              </el-tag>
            </div>
            <el-tag v-if="scope.row.editType === 'reject'" type="danger" size="small" class="ml-1"
              >拒绝约检</el-tag>
            <el-tag v-if="scope.row.editType === 'add'" type="success" size="small" class="ml-1"
              >新增设备</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reportRespVOList" label="记录编号" width="100" align="center">
          <template #default="{ row }">
            {{ Array.isArray(row.reportRespVOList) ? row.reportRespVOList[0]?.reportNo || '-' : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="checkType" label="检验性质" width="100" align="center">
          <template #default>
            {{ PressureCheckTypeMap[taskOrderDetail.checkType] || '-' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="reportRespVOList"
          label="检验项目"
          min-width="550"
          header-align="center"
        >
          <template #default="{ row }">
            <span v-for="item in getRowReportVOList(row)" :key="item?.templateId">
              <el-button
                :disabled="
                  taskOrder?.taskStatus === PressureTaskOrderTaskStatus['REPORT_END'] ||
                  canAddReportItem(row.taskStatus) ||
                  taskOrder?.taskStatus === PressureTaskOrderTaskStatus['AUDITING_CANCEL']
                "
                link
                type="primary"
                class="!whitespace-normal !m-[0px]"
              >{{ item?.reportName }}</el-button>
              <el-button
                :disabled="
                  taskOrder?.taskStatus === PressureTaskOrderTaskStatus['REPORT_END'] ||
                  taskOrder?.taskStatus === PressureTaskOrderTaskStatus['AUDITING_CANCEL']
                "
                link
                type="primary"
                class="!m-[0px]"
              >({{ getCheckItemFeeType(item) }})</el-button>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="reportRespVOList" label="操作指导书名称" width="180" align="center">
          <template #default="{ row }">
            <template
              v-if="
                filterReportType(row.reportRespVOList, PressureReportType['WORKINSTRUCTION']).length
              "
            >
              <template
                v-if="
                  filterReportType(row.reportRespVOList, PressureReportType['WORKINSTRUCTION'])
                    .length <= 2
                "
              >
                <el-button
                  class="!whitespace-normal !m-[0px] w-full"
                  link
                  v-for="(item, index) in filterReportType(
                    row.reportRespVOList,
                    PressureReportType['WORKINSTRUCTION']
                  )"
                  :type="item?.taskStatus != 800 ? 'danger' : 'success'"
                  :key="index"
                  @click="handlePreviewDownload(item)"
                >{{ item?.reportName ? `${item?.reportName}` : '-' }}</el-button>
              </template>
              <!-- 弹窗 -->
              <el-popover v-else placement="top-start" :width="200" trigger="hover">
                <el-button
                  class="!whitespace-normal !m-[0px] w-full"
                  link
                  v-for="(item, index) in filterReportType(
                    row.reportRespVOList,
                    PressureReportType['WORKINSTRUCTION']
                  )"
                  :type="item?.taskStatus != 800 ? 'danger' : 'success'"
                  :key="index"
                  @click="handlePreviewDownload(item)"
                >{{ item?.reportName ? `${item?.reportName}` : '-' }}</el-button>
                <template #reference>
                  <div>
                    <el-button
                      class="!whitespace-normal !m-[0px] w-full"
                      link
                      v-for="(item, index) in filterReportType(
                        row.reportRespVOList,
                        PressureReportType['WORKINSTRUCTION']
                      ).slice(0, 2)"
                      :type="item?.taskStatus != 800 ? 'danger' : 'success'"
                      :key="index"
                      @click="handlePreviewDownload(item)"
                    >{{ item?.reportName ? `${item?.reportName}` : '-' }}</el-button>
                  </div>
                </template>
              </el-popover>
            </template>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="reportRespVOList" label="检验方案" min-width="180" align="center">
          <template #default="{ row }">
            <template
              v-if="
                filterReportType(
                  row.reportRespVOList,
                  PressureReportType['INSPECTIONPLAN'],
                  row.majorIssuesList
                ).length
              "
            >
              <template
                v-if="
                  filterReportType(
                    row.reportRespVOList,
                    PressureReportType['INSPECTIONPLAN'],
                    row.majorIssuesList
                  ).length <= 2
                "
              >
                <el-button
                  class="!whitespace-normal !m-[0px] w-full"
                  link
                  v-for="(item, index) in filterReportType(
                    row.reportRespVOList,
                    PressureReportType['INSPECTIONPLAN'],
                    row.majorIssuesList
                  )"
                  :type="item?.taskStatus != 800 ? 'danger' : 'success'"
                  :key="index"
                  @click="handlePreviewDownload(item)"
                >{{
                  item?.reportName ? `${item?.reportName}(${item.currentIndex})` : '-'
                }}</el-button>
              </template>
              <!-- 弹窗 -->
              <el-popover v-else placement="top-start" :width="200" trigger="hover">
                <el-button
                  class="!whitespace-normal !m-[0px] w-full"
                  link
                  v-for="(item, index) in filterReportType(
                    row.reportRespVOList,
                    PressureReportType['INSPECTIONPLAN'],
                    row.majorIssuesList
                  )"
                  :type="item?.taskStatus != 800 ? 'danger' : 'success'"
                  :key="index"
                  @click="handlePreviewDownload(item)"
                >{{
                  item?.reportName ? `${item?.reportName}(${item.currentIndex})` : '-'
                }}</el-button>
                <template #reference>
                  <div>
                    <el-button
                      class="!whitespace-normal !m-[0px] w-full"
                      link
                      v-for="(item, index) in filterReportType(
                        row.reportRespVOList,
                        PressureReportType['INSPECTIONPLAN'],
                        row.majorIssuesList
                      ).slice(0, 2)"
                      :type="item?.taskStatus != 800 ? 'danger' : 'success'"
                      :key="index"
                      @click="handlePreviewDownload(item)"
                    >{{
                      item?.reportName ? `${item?.reportName}(${item.currentIndex})` : '-'
                    }}</el-button>
                  </div>
                </template>
              </el-popover>
            </template>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="taskStatus" label="主报告状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getTypeColor(scope.row.taskStatus)">
              {{ PressureTaskOrderTaskStatusMap[scope.row.taskStatus] || '-' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="检验结论" align="center" prop="mainConclusion" min-width="120px">
          <template #default="scope">
            <div v-if="scope.row.mainConclusion">
              <el-tag
                v-if="['符合要求', '基本符合要求'].includes(scope.row.mainConclusion)"
                type="success"
              >{{ scope.row.mainConclusion }}</el-tag>
              <el-tag v-else type="danger">{{ scope.row.mainConclusion }}</el-tag>
            </div>
            <div v-else>-</div>
          </template>
        </el-table-column>
        <el-table-column prop="equipDistrictName" align="center" label="区域" width="100">
          <template #default="scope">
            <div>{{ scope.row.equipDistrictName }}</div>
            <div class="text-gray-400 text-sm">{{ scope.row.equipStreetName }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="useRegisterNo" label="使用证编号" width="135" align="center" />
        <el-table-column prop="equipVolume" label="容积" width="60" align="center" />
        <el-table-column label="下次年度检查" width="110" align="center">
          <template #default="scope">
            {{ !scope.row.nextYearCheckDate ? '-' : formatArrayDate(scope.row.nextYearCheckDate) }}
          </template>
        </el-table-column>
        <el-table-column label="下次定期检验" width="110" align="center">
          <template #default="scope">
            {{ formatArrayDate(scope.row.nextCheckDate) }}
          </template>
        </el-table-column>
        <el-table-column label="超年限检验" width="110" align="center">
          <template #default="scope">
            {{
              scope.row.nextExpiredCheckDate ? formatArrayDate(scope.row.nextExpiredCheckDate) : '-'
            }}
          </template>
        </el-table-column>
        <el-table-column label="超年限时间" width="110" align="center">
          <template #default="scope">
            {{ scope.row.overdueDate ? formatArrayDate(scope.row.overdueDate) : '-' }}
          </template>
        </el-table-column>
        <el-table-column
          label="约检联系人"
          prop="contact"
          width="110"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column label="约检联系人电话" prop="contactPhone" width="135" align="center" />
        <el-table-column label="主检人" width="110" align="center">
          <template #default="scope">
            <div>{{ scope.row.mainCheckerUser?.nickname || '-' }}</div>
            <div class="text-gray-400 text-sm">{{ scope.row.mainCheckerUser?.employeeNo || '' }}</div>
          </template>
        </el-table-column>
      </el-table>
    </template>
  </ContentWrap>
  <!-- 打印记录 -->
  <Dialog
    v-model="nprintRecordDialogVisible"
    :dialogAttrs="{
      zIndex: 10006
    }"
    :title="'打印项目'"
  >
    <SmartTable
      ref="nprintRecordTableRef"
      v-model:columns="nprintRecordColumns"
      :isPagination="false"
      :maxHeight="600"
      :data="nprintRecordTableList"
      :buttons="[]"
      :showSettingTools="false"
      :showSearch="false"
      :showRefresh="false"
      :tableProps="{
        onRowClick: handleRowClick
      }"
    />
    <template #footer>
      <el-button :loading="nprintRecordLoading" type="primary" @click="handlePrintFn"
        >打 印</el-button>
      <el-button :loading="nprintRecordLoading" type="primary" @click="handlePrintFnDownload"
        >下 载</el-button>
      <el-button :loading="nprintRecordLoading" @click="nprintRecordDialogVisible = false"
        >取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="tsx">
import {
  PressureCheckTypeMap,
  PressureTaskOrderTaskStatus,
  PressureTaskOrderTaskStatusMap,
  PressureCheckerMyTaskStatusMap,
  PressureCheckerMyTaskStatus,
  PressureReportType
} from '@/utils/constants'
import SmartTable from '@/components/SmartTable/SmartTable'
import { SmartTableColumn } from '@/types/table'
import { is } from '@/utils/is'
import { formatArrayDate } from '@/utils/formatTime'
import { TableInstance } from 'element-plus'
import { TaskOrderApi } from '@/api/pressure/taskorder'
import { BoilerTaskOrderApi } from '@/api/pressure2/boilertaskorder'
import { PipeTaskOrderApi } from '@/api/pressure2/pipetaskorder'
import { buildFileUrl } from '@/utils'
import { getJCP } from '@/utils/jcp/jcp-vue'

const props = defineProps({
  taskOrder: {
    type: Object as () => Record<string, any>,
    required: true
  },
  taskOrderDetail: {
    type: Object as () => Record<string, any>,
    required: true
  },
  supportingDocsAuditDataList: {
    type: Array as () => Record<string, any>[],
    required: true
  }
})

// 设备类型 200-锅炉 300-管道
const equipMainType = computed(() => {
  return props.taskOrderDetail?.equipMainType || null
})

// 根据 equipMainType 获取对应的 API
const getCurrentApi = () => {
  if (equipMainType.value === 200) {
    return BoilerTaskOrderApi
  } else if (equipMainType.value === 300) {
    return PipeTaskOrderApi
  }
  return TaskOrderApi // 默认
}

const InformationModificationVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false)
const formData = ref({
  safeManager: '', //安全管理员姓名
  safeManagerPhone: '', //安全管理员电话
  safeManagerIdNumber: '', //安全管理员证号
  operatorIdNumber: '' //操作人证号
})
const formRules = reactive({})
const formRef = ref() // 表单 Ref
const nprintRecordLoading = ref(false)
const nprintRecordTableRef = ref()
const nprintRecordDialogVisible = ref(false)
const nprintRecordTableList = ref<any[]>([])
const nprintRecordColumns = ref<SmartTableColumn[]>([
  {
    type: 'selection',
    width: '50px'
  },
  {
    label: '检验项目',
    prop: 'reportName'
  },
  {
    label: '状态',
    prop: 'taskStatus',
    render: (row) => {
      return row.taskStatus ? (
        <div>
          <el-tag key={row.id} type={getTypeColor2(row.taskStatus)}>
            {PressureCheckerMyTaskStatusMap[row.taskStatus]}
          </el-tag>
        </div>
      ) : (
        '-'
      )
    }
  }
])

const emit = defineEmits([
  'refresh-detail',
  'handle-add-checker-items',
  'handle-mainquestion-add-report',
  'handle-add-inspectionplan-report',
  'handle-batch-edit-fn',
  'handle-abort-task',
  'handle-equip-selection-change',
  'handle-equip-code-fn',
  'handle-input-calc-field',
  'handle-preview-download',
  'handle-add-report',
  'handle-view-mainquestion-report',
  'handle-set-main-checker',
  'handle-preview-report',
  'handle-add-finite-space-report'
])

const rowData = ref<any>({})
const selectedEquips = ref<Array<Record<string, any>>>([])
const handlePrintFnDownload = async () => {
  const selectRows = nprintRecordTableRef.value.getTableRef().getSelectionRows()
  if (selectRows.length == 0) {
    return ElMessage.error('请选择打印项目')
  } else {
    const params = selectRows.map((item) => item.id)
    const currentApi = getCurrentApi()
    const result = await currentApi.downloadReport({ ids: params })
    const downloadUrl = window.URL.createObjectURL(result)
    const a = document.createElement('a')
    a.href = downloadUrl
    const fileName = `${rowData.value.equipCode}` + '项目'
    a.download = fileName
    document.body.appendChild(a)
    a.click()
    // 下载文件
    window.URL.revokeObjectURL(downloadUrl)
    document.body.removeChild(a)
  }
}

const handleRowClick = (row) => {
  nprintRecordTableRef.value?.getTableRef()?.toggleRowSelection(row)
}

const handlePrintFn = async () => {
  const selectRows = nprintRecordTableRef.value.getTableRef().getSelectionRows()
  if (selectRows.length == 0) {
    return ElMessage.error('请选择打印项目')
  }

  const ids = selectRows.map((item) => item.id)
  const queryString = ids.map((id) => `ids=${id}`).join('&')
  nprintRecordLoading.value = true

  try {
    const currentApi = getCurrentApi()
    const result = await currentApi.getBatchUploadPdfApi(queryString)

    if (!result || result.length === 0) {
      nprintRecordLoading.value = false
      return ElMessage.error('未获取到打印文件')
    }

    const jcp = getJCP()

    // 检测JCP是否可用
    if (!jcp) {
      nprintRecordLoading.value = false
      return ElMessage.error('打印组件未初始化,请安装打印插件')
    }

    let completedCount = 0
    let failedCount = 0

    // 循环打印每个PDF
    for (let i = 0; i < result.length; i++) {
      const url = buildFileUrl(result[i])
      const encodedUrl = url
        .split('/')
        .map((part) => {
          return /[\u4e00-\u9fa5]/.test(part) ? encodeURIComponent(part) : part
        })
        .join('/')

      // 为每个打印任务添加超时处理
      await new Promise((resolve) => {
        let isResolved = false

        // 设置10秒超时
        const timeout = setTimeout(() => {
          if (!isResolved) {
            isResolved = true
            failedCount++
            console.error(`第 ${i + 1} 个文件打印超时(可能用户取消了打印)`)
            resolve(false)
          }
        }, 5000) // 5秒超时,可根据实际情况调整

        jcp.printPDF(encodedUrl, {
          settings: {
            paperName: 'A4',
            orientation: 'portrait',
            marginTop: 0,
            marginBottom: 0,
            marginLeft: 0,
            marginRight: 0,
            shrink: false
          },
          printer: '',
          preview: false,
          fileType: 'pdf',
          done: function () {
            if (!isResolved) {
              isResolved = true
              clearTimeout(timeout)
              completedCount++
              console.log(`第 ${i + 1} 个文件打印完成`)
              resolve(true)
            }
          },
          fail: function (error) {
            if (!isResolved) {
              isResolved = true
              clearTimeout(timeout)
              failedCount++
              console.error(`第 ${i + 1} 个文件打印失败:`, error)
              resolve(false)
            }
          }
        })
      })
    }

    // 显示最终结果
    if (failedCount === 0) {
      ElMessage.success(`全部打印完成,共 ${completedCount} 个文件`)
    } else if (completedCount === 0) {
      ElMessage.error(`打印失败,共 ${failedCount} 个文件未能打印`)
    } else {
      ElMessage.warning(`打印完成 ${completedCount} 个,失败 ${failedCount} 个`)
    }
  } catch (error) {
    console.error('打印过程出错:', error)
    ElMessage.error('打印过程出错: ' + (error.message || '未知错误'))
  } finally {
    // 确保无论如何都会关闭loading
    nprintRecordLoading.value = false
  }
}

// 作废报告项
const submitForm = async () => {
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const selectRows = getSelectionRows()
    const data = {
      ...formData.value,
      ids: selectRows.map((item) => item.equipId)
    }
    const logId = await TaskOrderApi.updateEquipJobInfoApi(data)
    if (logId) {
      ElMessage.success('修改成功')
    }
    InformationModificationVisible.value = false
  } finally {
    formLoading.value = false
  }
}

const orderItemsTableRef = ref<TableInstance>()
const handleEquipSelectionChange = (selection) => {
  // 实现设备选择逻辑
  selectedEquips.value = selection
  emit('handle-equip-selection-change', selection)
}

const isTaskCancelled = computed(() => {
  return props.taskOrderDetail?.taskStatus === PressureTaskOrderTaskStatus.CANCELLED
})

const handlePreviewReport = (row: any) => {
  emit('handle-preview-report', row)
}

const handleEquipCodeFn = (id?: string) => {
  emit('handle-equip-code-fn', id)
}

const getRowReportVOList = (row) => {
  return (row.reportRespVOList || []).filter(
    (item) =>
      ![PressureReportType['WORKINSTRUCTION'], PressureReportType['INSPECTIONPLAN']].includes(
        item.reportType
      )
  )
}

const canAddReportItem = (taskStatus) => {
  const { REPORT_AUDIT, REPORT_APPROVE, REPORT_END } = PressureCheckerMyTaskStatus
  return [REPORT_AUDIT, REPORT_APPROVE, REPORT_END].includes(taskStatus)
}

const getCheckItemFeeType = computed(() => {
  return ({ isAutoAmount, fee }) => {
    if (is(fee, 'Number')) return fee
    else if (is(fee, 'Null') && isAutoAmount === '1') return '录入计算'
    else return '0'
  }
})

const filterReportType = (list: any[], reportType: number, majorIssuesList?: any[]) => {
  const reportList = list.filter((item) => item.reportType === reportType)
  const majorIssuesListValue = majorIssuesList?.map((item) => item) || []
  const newList = [...reportList, ...majorIssuesListValue]

  const sortedList = newList.sort((a, b) => {
    const timeA = a.createTime || 0
    const timeB = b.createTime || 0
    return timeB - timeA // 倒序排列
  })

  const total = sortedList.length

  return sortedList.map((item, index) => {
    return {
      ...item,
      currentIndex: total - index // 倒序编号：第一个显示的是最大数字
    }
  })
}

const handlePreviewDownload = (row) => {
  emit('handle-preview-download', row)
}

const getTypeColor = (status: string | number) => {
  const statusMap = {
    [PressureTaskOrderTaskStatus.WAIT_CONFIRM]: 'primary',
    [PressureTaskOrderTaskStatus.CANCELLED]: 'info',
    [PressureTaskOrderTaskStatus.AUDITING_EDIT]: 'warning',
    [PressureTaskOrderTaskStatus.AUDITING_CANCEL]: 'warning',
    [PressureTaskOrderTaskStatus.AUDITING_TIME]: 'warning',
    [PressureTaskOrderTaskStatus.CONFIRMED]: 'success',
    [PressureTaskOrderTaskStatus.RECORD_INPUT]: 'warning',
    [PressureTaskOrderTaskStatus.RECORD_CHECK]: 'warning',
    [PressureTaskOrderTaskStatus.REPORT_INPUT]: 'warning',
    [PressureTaskOrderTaskStatus.REPORT_AUDIT]: 'warning',
    [PressureTaskOrderTaskStatus.REPORT_APPROVE]: 'warning',
    [PressureTaskOrderTaskStatus.REPORT_END]: 'primary'
  }
  return statusMap[status] || 'info'
}

const getTypeColor2 = (status: string | number) => {
  const statusMap = {
    [PressureTaskOrderTaskStatus.WAIT_CONFIRM]: 'primary',
    [PressureTaskOrderTaskStatus.CANCELLED]: 'info',
    [PressureTaskOrderTaskStatus.AUDITING_EDIT]: 'warning',
    [PressureTaskOrderTaskStatus.AUDITING_CANCEL]: 'warning',
    [PressureTaskOrderTaskStatus.AUDITING_TIME]: 'warning',
    [PressureTaskOrderTaskStatus.CONFIRMED]: 'success',
    [PressureTaskOrderTaskStatus.RECORD_INPUT]: 'warning',
    [PressureTaskOrderTaskStatus.RECORD_CHECK]: 'warning',
    [PressureTaskOrderTaskStatus.REPORT_INPUT]: 'warning',
    [PressureTaskOrderTaskStatus.REPORT_AUDIT]: 'warning',
    [PressureTaskOrderTaskStatus.REPORT_APPROVE]: 'warning',
    [PressureTaskOrderTaskStatus.REPORT_END]: 'success'
  }
  return statusMap[status] || 'info'
}

const getSelectionRows = () => {
  return orderItemsTableRef.value?.getSelectionRows() || []
}

defineExpose({
  getSelectionRows
})
</script>
