<template>
  <!-- 主内容区域 -->
  <div :class="{ 'app-container': inPageMode }">
    <!-- 页面模式下的操作按钮 -->
    <div v-if="inPageMode" class="mb-4">
      <div class="flex justify-between items-center">
        <div v-if="taskOrderDetail">
          <el-button
            type="primary"
            @click="openModifyTimeDialog"
            :disabled="canNotModify"
          >修改检验时间</el-button
          >
          <el-button
            type="primary"
            @click="handleModifyTaskOrder"
            :disabled="canNotModify"
          >修改任务单</el-button
          >
          <el-button
            type="danger"
            @click="openVoidTaskDialog"
            :disabled="canNotModify"
          >作废任务单</el-button
          >
          <el-button
            type="success"
            @click="openCheckerSelectionDialog"
            :disabled="isTaskCancelled || isTaskCompleted"
          >修改检验人员</el-button
          >
          <!--          <el-button v-if="props.type !== 'checker'" type="success" @click="openCheckerSelectionDialog" :disabled="isTaskCancelled">修改检验人员</el-button>-->
          <el-button
            type="success"
            @click="handleModifyManager"
            :disabled="isTaskCancelled || isTaskCompleted"
          >修改项目负责人</el-button
          >
          <el-button
            type="primary"
            plain
            @click="handleAddSafetyRecord"
            :disabled="isTaskCancelled || isTaskCompleted"
          >添加安全记录检查</el-button
          >
          <el-button
            type="primary"
            plain
            @click="() => handleServiceOrder(100)"
            :disabled="isTaskCancelled"
          >服务单/受理单</el-button
          >
          <el-button
            type="primary"
            plain
            @click="() => handleServiceOrder(200)"
            :disabled="isTaskCancelled"
          >检验情况告知</el-button
          >
        </div>
      </div>
    </div>

    <!-- 任务单详情、异常信息、审核、设备清单 -->
    <div v-if="!taskOrderDetail" class="loading-text">
      无法加载任务详情。
    </div>
    <div v-else>
      <ContentWrap class="mb-4" title="任务单详情">
        <div class="tip custom-block">单位信息</div>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="任务单号">
            {{ taskOrderDetail.orderNo }}
          </el-descriptions-item>
          <el-descriptions-item label="检验类别">
            {{ PressureBoilerCheckTypeMap[taskOrderDetail.checkType] || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="检验设备数量">
            {{ taskOrderDetail.equipNum || '-' }}
          </el-descriptions-item>

          <el-descriptions-item label="申请单位名称">
            {{ taskOrderDetail.unitName || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="使用单位名称">
            {{ taskOrderDetail.useUnitName || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="检验日期">
            {{ Array.isArray(taskOrderDetail.checkDate) ? formatArrayDate(taskOrderDetail.checkDate) : taskOrderDetail.checkDate || '-' }}
          </el-descriptions-item>

          <el-descriptions-item label="申请单位地址">
            {{ taskOrderDetail.unitAddress || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="使用单位地址">
            {{ taskOrderDetail.useUnitAddress || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="收费性质">
            {{ PressureFeeNatureMap[taskOrderDetail.feeNature] || '-' }}
          </el-descriptions-item>

          <el-descriptions-item label="收费形式">
            {{ PressureFeeTypeMap[taskOrderDetail.feeType] || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="收费金额">
            {{ taskOrderDetail.payAmount || '-'  }}
          </el-descriptions-item>
          <el-descriptions-item label="是否已交费">
            {{ taskOrderDetail.isPay === 1?'是':'否' }}
          </el-descriptions-item>

          <el-descriptions-item label="业务受理人">
            <el-tag v-if="taskOrderDetail.acceptUser" effect="light" :closable="false">
              {{
                taskOrderDetail.acceptUser
                  ? `${taskOrderDetail.acceptUser.nickname} (${taskOrderDetail.acceptUser.employeeNo})`
                  : '-'
              }}
            </el-tag>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="项目负责人">
            <div v-if="taskOrderDetail.manager">
              <el-tag type="primary">
                {{ taskOrderDetail.manager ? `${taskOrderDetail.manager.nickname} (${taskOrderDetail.manager.employeeNo})` : '-' }}
              </el-tag>
            </div>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="检验人员">
            <div
              v-if="taskOrderDetail.teamItemList && taskOrderDetail.teamItemList.length > 0">
              <div
                v-for="(team, teamIndex) in taskOrderDetail.teamItemList"
                :key="team.groupTeamId || 'team-' + teamIndex"
                style="margin-bottom: 8px">
                <div
                  v-if="taskOrderDetail.teamItemList.length > 1"
                  style="font-weight: bold; margin-bottom: 4px">
                  团队 {{ teamIndex + 1 }}:
                </div>
                <div
                  style="display: flex; flex-wrap: wrap; align-items: center; gap: 6px">
                  <template
                    v-for="(leader, leaderIdx) in team.leaders"
                    :key="
                      leader.id
                        ? 'leader-' + leader.id
                        : 'leader-idx-' + leaderIdx + '-' + teamIndex
                    ">
                    <el-tag
                      effect="light"
                      :closable="false">
                      <span class="leader-tag">组</span>
                      {{ leader.nickname }}
                    </el-tag>
                  </template>
                  <template
                    v-for="(member, memberIdx) in team.members"
                    :key="
                      member.id
                        ? 'member-' + member.id
                        : 'member-idx-' + memberIdx + '-' + teamIndex
                    ">
                    <el-tag effect="light" :closable="false"
                    >{{ member.nickname
                      }}({{ member.employeeNo }})</el-tag
                    >
                  </template>
                  <span
                    v-if="
                      (!team.leaders || team.leaders.length === 0) &&
                      (!team.members || team.members.length === 0)
                    "
                    style="margin-left: 4px"
                  >-</span
                  >
                </div>
              </div>
            </div>
            <span v-else>-</span>
          </el-descriptions-item>

          <el-descriptions-item label="计划编制人">
            <el-tag v-if="taskOrderDetail.scheduleUser" effect="light" :closable="false">
              {{
                taskOrderDetail.scheduleUser
                  ? `${taskOrderDetail.scheduleUser.nickname} (${taskOrderDetail.scheduleUser.employeeNo})`
                  : '-'
              }}
            </el-tag>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="中止检验">
            {{ taskOrderDetail.XXX || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="安全检查记录">
            <el-button link type="primary" @click="handleLookSecurityCheck">{{
                taskOrderDetail.securityCheckCount
              }}</el-button>
          </el-descriptions-item>

          <el-descriptions-item label="备注" :span="2">
            {{ taskOrderDetail.remark || '-' }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="tip custom-block">联系人信息</div>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="约检联系人">
            {{ taskOrderDetail.unitContact || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="约检联系人电话">
            {{ taskOrderDetail.unitPhone || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="约检联系人邮箱">
            {{ taskOrderDetail.unitEmail || '-' }}
          </el-descriptions-item>

          <el-descriptions-item label="电子报告接收人">
            {{ taskOrderDetail.recipient || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="报告接收人电话">
            {{ taskOrderDetail.recipientPhone || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="接收人邮箱">
            {{ taskOrderDetail.recipientEmail || '-' }}
          </el-descriptions-item>

          <el-descriptions-item label="缴费联系人">
            {{ taskOrderDetail.payerContactName || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="缴费人电话">
            {{ taskOrderDetail.payerContact || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="缴费人邮箱">
            {{ taskOrderDetail.payerMail || '-' }}
          </el-descriptions-item>
        </el-descriptions>
      </ContentWrap>
      <ContentWrap v-if="exceptionInfo.id" title="异常信息">
        <el-form
          v-if="exceptionInfo.id"
          disabled
          :model="exceptionInfo"
          ref="formRef"
          label-width="130px"
          class="p-3">
          <el-row
            v-if="exceptionInfo.id"
            class="form-group"
            :gutter="24">
            <el-col :span="8">
              <el-form-item
                label="有效日期调整原因"
                prop="effectiveDateAdjustReason">
                <el-input
                  v-model="exceptionInfo.effectiveDateAdjustReason"
                  placeholder="请输入有效日期调整原因" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="受理建议"
                prop="acceptSuggeston">
                <el-input
                  v-model="exceptionInfo.acceptSuggeston"
                  placeholder="请输入受理建议" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="调整有效日期"
                prop="adjustEffectiveDate">
                <el-date-picker
                  v-model="exceptionInfo.adjustEffectiveDate"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择调整有效日期" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="情况说明" prop="descrition">
                <component
                  :is="getExceptionItem('descrition', 'descritionAttach')" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="重启表" prop="restartTable">
                <component
                  :is="getExceptionItem('restartTable', 'restartTableAttach')" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="指令书" prop="instrustionBook">
                <component
                  :is="getExceptionItem('instrustionBook', 'instrustionBookAttach')" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="受理回执" prop="acceptReceipt">
                <component
                  :is="getExceptionItem('acceptReceipt', 'acceptReceiptAttach')" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="其他" prop="other">
                <component
                  :is="getExceptionItem('other', 'otherAttach')" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="提前检验申请函"
                prop="earlyCheckApply">
                <component
                  :is="getExceptionItem('earlyCheckApply', 'earlyCheckApplyAttach')" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </ContentWrap>
      <ContentWrap
        title="审核"
        v-if="supportingDocsAuditDataList.length > 0 && inPageMode">
        <SmartTable
          v-model:columns="supportingDocsAuditColumns"
          :data="supportingDocsAuditDataList"
          v-model:page-no="operationReportPageNo"
          v-model:page-size="operationReportPageSize"
          :total="operationReportTotal"
          @on-page-no-change="() => handleGetOperationReportAuditList()"
          @on-page-size-change="() => handleGetOperationReportAuditList()"
          @refresh="() => handleGetOperationReportAuditList()" />
      </ContentWrap>
      <ContentWrap title="设备清单">
        <div style="margin: 10px 0">
          <el-button
            type="primary"
            :disabled="taskOrder?.taskStatus === PressureTaskOrderTaskStatus['REPORT_END'] || isTaskCancelled"
            @click="() => handleAddCheckerItems()"
          >批量添加检验项目</el-button
          >
          <el-button
            type="primary"
            :disabled="selectedEquips.length !== 1  || isTaskCancelled"
            @click="() => handleMainquestionAddReport(PressureReportType['MAINQUESTION'], 'add')"
          >添加重大问题线索</el-button
          >
          <el-button
            type="primary"
            :disabled="selectedEquips.length !== 1  || isTaskCancelled"
            @click="handleAddInspectionplanReport">
            {{'添加检验方案'}}
          </el-button>
          <el-button
            type="primary"
            @click="handleBatchConcat"
            :disabled="selectedEquips.length === 0  || isTaskCancelled"
          >批量修改约检联系人</el-button
          >
        </div>
        <el-table
          :data="taskOrderDetail.orderItems"
          ref="orderItemsTableRef"
          @selection-change="handleEquipSelectionChange"
          border
          stripe
          empty-text="暂无设备信息">
          <el-table-column fixed="left" type="selection" width="40" />
          <el-table-column
            label="操作"
            fixed="left"
            align="center"
            width="200px">
            <template #default="scope">
              <div class="operation-buttons">
                <el-button type="primary" link size="small" @click="() => handleAddReport(PressureReportType['WORKINSTRUCTION'], scope.row)" :disabled="isTaskCancelled">添加作业指导书</el-button>
                <el-button v-if="showViewMainquestionBtn(scope.row)" type="primary" @click="handleViewMainquestionReport(scope.row)" link size="small">查看重大问题线索告知表</el-button>
                <el-button
                  v-if="scope.row.mainCheckerUser?.id !== taskOrderDetail.manager?.id"
                  link
                  type="primary"
                  size="small"
                  :disabled="isTaskCancelled"
                  @click="handleSetMainChecker(scope.row)"
                >修改主检人</el-button
                >
<!--                <el-button-->
<!--                  v-if="scope.row.taskStatus === PressureCheckerMyTaskStatus.REPORT_END"-->
<!--                  link-->
<!--                  type="primary"-->
<!--                  size="small"-->
<!--                  :disabled="isTaskCancelled"-->
<!--                  @click="handleEntityReport(scope.row)"-->
<!--                >添加作业指导书实体报告</el-button-->
<!--                >-->
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="equipDistrictName"
            align="center"
            label="区域"
            width="120px">
            <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="checkType"
            label="检验性质"
            width="150px"
            align="center">
            <template #default>
              {{ PressureBoilerCheckTypeMap[taskOrderDetail.checkType] || '-' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="reportRespVOList"
            label="检验项目"
            width="150px"
            align="center">
            <template #default="{ row }">
              <template
                v-if="getRowReportVOList(row).length <= 2">
                <el-row
                  v-for="item in getRowReportVOList(row)"
                  :key="item?.templateId">
                  <el-button
                    :disabled="taskOrder?.taskStatus === PressureTaskOrderTaskStatus['REPORT_END'] || canAddReportItem(row.taskStatus) || isTaskCancelled"
                    link
                    type="primary"
                    class="!whitespace-normal"
                    @click="() => handleAddCheckerItems(row)"
                  >{{ item?.reportName }}</el-button
                  >
                  <el-button
                    :disabled="taskOrder?.taskStatus === PressureTaskOrderTaskStatus['REPORT_END']"
                    link
                    type="primary"
                    @click.stop.prevent="() => handleInputCalcField(row.equipId, item)"
                  >(费用：{{ getCheckItemFeeType(item)
                    }})</el-button
                  >
                </el-row>
              </template>
              <!-- 弹窗 -->
              <el-popover
                v-else
                placement="top-start"
                :width="200"
                trigger="hover">
                <!-- 弹窗内容 -->
                <el-scrollbar max-height="400px">
                <el-row
                  v-for="item in getRowReportVOList(row)"
                  :key="item?.templateId">
                  <el-button
                    :disabled="taskOrder?.taskStatus === PressureTaskOrderTaskStatus['REPORT_END'] || canAddReportItem(row.taskStatus)"
                    link
                    type="primary"
                    class="!whitespace-normal"
                    @click="() => handleAddCheckerItems(row)"
                  >{{ item?.reportName }}</el-button
                  >
                  <el-button
                    :disabled="taskOrder?.taskStatus === PressureTaskOrderTaskStatus['REPORT_END']"
                    link
                    type="primary"
                    @click.stop.prevent="() => handleInputCalcField(row.equipId, item)"
                  >(费用：{{ getCheckItemFeeType(item)
                    }})</el-button
                  >
                </el-row>
                </el-scrollbar>
                <template #reference>
                  <div>
                    <el-row
                      v-for="item in getRowReportVOList(row).slice(0, 2)"
                      :key="item?.templateId">
                      <el-button
                        :disabled="taskOrder?.taskStatus === PressureTaskOrderTaskStatus['REPORT_END']"
                        link
                        class="!whitespace-normal"
                        type="primary"
                        @click="() => handleAddCheckerItems(row)"
                      >{{ item?.reportName }}</el-button
                      >
                      <el-button
                        :disabled="taskOrder?.taskStatus === PressureTaskOrderTaskStatus['REPORT_END']"
                        link
                        type="primary"
                        @click.stop.prevent="() => handleInputCalcField(row.equipId, item)"
                      >(费用：{{ getCheckItemFeeType(item)
                        }})</el-button
                      >
                    </el-row>
                  </div>
                </template>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column
            prop="reportRespVOList"
            label="操作指导书"
            width="120px"
            align="center">
            <template #default="{row}">
              <template
                v-if="filterReportType(row.reportRespVOList).length">
                <div
                  class="w-full"
                  v-for="(item,index) in filterReportType(row.reportRespVOList)"
                  :key="index">
                  {{ item?.reportName }}
                </div>
              </template>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="fee"
            label="收费金额"
            width="120px"
            align="center" />
          <el-table-column
            prop="taskStatus"
            label="主报告状态"
            width="150px"
            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
            prop="equipCode"
            label="设备注册代码"
            width="200px"
            align="center">
            <template #default="scope">
              <el-tag
                type="primary"
                size="small"
                class="ml-1"
              >{{ scope.row.equipCode }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="useCode"
            label="使用证编号"
            width="150px"
            align="center" />
          <el-table-column
            prop="maxContinueEvapor"
            label="蒸发量"
            min-width="200px"
            align="center" />
<!--          <el-table-column-->
<!--            prop="tonnage"-->
<!--            label="吨位"-->
<!--            width="80px"-->
<!--            align="center" />-->
          <el-table-column
            prop="boilerModel"
            label="型号"
            width="150px"
            align="center" />
          <el-table-column
            label="下次内部检验"
            width="120px"
            align="center">
            <template #default="scope">
              {{ scope.row.nextInCheckDate ? dayjs(scope.row.nextInCheckDate).format('YYYY-MM-DD') : '-' }}
            </template>
          </el-table-column>
          <el-table-column
            label="下次外部检验"
            width="120px"
            align="center">
            <template #default="scope">
              {{ scope.row.nextOutCheckDate ? dayjs(scope.row.nextOutCheckDate).format('YYYY-MM-DD') : '-' }}
            </template>
          </el-table-column>
          <el-table-column
            label="下次耐压检验"
            width="120px"
            align="center">
            <template #default="scope">
              {{ scope.row.nextPressureCheckDate ? dayjs(scope.row.nextPressureCheckDate).format('YYYY-MM-DD') : '-' }}
            </template>
          </el-table-column>
          <el-table-column
            label="约检联系人"
            width="160px"
            align="center">
            <template #default="scope">
              <div>{{ scope.row.contact || '-' }}</div>
            </template>
          </el-table-column>
          <el-table-column
            label="约检联系人电话"
            width="160px"
            align="center">
            <template #default="scope">
              <div>{{ scope.row.contactPhone || '-' }}</div>
            </template>
          </el-table-column>
        </el-table>
      </ContentWrap>
    </div>

    <!-- 页面模式下的底部操作按钮 -->
    <div
      v-if="inPageMode && taskOrderDetail"
      class="flex justify-center mt-4">
      <!--      <el-button v-if="props.type !== 'checker'" type="success" @click="handlePrintCommitment" :disabled="isTaskCancelled">打印委托书</el-button>-->
      <!--      <el-button v-if="props.type !== 'checker'" type="success" @click="handlePrintEquipmentRecord" :disabled="isTaskCancelled">打印设备记录</el-button>-->
      <el-button
        type="primary"
        @click="handleConfirm"
        v-if="taskStatus === PressureTaskOrderTaskStatus.WAIT_CONFIRM"
        :disabled="isTaskCancelled"
      >认领</el-button
      >
      <el-button
        type="primary"
        @click="handleCancelConfirm"
        v-if="taskStatus === PressureTaskOrderTaskStatus.CONFIRMED"
        :disabled="isTaskCancelled || isTaskCompleted"
      >取消认领</el-button
      >
      <el-button @click="handleClosePage">关闭</el-button>
    </div>
  </div>

  <!-- 内部弹窗：修改检验时间、作废任务单、检验员选择 (仅在页面模式且有权限时出现) -->
  <template v-if="inPageMode && taskOrderDetail">
    <!-- 修改检验时间对话框 -->
    <el-dialog
      v-model="modifyTimeDialogVisible"
      title="修改检验时间"
      width="500px"
      draggable
      :close-on-click-modal="false"
      append-to-body>
      <el-form
        ref="modifyTimeFormRef"
        :model="modifyTimeForm"
        label-width="100px">
        <el-form-item label="检验日期" prop="newInspectionDate" required>
          <el-date-picker
            v-model="modifyTimeForm.newInspectionDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            class="!w-full" />
        </el-form-item>
        <el-form-item label="修改原因" prop="reason" required>
          <el-input
            v-model="modifyTimeForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入修改原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="modifyTimeDialogVisible = false"
        >取消</el-button
        >
        <el-button type="primary" @click="handleSubmitModifyTime"
        >确定</el-button
        >
      </template>
    </el-dialog>

    <!-- 作废任务单对话框 -->
    <el-dialog
      v-model="voidTaskDialogVisible"
      title="作废任务单"
      width="500px"
      draggable
      :close-on-click-modal="false"
      append-to-body>
      <el-form
        ref="voidTaskFormRef"
        :model="voidTaskForm"
        :rules="{
          reason: [
            { required: true, message: '请输入作废原因', trigger: 'blur' },
          ],
        }"
        label-width="100px">
        <el-form-item label="作废原因" prop="reason">
          <el-input
            v-model="voidTaskForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入作废原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="voidTaskDialogVisible = false"
        >取消</el-button
        >
        <el-button type="primary" @click="handleSubmitVoidTask"
        >确定</el-button
        >
      </template>
    </el-dialog>

    <!-- 检验员选择弹窗 -->
    <el-dialog
      v-model="checkerSelectVisible"
      title="选择检验员"
      append-to-body
      width="800px"
      draggable
      :close-on-click-modal="false">
      <CheckerSelect
        ref="checkerSelectRef"
        v-model="tempSelectedCheckersInDialog"
        :dept-id="taskOrderDetail?.deptId?.toString() || userStore.getUser.deptId?.toString() || '1'"
        :disabled="false"
        :has-data="true"
        empty-text="暂无检验员数据"
        :multiple="true"
        @change="handleCheckerSelectionChangeInDialog"
      />
      <template #footer>
        <div class="flex justify-end">
          <el-button @click="checkerSelectVisible = false"
          >取消</el-button
          >
          <el-button
            type="primary"
            @click="confirmCheckerSelectionAndSubmit"
          >确定</el-button
          >
        </div>
      </template>
    </el-dialog>

    <UserSelectForm
      ref="userSelectFormRef"
      @confirm="handleManagerSelected"
      :single="true" />

    <!-- 出具报告对话框 -->
    <GenerateReportDialog
      v-model:visible="generateReportDialogVisible"
      :equip-id="currentReportEquip?.id || ''"
      :equip-name="currentReportEquip?.equipName"
      @success="handleGenerateReportSuccess" />

    <!-- 出具报告对话框（新版本） -->
    <IssueReportDialog
      v-model:visible="issueReportDialogVisible"
      :task-order-id="currentTaskOrderId"
      :report-type="currentReportType"
      :default-report-scope="200"
      :is-part-report="true"
      :default-selected-equipments="currentSelectedEquipment ? [currentSelectedEquipment] : []"
      @confirm="handleIssueReportConfirm" />

    <!-- 修改主检人对话框 -->
    <el-dialog
      v-model="mainCheckerDialogVisible"
      title="修改主检人"
      width="800px"
      draggable
      :close-on-click-modal="false"
      append-to-body>
      <div class="mb-4">
        <div class="text-sm text-gray-600 mb-2">
          当前设备：{{ currentEquipmentRow?.equipCode }} -
          {{ currentEquipmentRow?.equipName }}
        </div>
        <div class="text-sm text-gray-600 mb-4">
          请选择一个检验员作为主检人（单选）
        </div>
      </div>

      <CheckerSelect
        v-model="tempSelectedMainChecker"
        @change="handleMainCheckerSelectionChange"
        :max="1"/>

      <template #footer>
        <div class="flex justify-end">
          <el-button @click="mainCheckerDialogVisible = false"
          >取消</el-button
          >
          <el-button
            type="primary"
            @click="confirmMainCheckerSelection"
          >确定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </template>

  <!-- 安全检查记录弹窗 -->
  <SavetyCheckRecordList
    v-if="savetyCheckRecordListVsible"
    v-model:visible="savetyCheckRecordListVsible"
    :checkId="savetyCheck.checkId"
    :orderId="savetyCheck.orderId"
    @success="handleUpdateSavetyCheckRecordList" />

  <CustomDialog
    v-if="showSavetyCheckRecordVersions"
    v-model="showSavetyCheckRecordVersions"
    title="安全检查记录列表"
    width="800px"
    :showFooter="false"
    :z-index="1001">
    <SmartTable
      ref="smartTableRef"
      v-model:pageNo="savetyRecordPageNo"
      v-model:pagesize="savetyRecordPageSize"
      v-model:total="savetyRecordTotal"
      v-model:columns="savetyRecordColumns"
      :useBorderLayout="false"
      :data="savetyRecordList"
      :buttons="[]"
      @on-page-no-change="() => fetchSafetyCheckRecordPage()"
      @on-page-size-change="() => fetchSafetyCheckRecordPage()"
      @refresh="() => fetchSafetyCheckRecordPage()" />
  </CustomDialog>

  <!-- 批量修改约检联系人 -->
  <batchEditForm ref="formRef" @success="handleScheduleSuccess" />

  <!-- 添加检验项目弹窗 -->
  <AddOrEditCheckItemForEquipment
    v-if="showAddCheckItemsDialog"
    v-model="showAddCheckItemsDialog"
    :orderInfo="taskOrder"
    :selectedIds="checkItemIds"
    :isBatch="isBatchAdd"
    :equipmentIds="selectedEquipmentIds"
    :orderItemIds="selectedOrderIds"
    :isShowItemPart="false"
    @refresh="() => emit('refresh')" />

  <!-- 添加检验方案 添加弹窗 -->
  <AddInspectionplan
    ref="addInspectionplanRef"
    @success="handleSuccessInspectionplan" />

  <!-- 添加检验方案详情 -->
  <AddInspectionplanDetail
    v-if="AddInspectionplanDetailVisible"
    v-model:visible="AddInspectionplanDetailVisible"
    :editInspectionplanParams="editInspectionplanParams"
    :inspectionplanDetail="inspectionplanDetail"
    :taskOrderDetail="taskOrderDetail"
    :isEdit="isEdit"
    @success="handleUpdateInspectionplanDetail"
    @refresh="handleRefreshInspectionplan"
  />

  <!-- 服务单/受理单 添加弹窗 -->
  <OrderDialog
    ref="orderDialogRef"
    :orderId="props.taskOrder.id"
    type="boiler"
  />

  <ServiceRecordList
    v-if="serviceRecordListVisible"
    v-model:visible="serviceRecordListVisible"
    :serverForm="serviceOrderDialogFormData"
    :businessType="businessType"
    :orderItemId="mainOrderItemId"
    :reportId="mainReportId"
    :isAddMainquestion="isAddMainquestion"
    :taskOrderDetail="taskOrderDetail"
    @success="handleUpdateServiceRecordList"
  />

  <!-- 作业指导书 添加弹窗 -->
  <AddBookAndCheckScheme ref="addBookAndCheckSchemeRef" @success="handleSuccessReport" />

  <!-- 作业指导书 编辑弹窗 -->
  <EditWorkBookReport
    v-if="editWorkBookReportVisible"
    v-model:visible="editWorkBookReportVisible"
    :title="editOperationReportTypeTitle"
    :templateId="editOperationReportParams?.templateId"
    :reportId="editOperationReportParams?.reportId"
    :orderId="editOperationReportParams?.orderId"
    :dataJSON="editOperationReportParams?.prepareJson"
    :curReportTypeInfo="curReportTypeInfo"
    :isCustomFileUrl="false"
    :isEdit="isWorkBookEdit"
    @success="handleEditOperationReportList"
  />
  <calcCheckItemFee
    v-if="showCalcCheckItemFeeDialog"
    v-model="showCalcCheckItemFeeDialog"
    :equipmentId="calcEquipmentId"
    :templateInfo="calcTemplateInfo"
    @save="handleSaveCalcFee"
  />
</template>

<script setup lang="tsx">
import CustomDialog from '@/components/CustomDialog/index.vue'
import SmartTable from '@/components/SmartTable/SmartTable'
import calcCheckItemFee from './calcCheckItemFee.vue'
import SavetyCheckRecordList from './SavetyCheckRecordList.vue'
import AddOrEditCheckItemForEquipment from './AddOrEditCheckItemForEquipment.vue'
import { ref, watch, defineProps, defineEmits, reactive, computed, nextTick } from 'vue'
import { BoilerTaskOrderApi,BoilerTaskOrderItemVO } from '@/api/pressure2/boilertaskorder'
import {
  PressureFeeTypeMap,
  PressureTaskOrderTaskStatus,
  PressureCheckerMyTaskStatus,
  PressureFeeNatureMap,
  PressureBoilerCheckTypeMap,
  PressureReportType,
  PressureReportTypeMap,
  PressureTaskOrderStatus,
  PressureTaskOrderStatusMap, PressureCheckerMyTaskStatusMap, PressureTaskOrderTaskStatusMap
} from '@/utils/constants'
import { formatArrayDate } from '@/utils/formatTime'
import {
  ElMessage,
  FormInstance,
  ElMessageBox,
  dayjs,
  type ElForm,
  type ElTable,
  ElSelect, ElOption, type Action
} from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import CheckerSelect, { type CheckerItem } from '@/views/pressure2/components/CheckerSelect'
import UserSelectForm from '@/components/UserSelectForm/index.vue'
import { useTagsViewStore } from '@/store/modules/tagsView'
import GenerateReportDialog from './GenerateReportDialog.vue'
import IssueReportDialog from './IssueReportDialog.vue'
import VuePdfEmbed from 'vue-pdf-embed'
import { Icon } from '@/components/Icon'
import batchEditForm from '../../equipboilerscheduling/components/batchEditForm.vue'
import {Message as message} from "@/layout/components/Message";
import {buildFileUrl} from "@/utils";
import FileUploadModal from '@/views/pressure2/boilertaskorder/components/ImportFile.vue'
import {is} from "@/utils/is";
import {BoilerAppointmentConfirmOrderApi} from "@/api/pressure2/appointmentconfirmorder";
import { getPressureReportTemplateListNoLimit } from '@/api/pressure2/reportTemplate'
import AddInspectionplan from "@/views/pressure2/boilertaskorder/components/AddInspectionplan.vue";
import {useUserStore} from "@/store/modules/user";
import AddInspectionplanDetail from "@/views/pressure2/boilertaskorder/components/AddInspectionplanDetail.vue";
import ServiceRecordList from "@/views/pressure2/boilertaskorder/components/ServiceRecordList.vue";
import AddBookAndCheckScheme from "@/views/pressure2/boilertaskorder/components/AddBookAndCheckScheme.vue";
import EditWorkBookReport from "@/views/pressure2/boilertaskorder/components/EditWorkBookReport.vue";
import {EquipBoilerApi} from "@/api/pressure2/equipboiler";
import {TaskOrderApi} from "@/api/pressure/taskorder";
import OrderDialog from "@/views/pressure2/boilertaskorder/components/OrderDialog.vue";


const userStore = useUserStore()
const userInfo = computed(() => userStore.user)
const router = useRouter()
const route = useRoute()
const tagsViewStore = useTagsViewStore()

const orderDialogRef = ref()

const isWorkBookEdit = ref(false)
// 异常信息
const exceptionInfo = ref<Record<string, any>>({})

// 定义emit事件
const emit = defineEmits<{
  refresh: []
}>()

const props = defineProps({
  taskOrder: {
    type: Object as () => Record<string, any>, // Assuming a generic object, replace with TaskOrderVO or a more specific interface if available
    required: true
  },
  inPageMode: {
    type: Boolean,
    default: false
  },
  type: {
    type: String,
    default: 'taskorder'
  }
})

const taskOrderDetail = ref<any>(null) // This will hold the reactive copy of props.taskOrder

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

const isTaskCompleted = computed(() => {
  const completeStatus = [PressureTaskOrderTaskStatus.REPORT_CONFIRMATION, PressureTaskOrderTaskStatus.REPORT_END];
  return completeStatus.includes(taskOrderDetail.value.taskStatus)
})

const canNotModify = computed(() => {
  if (!taskOrderDetail.value) return true;
  if (taskOrderDetail.value.taskStatus === PressureTaskOrderTaskStatus.CANCELLED) {
    return true;
  }
  return taskOrderDetail.value.taskStatus !== PressureTaskOrderTaskStatus.WAIT_CONFIRM;
});

const taskStatus = computed(() => {
  return taskOrderDetail.value.taskStatus;
});

const modifyTimeDialogVisible = ref(false)
const modifyTimeFormRef = ref<FormInstance>()
const modifyTimeForm = reactive({
  newInspectionDate: undefined as string | undefined,
  reason: ''
})

const voidTaskDialogVisible = ref(false)
const voidTaskFormRef = ref<FormInstance>()
const voidTaskForm = reactive({
  reason: ''
})

const showDocPdfDialog = ref(false)
const checkRowReport = ref()
const showDesigner = ref(false)

const checkerSelectVisible = ref(false)
const currentSelectedCheckerIdsForDialog = ref<string[]>([])
const tempSelectedCheckersInDialog = ref<CheckerItem[]>([])

// 检验员组件引用
const checkerSelectRef = ref()
const userSelectFormRef = ref<InstanceType<typeof UserSelectForm> | null>(null)

// 修改主检人相关状态
const mainCheckerDialogVisible = ref(false)
const currentEquipmentRow = ref<any>(null)
const tempSelectedMainChecker = ref<string[]>([])
const tempSelectedMainCheckerInfo = ref<any[]>([])

// 出具报告对话框状态
const generateReportDialogVisible = ref(false)
const currentReportEquip = ref<any>(null)

// 出具报告对话框状态（新的IssueReportDialog）
const issueReportDialogVisible = ref(false)
const currentTaskOrderId = ref('')
const currentReportType = ref<100 | 200>(100)
const currentSelectedEquipment = ref<any>(null)

const orderItemsTableRef = ref<InstanceType<typeof ElTable>>()

/** 服务单/受理单 */
const serviceOrderDialogFormRef = ref<FormInstance>()
const serviceOrderDialogVisible = ref(false)
const serviceRecordListVisible = ref(false)
const businessType = ref<BusinessType>()
const submitting = ref(false)
const serviceOrderDialogFormData = ref<Record<string,any>>({
  serviceFormReceiver: '',
  serviceFormReceiverPhone: '',
  confirmStatus: ''
})

const formRef = ref()
// 选中的设备
const selectedEquips = ref<BoilerTaskOrderItemVO[]>([])

watch(() => props.taskOrder, (newVal) => {
  if (newVal) {
    taskOrderDetail.value = JSON.parse(JSON.stringify(newVal)); // Use deep copy if modifications are made locally, otherwise direct assignment is fine

    // 更新异常单信息
    const orderExceptionRespVO = taskOrderDetail.value.orderExceptionRespVO
    if(orderExceptionRespVO){
      exceptionInfo.value = {
        ...orderExceptionRespVO,
        adjustEffectiveDate: orderExceptionRespVO.adjustEffectiveDate ? dayjs(orderExceptionRespVO.adjustEffectiveDate.join('-')).format('YYYY-MM-DD') : '',
      }
    }
  } else {
    taskOrderDetail.value = null;
  }
}, { immediate: true, deep: true })

const openModifyTimeDialog = () => {
  if (!taskOrderDetail.value) return;
  const currentApptDate = taskOrderDetail.value?.checkDate;
  if (currentApptDate) {
    modifyTimeForm.newInspectionDate = Array.isArray(currentApptDate) ? formatArrayDate(currentApptDate) : currentApptDate
  } else {
    modifyTimeForm.newInspectionDate = undefined;
  }
  modifyTimeForm.reason = ''
  if(modifyTimeFormRef.value) {
    modifyTimeFormRef.value.clearValidate()
  }
  modifyTimeDialogVisible.value = true
}

const handleModifyTaskOrder = () => {
  if (!taskOrderDetail.value?.id) {
    ElMessage.error('任务单ID不存在，无法修改！');
    return;
  }
  router.push({
    name: 'BoilerTaskOrderDetail', // Ensure this route name is correct for editing
    query: {
      id: taskOrderDetail.value.id
    }
  })
}

const handleModifyManager = () => {
  if (!userSelectFormRef.value) {
    ElMessage.error('用户选择组件未加载！');
    return;
  }
  if (!taskOrderDetail.value?.id) {
    ElMessage.error('任务ID无效，无法修改项目负责人！');
    return;
  }
  if (!taskOrderDetail.value?.managerId) {
    ElMessage.error('请先认领再修改项目负责人！');
    return;
  }
  userSelectFormRef.value.open(taskOrderDetail.value.id); // ID is now from taskOrderDetail
}

const handleManagerSelected = async (emittedId: string, selectedUsers: any[]) => {
  //console.log(emittedId);
  if (!taskOrderDetail.value?.id) {
    ElMessage.error('任务ID不存在，无法修改项目负责人！');
    return;
  }
  if (selectedUsers.length === 0) {
    ElMessage.info('未选择新的项目负责人。');
    return;
  }
  const newManager = selectedUsers[0];
  try {
    const payload = {
      id: taskOrderDetail.value.id, // ID from taskOrderDetail
      managerId: newManager.id
    };
    await BoilerTaskOrderApi.updateTaskOrder(payload);
    ElMessage.success('项目负责人更新成功！');
    // 通知父组件刷新数据
    emit('refresh');
  } catch (error) {
    console.error("Failed to update project manager:", error);
    ElMessage.error('项目负责人更新失败！');
  }
}

const openVoidTaskDialog = () => {
  if (!taskOrderDetail.value) return;
  voidTaskForm.reason = ''
  if(voidTaskFormRef.value) {
    voidTaskFormRef.value.clearValidate()
  }
  voidTaskDialogVisible.value = true
}

const openCheckerSelectionDialog = async () => {
  if (!taskOrderDetail.value) {
    ElMessage.warning('无法加载任务单信息');
    return;
  }
  
  checkerSelectVisible.value = true;
  
  // 先获取检验员列表
  await nextTick()
  const deptId = taskOrderDetail.value.deptId?.toString() || userStore.getUser.deptId?.toString() || '1'
  await checkerSelectRef.value?.getCheckerList(deptId)
  
  // 等待数据加载完成后，再从 teamItemList 中构建检验员列表
  await nextTick()
  
  // 从 teamItemList 中构建检验员列表
  const checkers: CheckerItem[] = []
  
  if (taskOrderDetail.value.teamItemList && taskOrderDetail.value.teamItemList.length > 0) {
    taskOrderDetail.value.teamItemList.forEach(team => {
      // 添加组长
      if (team.leaders && team.leaders.length > 0) {
        team.leaders.forEach(leader => {
          checkers.push({
            groupTeamId: team.groupTeamId,
            memberId: leader.id,
            leaderId: leader.id,
            member: leader,
            isLeader: true
          })
        })
      }
      
      // 添加组员
      if (team.members && team.members.length > 0) {
        team.members.forEach(member => {
          checkers.push({
            groupTeamId: team.groupTeamId,
            memberId: member.id,
            leaderId: team.leaders?.[0]?.id || '',
            member: member,
            isLeader: false
          })
        })
      }
    })
  }
  
  tempSelectedCheckersInDialog.value = checkers
  
  // 等待赋值完成后，触发组件内部的状态更新
  await nextTick()
  
  // 手动触发组件内部的全选状态更新
  checkerSelectRef.value?.processedDeptData?.forEach((dept: any) => {
    dept.teamList?.forEach((team: any) => {
      team.memberList?.forEach((subTeam: any) => {
        const availableMembers = subTeam.memberList || []
        const allSubTeamMembers = availableMembers.map((m: any) => subTeam.id + ':' + m.memberId)
        
        if (allSubTeamMembers.length === 0) {
          subTeam.checked = false
          return
        }
        
        const selectedSubTeamMembers = checkers.filter((c: CheckerItem) => 
          allSubTeamMembers.includes(c.groupTeamId + ':' + c.memberId)
        )
        
        subTeam.checked = selectedSubTeamMembers.length === allSubTeamMembers.length
      })
    })
  })
}

/** 处理检验员变化 */
const handleCheckerSelectionChangeInDialog = (checkers: CheckerItem[]) => {
  tempSelectedCheckersInDialog.value = checkers;
}

const confirmCheckerSelectionAndSubmit = async () => {
  if (!taskOrderDetail.value?.id) {
    ElMessage.error('任务ID不存在，无法修改检验员！');
    return;
  }
  try {
    const groupedByTeam: Record<string, { leaderId: string | null; userIds: string[] }> = {};
    tempSelectedCheckersInDialog.value.forEach(checker => {
      if (!checker.groupTeamId) {
        console.warn('Checker missing groupTeamId:', checker);
        return;
      }
      if (!groupedByTeam[checker.groupTeamId]) {
        groupedByTeam[checker.groupTeamId] = { leaderId: null, userIds: [] };
      }
      if (checker.isLeader) {
        groupedByTeam[checker.groupTeamId].leaderId = checker.memberId;
      } else {
        groupedByTeam[checker.groupTeamId].userIds.push(checker.memberId);
      }
    });
    const teamList = Object.keys(groupedByTeam).map(groupTeamId => ({
      groupTeamId: groupTeamId,
      leaderId: groupedByTeam[groupTeamId].leaderId,
      userIds: groupedByTeam[groupTeamId].userIds
    }));
    if (teamList.length < 1){
      ElMessage.error('请选择检验员！');
      return;
    }
    const data = {
      id: taskOrderDetail.value.id, // ID from taskOrderDetail
      teamList: teamList
    };
    await BoilerTaskOrderApi.updateCheckers(data);
    ElMessage.success('检验人员更新成功！');
    checkerSelectVisible.value = false;
    // 通知父组件刷新数据
    emit('refresh');

  } catch (error) {
    console.error("Failed to update checkers:", error);
    ElMessage.error('检验人员更新失败！');
  }
}

const handleSubmitModifyTime = async () => {
  if (!modifyTimeFormRef.value) return
  if (!taskOrderDetail.value?.id) {
    ElMessage.error('任务ID不存在，无法修改检验时间！')
    return
  }
  await modifyTimeFormRef.value.validate(async (valid) => {
    if (valid) {
      if (!taskOrderDetail.value) {
        ElMessage.error('任务详情为空，无法修改！')
        return
      }
      const taskOrderDetailCopy = JSON.parse(JSON.stringify(taskOrderDetail.value))
      taskOrderDetailCopy.checkDate = modifyTimeForm.newInspectionDate
      const data = {
        id: taskOrderDetail.value.id, // ID from taskOrderDetail
        objId: taskOrderDetail.value.id, // objId from taskOrderDetail
        checkDate: modifyTimeForm.newInspectionDate,
        reason: modifyTimeForm.reason,
        changeType: 100,
        afterJson: JSON.stringify(taskOrderDetailCopy)
      }
      try {
        await BoilerTaskOrderApi.createTaskOrderOperationRecord(data)
        ElMessage.success('修改检验时间请求已提交！')
        modifyTimeDialogVisible.value = false
        // 通知父组件刷新数据
        emit('refresh');
      } catch (error) {
        ElMessage.error('提交修改检验时间失败！')
      }
    }
  })
}

const handleSubmitVoidTask = async () => {
  if (!voidTaskFormRef.value) return
  if (!taskOrderDetail.value?.id) {
    ElMessage.error('任务ID不存在，无法作废！')
    return
  }
  await voidTaskFormRef.value.validate(async (valid) => {
    if (valid) {
      const data = {
        id: taskOrderDetail.value.id, // ID from taskOrderDetail
        objId: taskOrderDetail.value.id, // objId from taskOrderDetail
        reason: voidTaskForm.reason,
        changeType: 300
      }
      try {
        await BoilerTaskOrderApi.createTaskOrderOperationRecord(data)
        ElMessage.success('作废任务单请求已提交！')
        voidTaskDialogVisible.value = false
        // 通知父组件刷新数据
        emit('refresh');
      } catch (error) {
        ElMessage.error('提交作废任务单失败！')
      }
    }
  })
}

const handleSetMainChecker = (row: any) => {

  if (!isCanAddFlag(row)){
    return
  }

  currentEquipmentRow.value = row
  // 如果当前有主检人，预选中该主检人
  if (row.mainCheckerUserId) {
    tempSelectedMainChecker.value = [row.mainCheckerUserId]
  } else {
    tempSelectedMainChecker.value = []
  }
  tempSelectedMainCheckerInfo.value = []
  mainCheckerDialogVisible.value = true
}

/** 处理主检人选择变化 - 单选逻辑 */
const handleMainCheckerSelectionChange = (checkers: any[]) => {
  // 实现单选逻辑：如果选择了新的检验员，只保留最后选择的一个
  //console.log(checkers)
  if (checkers.length > 1) {
    // 获取新选择的检验员（最后一个）
    const newSelected = checkers[checkers.length - 1]
    tempSelectedMainChecker.value = [newSelected.groupTeamId + ':' + newSelected.memberId]
    tempSelectedMainCheckerInfo.value = [newSelected]
  } else if (checkers.length === 1) {
    tempSelectedMainChecker.value = [checkers[0].groupTeamId + ':' + checkers[0].memberId]
    tempSelectedMainCheckerInfo.value = [checkers[0]]
  } else {
    tempSelectedMainChecker.value = []
    tempSelectedMainCheckerInfo.value = []
  }
}

/** 确认修改主检人 */
const confirmMainCheckerSelection = async () => {
  if (tempSelectedMainChecker.value.length === 0) {
    ElMessage.warning('请选择一个主检人')
    return
  }

  if (!currentEquipmentRow.value?.id) {
    ElMessage.error('设备信息无效，无法修改主检人')
    return
  }

  try {
    // 调用修改主检人的API
    const data = {
      id: currentEquipmentRow.value.mainID,
      mainCheckerId: tempSelectedMainChecker.value[0].split(':')[1]
    }
    await BoilerTaskOrderApi.updateTaskOrderMainChecker(data)

    ElMessage.success('主检人修改成功')
    mainCheckerDialogVisible.value = false

    // 通知父组件刷新数据
    emit('refresh');

  } catch (error) {
    console.error('修改主检人失败:', error)
    ElMessage.error('修改主检人失败')
  }
}

/** 实体报告 */
const handleEntityReport = (row: any) => {
  currentTaskOrderId.value = taskOrderDetail.value?.id || ''
  currentReportType.value = 100
  currentSelectedEquipment.value = row
  issueReportDialogVisible.value = true
}


/** 出具报告确认 */
const handleIssueReportConfirm = (data: any) => {
  console.log('出具报告数据:', data)
  // 刷新数据
  emit('refresh')
}

/** 出具报告成功回调 */
const handleGenerateReportSuccess = () => {
  // 刷新数据或其他处理
  emit('refresh')
}

const handleConfirm = async () => {
  //taskOrderDetail.value.id
  try {
    await ElMessageBox.confirm('是否认领该任务单？', '认领提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await BoilerTaskOrderApi.confirmTaskOrder({ id:taskOrderDetail.value.id, "confirm": true })
    ElMessage.success('认领成功')
    if (props.inPageMode) {
      tagsViewStore.closeSelectedTag(route)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('认领失败')
      console.error('Confirm error:', error)
    }
  }
}

// 取消认领
const handleCancelConfirm = async () => {
  try {
    await ElMessageBox.confirm('是否取消认领该任务单？', '取消认领提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await BoilerTaskOrderApi.confirmTaskOrder({ id:taskOrderDetail.value.id, "confirm": false })
    ElMessage.success('取消认领成功')
    if (props.inPageMode) {
      tagsViewStore.closeSelectedTag(route)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消认领失败')
      console.error('Cancel confirm error:', error)
    }
  }
}

const handleClosePage = () => {
  if (props.inPageMode) {
    tagsViewStore.closeSelectedTag(route)
  }
}


/**
 * 安全检查记录弹窗
 * @param { visible } 显示状态
 * ***/
const savetyCheckRecordListVsible = ref(false)
// 安全检查记录弹窗 携带参数
const savetyCheck = reactive({
  checkId: '',
  orderId: '',
})

const handleAddSafetyRecord = async () => {

  const confirmed = await ElMessageBox.confirm('是否确定添加安全检查记录？', '添加安全检查记录提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).catch(() => false);

  if (!confirmed) {
    return;
  }

  savetyCheckRecordListVsible.value = true
  savetyCheck.orderId = taskOrderDetail.value.id
}

watch(() => savetyCheckRecordListVsible.value, (savetyCheckRecordListVsible) => {
  if(savetyCheckRecordListVsible) return
  savetyCheck.checkId = ''
  savetyCheck.orderId = ''
})

// 安全检查记录列表弹窗
const showSavetyCheckRecordVersions = ref(false)
const savetyRecordList = ref([])
const savetyRecordPageSize = ref(10)
const savetyRecordPageNo = ref(1)
const savetyRecordTotal = ref(0)
const savetyRecordColumns = ref([
  {
    label: '名称',
    prop: 'name',
  },
  {
    label: '日期',
    prop: 'date',
    render: (row, value) => (value ? dayjs(value).format('YYYY-MM-DD') : '-')
  },
  {
    label: '有效期至',
    prop: 'validityDate',
    render: (row, value) => (value ? dayjs(value).format('YYYY-MM-DD') : '-')
  },
  {
    label: '检查结论',
    prop: 'conclusion',
  },
  {
    label: '操作',
    prop: '',
    render: (row) => {
      return <div>
        <el-button link type="primary" onClick={() => handleModifySavetyRecord(row)}>修改</el-button>
        <el-button link type="danger" onClick={() => handleDeleteSavetyRecord(row)}>删除</el-button>
      </div>
    }
  }
])
const fetchSafetyCheckRecordPage = async () => {
  const result = await BoilerTaskOrderApi.getSafetyCheckRecordPage({
    pageNo: savetyRecordPageNo.value,
    pageSize: savetyRecordPageSize.value,
    orderId: taskOrderDetail.value.id
  })
  if(result) {
    savetyRecordList.value = result.list
    savetyRecordTotal.value = result.total
    taskOrderDetail.value.securityCheckCount = result.total
  }
}

const handleModifySavetyRecord = (row) => {
  // 修改安全检查记录
  savetyCheckRecordListVsible.value = true
  savetyCheck.orderId = taskOrderDetail.value.id
  savetyCheck.checkId = row.id
}

const handleDeleteSavetyRecord = (row) => {
  ElMessageBox.confirm(`确定要删除【${row.name}】吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 恢复版本
    // TODO: 这里发起删除请求 --- 缺少删除接口
    const delRes = await BoilerTaskOrderApi.deleteSafetyCheckRecord({ id: row.id })
    if(delRes) {
      ElMessage.success('删除成功')
      await fetchSafetyCheckRecordPage()
    }
  }).catch(() => {
    // 取消恢复版本
  })
}

const safetyCheckRecordPdfUrl = ref('')
const savetyCheckRecordPdfLoading = ref(false)
const handleSafetyCheckRecordPdfRendered = () => {
  console.log('安全检查记录PDF渲染完成')
  savetyCheckRecordPdfLoading.value = false
}

// 安全检查记录回调方法
const handleUpdateSavetyCheckRecordList = () => {
  fetchSafetyCheckRecordPage()
}

/** 表格选择框变化 */
const handleEquipSelectionChange = (selection: BoilerTaskOrderItemVO[]) => {
  // 实现设备选择逻辑
  selectedEquips.value = selection
}

/** 处理批量修改约检联系人 */
const handleBatchConcat = () => {
  if (selectedEquips.value.length === 0) {
    message.warning('请至少选择一条记录')
    return
  }
  if (!isCanAddFlag()){
    return
  }
  formRef.value.open(selectedEquips.value, 'taskOrder')
}

/** 修改成功处理 */
const handleScheduleSuccess = () => {
  selectedEquips.value = []
  //通知父组件刷新数据
  emit('refresh');
}

/*****  重大问题线索&检验方案&作业指导书  *****/
const supportingDocsAuditDataList = ref<Recordable[]>([])
const supportingDocsAuditColumns = ref([
  {
    label: '设备注册代码',
    prop: 'equipCode',
  },
  {
    label: '项目名称',
    prop: 'reportName'
  },
  {
    label: '类型',
    prop: 'reportType',
    render: (row, reportType) => {
      return PressureReportTypeMap[reportType] || '-'
    }
  },
  {
    label: '状态',
    prop: 'status',
    render: (row, status) => !status ? '-' : PressureTaskOrderStatusMap[status]
  },
  {
    label: '当前流程',
    prop: 'currentNode',
    render: (row) => {
      switch(row.status) {
        case PressureTaskOrderStatus['CANCELLED']:
          return '-'
        case PressureTaskOrderStatus['APPROVED']:
          return '审核通过'
        case PressureTaskOrderStatus['AUDITING']:
        case PressureTaskOrderStatus['REJECTED']:
          return <div>
            <p>当前流程：{row?.currentNode || '-'}</p>
            <p>状态：{row.status === PressureTaskOrderStatus['AUDITING'] ? '审核中' : `${row?.currentAuditor?.nickname}（${row?.currentAuditor?.id}）拒绝`}</p>
          </div>
        default:
          return '-'
      }
    }
  },
  {
    label: '退回原因',
    prop: 'returnReason',
    render: (row, returnReason) => {
      return returnReason || '-'
    }
  },
  {
    label: '提交人',
    prop: 'submitUser',
    render: (row, submitUser) => {
      return submitUser?.nickname || '-'
    }
  },
  {
    label: '提交时间',
    prop: 'submitTime',
    render: (row, submitTime) => {
      return !submitTime ? '-' : dayjs(submitTime).format('YYYY-MM-DD')
    }
  },
  {
    label: '操作',
    prop: '',
    render: (row) => {
      switch(row.status) {
        case PressureTaskOrderStatus['AUDITING']:
        case PressureTaskOrderStatus['APPROVED']:
          return <el-button link type="primary" onClick={() => newHandleOperationReport(row, 'view')}>查看详情</el-button>
        // case PressureTaskOrderStatus['APPROVED']:
        //   return <el-button link type="primary" onClick={() => handleAssociateEquipment(row)}>关联设备</el-button>
        case PressureTaskOrderStatus['REJECTED']:
          return <div>
            <el-button link type="primary" onClick={() => handleResubmitDocs(row)}>重新提交</el-button>
            <el-button link type="primary" onClick={() => handleCancelDocs(row)}>作废</el-button>
          </div>
        case 0:
          return <div>
            <el-button link type="primary" onClick={() => handleCancelDocs(row)}>作废</el-button>
            <el-button link type="primary" onClick={() => newHandleOperationReport(row, 'edit')}>编辑</el-button>
          </div>
        default:
          return '-'
      }
    }
  },
])

/*****   异常信息 start  *****/
const getExceptionItem = (field: string, fieldAttr: string)=>{
  const fileUrl = exceptionInfo.value[fieldAttr] && buildFileUrl(exceptionInfo.value[fieldAttr])
  const fileName = exceptionInfo.value[field]
  if(fileUrl) {
    return (
      <>
        <div class="flex items-center w-full p-l-10px p-r-10px hover:bg-gray-100 rounded-6px">
          {/* <el-tooltip content={fileName}>  */}
          <span class="flex-1 text-ellipsis overflow-hidden whitespace-nowrap">{fileName}</span>
          {/* </el-tooltip>  */}
          <div class="ml-10px">
            <el-link href={fileUrl} underline={false} download target="_blank" type="primary">下载</el-link>
          </div>
          {/* <div class="ml-10px">
            <el-button link type="danger" onClick={()=>handleRemove(field, fieldAttr)}>删除</el-button>
          </div> */}
        </div>
      </>
    )
  } else {
    return (
      <el-button type="primary" onClick={()=>handleOpenFileUploadModal(field, fieldAttr)}>
        <Icon icon="ep:upload-filled" />
        <span>附件上传</span>
      </el-button>
    )
  }
}

const handleGetExceptionInfo = (id: string) => {
  BoilerAppointmentConfirmOrderApi.getExceptionInfo(id).then((res) => {
    if(res) exceptionInfo.value = {
      ...res,
      adjustEffectiveDate: res.adjustEffectiveDate?.join('-')
    }
  }).catch((error)=>{
    console.log(error, '-----error--->')
    ElMessage.error(error)
  })
}

const fileUploadModalRef = ref<InstanceType<typeof FileUploadModal>>();
const currentUploadMap = reactive({
  field: '',
  fieldAttr: '',
})

const handleOpenFileUploadModal = (type: string, attach: string) => {
  currentUploadMap.field = type
  currentUploadMap.fieldAttr = attach
  fileUploadModalRef.value?.open()
}
const handleFileUploadSuccess = (fileInfo:{fileName: string, fileUrl: string}) => {
  exceptionInfo.value[currentUploadMap.field] = fileInfo.fileName
  exceptionInfo.value[currentUploadMap.fieldAttr] = fileInfo.fileUrl
  console.log('handleFileUploadSuccess:', exceptionInfo.value)
}
/*****   异常信息 end  *****/

// 获取服务单/受理单模板
type BusinessType = 100 | 200 | 400
const handleServiceOrder = (type: BusinessType) => {
  console.log(type)
  if (type == 100){
    orderDialogRef.value?.open()
    return
  }
  businessType.value = type
  serviceRecordListVisible.value = true
  // isAddMainquestion.value = 'edit'
  // serviceOrderDialogVisible.value = true
  // const currentBusinessType = getSignFilePath(type)
  // serviceOrderDialogFormData.value.confirmStatus = currentBusinessType.isSignature || '0'
  // downloadSignFilePdf.value = currentBusinessType.signFilePdf
}

// 获取审核列表
const operationReportPageNo = ref(1)
const operationReportPageSize = ref(10)
const operationReportTotal = ref(0)
const handleGetOperationReportAuditList = async () => {
  const auditListResult = await BoilerTaskOrderApi.getMajorIssuesAuditList({
    pageNo: operationReportPageNo.value,
    pageSize: operationReportPageSize.value,
    orderId: route.query.id,
    // notStatusList: 200,
  })
  supportingDocsAuditDataList.value = auditListResult.list.filter(item => {
    // if([PressureReportType.INSPECTIONPLAN, PressureReportType.WORKINSTRUCTION].includes(item.reportType)){
    //   return item.status !== 200
    // } else {
    //   return item
    // }
    return item
  })
  operationReportTotal.value = auditListResult.total
}
handleGetOperationReportAuditList()

// 添加重大问题线索 & 检验方案 & 作业指导书
// reportType：500重大问题线索通知 600 检验方案 700 作业指导书
const curMainquestionEquipmentRow = ref<Recordable>({})
const isAddMainquestion = ref<'add' | 'edit' | 'view'>('view')
const mainOrderItemId = ref('')
const mainReportId = ref('')
const editOperationReportVisible = ref(false)
const editOperationReportTypeTitle = ref('')
const editOperationReportParams = ref<Record<string, any>>({
  templateId: '',
  reportId: '',
  orderId: '',
  prepareJson: ''
})

/*****   添加检验项目   *****/
const isBatchAdd = ref(false)
const showAddCheckItemsDialog = ref(false)
const selectedEquipmentIds = ref<string[]>([])
const selectedOrderIds = ref<string[]>([])
const checkItemIds = ref<string[]>([])
const canAddReportItem = (taskStatus)=>{
  const {REPORT_AUDIT, REPORT_APPROVE, REPORT_END} = PressureCheckerMyTaskStatus
  return [REPORT_AUDIT, REPORT_APPROVE, REPORT_END].includes(taskStatus)
}
const isCanAddFlag = (row?:any) =>{

  let selectedItems = [] as any[]
  if(row) {
    isBatchAdd.value = false
    selectedItems.push(row)
    selectedEquipmentIds.value = [row?.equipId]
    selectedOrderIds.value = [row?.mainID]
    checkItemIds.value = (row.reportRespVOList || []).map(item => item.templateId)
  } else {
    isBatchAdd.value = true
    selectedItems = orderItemsTableRef.value?.getSelectionRows() || []
    selectedEquipmentIds.value = selectedItems.map(item => item?.equipId)
    selectedOrderIds.value = selectedItems.map(item => item?.mainID)
    if(selectedItems.length >= 1) {
      checkItemIds.value = (selectedItems[0].reportRespVOList || []).map(item => item.templateId)
    }
  }
  if(selectedItems.length === 0) {
    ElMessage.warning('请选择设备单！')
    return false
  }
  // 校验选中行的状态是否存在 报告审核/审核/办结
  let canAddFlag = true
  selectedItems.forEach(row=>{
    if(canAddReportItem(row.taskStatus)) {
      ElMessage.warning(`设备:${row.equipCode}的主报告状态为${PressureCheckerMyTaskStatusMap[row.taskStatus]}，不能进行调整！`)
      canAddFlag = false
    }
  })
  return canAddFlag

}
const handleAddCheckerItems = (row?: any) => {

  if (!isCanAddFlag(row)){
    return
  }

  // let selectedItems = [] as any[]
  // if(row) {
  //   isBatchAdd.value = false
  //   selectedItems.push(row)
  //   selectedEquipmentIds.value = [row?.equipId]
  //   selectedOrderIds.value = [row?.mainID]
  //   checkItemIds.value = (row.reportRespVOList || []).map(item => item.templateId)
  // } else {
  //   isBatchAdd.value = true
  //   selectedItems = orderItemsTableRef.value?.getSelectionRows() || []
  //   selectedEquipmentIds.value = selectedItems.map(item => item?.equipId)
  //   selectedOrderIds.value = selectedItems.map(item => item?.mainID)
  //   if(selectedItems.length >= 1) {
  //     checkItemIds.value = (selectedItems[0].reportRespVOList || []).map(item => item.templateId)
  //   }
  // }
  // if(selectedItems.length === 0) {
  //   ElMessage.warning('请选择设备单！')
  //   return
  // }
  // // 校验选中行的状态是否存在 报告审核/审核/办结
  // let canAddFlag = true
  // selectedItems.forEach(row=>{
  //   if(canAddReportItem(row.taskStatus)) {
  //     ElMessage.warning(`设备:${row.equipCode}的主报告状态为${PressureCheckerMyTaskStatusMap[row.taskStatus]}，不能添加检验项目！`)
  //     canAddFlag = false
  //   }
  // })
  // if(!canAddFlag) return
  showAddCheckItemsDialog.value = true
}
/*****   添加检验项目 end   *****/

//判断主报告状态
const checkMainStatus = (row?: any) => {

  // 校验选中行的状态是否存在 报告审核/审核/办结
  let canAddFlag = true
  selectedItems.forEach(row=>{
    if(canAddReportItem(row.taskStatus)) {
      ElMessage.warning(`设备:${row.equipCode}的主报告状态为${PressureCheckerMyTaskStatusMap[row.taskStatus]}，不能添加检验项目！`)
      canAddFlag = false
    }
  })
  return canAddFlag;

}

const getRowReportVOList = (row)=>{
  return (row.reportRespVOList || []).filter(item=>item.reportType !== PressureReportType['WORKINSTRUCTION'])
}
const filterReportType = (list: any[])=>{
  return (list || []).filter(item=>item.reportType === PressureReportType['WORKINSTRUCTION'])
}

// 添加检验方案/查看检验方案按钮
const initEditOperationReportParams = JSON.parse(JSON.stringify(editOperationReportParams.value))
const addInspectionplanRef = ref<InstanceType<typeof AddInspectionplan>>()
const isEdit = ref<'add' | 'edit' | 'view'>('view')
const editInspectionplanParams = ref<Recordable>({
  ...initEditOperationReportParams.value,
})
const AddInspectionplanDetailVisible = ref(false)
const inspectionplanDetail = ref({})
const handleUpdateInspectionplanDetail = (info) => {
  console.log('handleUpdateInspectionplanDetail-info:', info )
  editInspectionplanParams.value = {
    ...editInspectionplanParams.value,
    ...info
  }
}
const handleRefreshInspectionplan= ()=>{
  // 重新获取审核列表数据
  operationReportPageNo.value = 1
  handleGetOperationReportAuditList()
}
const handleAddInspectionplanReport = async () => {
  try {
    if (!isCanAddFlag()){
      return
    }
    // 查询检验方案模板数据
    const options = ref<any[]>([])
    const params = { type: '6',reportType : 600 }
    const response = await getPressureReportTemplateListNoLimit({...params, pageNo: 1, pageSize: 100, status: 200})
    options.value = response?.data?.list || response?.list || response || []
    const newParams = {
      options: options.value.map(item => ({
        ...item,
        label: item.tbName,
        value: item.id
      })),
      formData: {
        orderId: taskOrderDetail.value.id,
      },
      equipCount: unref(selectedEquips).length
    }
    // 添加检验方案逻辑
    addInspectionplanRef.value?.open(newParams, '添加检验方案')
  } catch (error) {
    // 处理接口错误
    ElMessage({
      type: 'error',
      message: 'Failed to load options'
    });
    console.error('API error:', error);
  }
}

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

const newHandleOperationReport = async (row, type: 'add' | 'edit' | 'view' | '' = '') => {
  if(row.reportType === PressureReportType.MAINQUESTION){
    return handleMainquestionAddReport(row.reportType, type, row)
  }
  // 如果是检验方案走检验方案的逻辑
  if(row.reportType === PressureReportType['INSPECTIONPLAN']) {
    // 检验方案
    editInspectionplanParams.value = {
      ...editInspectionplanParams.value,
      reportId: row.id,
      templateId: row.templateId,
      orderId: taskOrderDetail.value.id,
    }
    inspectionplanDetail.value = row
    if(!row.status){
      // const templateInitJSON =  await getPressureReportTemplateMockJSON( {taskOrderNo: props.taskOrder.orderNo,
      //   templateId: row.templateId})
      // editInspectionplanParams.value.prepareJson = templateInitJSON
    }
    isEdit.value = type ? type : !row.status ? 'add' : 'edit'
    AddInspectionplanDetailVisible.value = true
    return
  }
  //作业指导书 选择的是模板，则直接通过葡萄城进行查看预览
  if(row.reportType === PressureReportType['WORKINSTRUCTION']) {
    return handleWorkBookDetail(row,type !== 'view')
  }
  // 查看文件详情的pdf
  showDocPdfDialog.value = true
  checkRowReport.value = row
  showDesigner.value = !!row.templateId
}

// 作业指导书查看详情/编辑
const handleWorkBookDetail = (row, isEdit = false)=>{
  //isCustomFileUrl.value = !row.templateId
  editOperationReportTypeTitle.value = PressureReportTypeMap[row.reportType]
  editOperationReportParams.value = {
    ...editOperationReportParams.value,
    reportId: row.id,
    templateId: row.templateId,
    orderId: taskOrderDetail.value.id,
    prepareJson: row.prepareJson
  }
  isWorkBookEdit.value = isEdit
  editWorkBookReportVisible.value = true
}

/*****   费用计算   *****/
const calcEquipmentId = ref('')
const calcTemplateInfo = ref({})
const showCalcCheckItemFeeDialog = ref(false)
const handleInputCalcField = async (equipId, item) => {
  try {
    calcTemplateInfo.value = item
    calcEquipmentId.value = equipId
    showCalcCheckItemFeeDialog.value = true
  } catch (error) {
    ElMessage.error('录入费用出错啦！')
    console.error('录入费用出错啦！', error)
  }
}

const handleSaveCalcFee = async (templateInfo) => {
  // 更新检验项目的费用
  const updateRes = await BoilerTaskOrderApi.updateCheckItemFee({id: templateInfo.id, fee: templateInfo.fee, feeCalculateJson: templateInfo.feeCalculateJson })
  if(updateRes) {
    emit('refresh')
    ElMessage.success('费用已更新')
  }
}
/*****   费用计算 end  *****/
/*
* 添加重大问题线索
* */
const handleMainquestionAddReport = async (reportType, type: 'add' | 'edit' | 'view', row?: Recordable) => {

  if (!reportType) return ElMessage.error('未知的报告类型')
  if (!row && unref(selectedEquips).length !== 1) return ElMessage.error('请选择一台设备')
  if (type !== 'view' && !isCanAddFlag(row)){
    return
  }
  isAddMainquestion.value = type
  console.log('isAddMainquestion:log', isAddMainquestion.value)
  mainReportId.value = row ? row.id : ''
  mainOrderItemId.value = row ? row.orderItemId : unref(selectedEquips)[0].mainID
  curMainquestionEquipmentRow.value = row ? {...row} : unref(selectedEquips)[0]

  // 校验审核列表是否已经存在
  const existingAudit = supportingDocsAuditDataList.value.find(item => item.reportType === reportType && item.orderItemId === curMainquestionEquipmentRow.value.mainID)
  if (existingAudit) {
    ElMessage.error('该设备已存在该类型的报告')
    return
  }

  if (type == 'add'){
    const confirmed = await ElMessageBox.confirm('是否确定添加重大问题线索？', '添加重大问题线索提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).catch(() => false);

    if (!confirmed) {
      return;
    }
  }

  handleServiceOrder(400)
}

const handleSuccessInspectionplan = async (info) => {
  const firstOrderItem = unref(taskOrderDetail).orderItems[0] || {}
  const params: Recordable = {
    taskOrderNo: props.taskOrder.orderNo,
    templateId: info.templateId,
  }
  if (firstOrderItem.equipCode) {
    params.equipCode = firstOrderItem.equipCode
  }
  try {
    // 1.获取选中模板配置信息
    //const templateInitJSON = await getPressureReportTemplateMockJSON(params)
    const templateInitJSON = null;
    const defaultUser: Record<string, any> = {
      prepareName: unref(userInfo)?.nickname,
      prepareDate: dayjs().format('YYYY年MM月DD')
    }
    const prepareJson = templateInitJSON ? {...JSON.parse(templateInitJSON), ...defaultUser} : defaultUser
    // 2.组装参数， 生成新的检验方案记录，
    const addParams = {
      orderId: taskOrderDetail.value.id,
      templateId: info.templateId,
      prepareJson: JSON.stringify(prepareJson),
      prepareId: unref(userInfo)?.id,
      prepareName: unref(userInfo)?.nickname,
      orderItemIds: selectedEquips.value.map(item => item.mainID),
      reportName: info.reportName,
    }
    const newReportId = await BoilerTaskOrderApi.addMajorIssues(addParams)
    editInspectionplanParams.value = {
      reportId: newReportId,
      templateId: info.templateId,
      orderId: taskOrderDetail.value.id,
      // prepareJson: templateInitJSON ? JSON.parse(templateInitJSON) : ''
      prepareJson: JSON.stringify(prepareJson),
    }
    isEdit.value = 'add'
    AddInspectionplanDetailVisible.value = true
  } catch (error) {
    ElMessage.error('获取模板失败')
  }
}

const handleUpdateServiceRecordList = ()=>{
  isAddMainquestion.value = 'view'
  emit('refresh');
}

const showViewMainquestionBtn = (row: Recordable)=>{
  return supportingDocsAuditDataList.value.some(item => item.reportType === PressureReportType.MAINQUESTION && item.orderItemId === row.mainID)
}

const handleViewMainquestionReport = (row: Recordable)=>{
  if(!showViewMainquestionBtn(row)) return ElMessage.error('该设备不存在该类型的报告')
  const checkAuditRow = unref(supportingDocsAuditDataList).find(item => item.reportType === PressureReportType.MAINQUESTION && item.orderItemId === row.mainID)
  newHandleOperationReport(checkAuditRow, 'view')
}

const handleLookSecurityCheck = async () => {
  showSavetyCheckRecordVersions.value = true
  await fetchSafetyCheckRecordPage()
}

//添加作业指导书
// 记录当前的报告类型相关信息
const addBookAndCheckSchemeRef = ref<InstanceType<typeof AddBookAndCheckScheme>>()
const curReportType = ref()
const editWorkBookReportVisible = ref(false)
const curReportTypeInfo = reactive({
  reportType: '',
  data: {}
})
const handleAddReport = async (reportType, row?: Recordable) => {

  if (!isCanAddFlag(row)){
    return
  }

  // 更新记录操作行信息
  curReportTypeInfo.reportType = reportType
  curReportTypeInfo.data = {...row}
  // 创建一个带ElSelect组件的弹窗
  const dialogSelectedValue = ref<string | number>('')
  const createElSelectFormDialog = (options, label) => {
    return defineComponent({
      setup() {
        return () => h('div', [
          h('p', { style: 'margin-bottom: 6px' }, label),
          h(ElSelect, {
            modelValue: dialogSelectedValue.value,
            'onUpdate:modelValue': (value: string) => {
              dialogSelectedValue.value = value;
            },
            placeholder: '请选择' + label,
            style: 'width: 100%'
          }, options.map(option =>
            h(ElOption, {
              key: option.id,
              label: option.name,
              value: option.id
            })
          ))
        ]);
      }
    });
  }
  try {
    if(!reportType) {
      ElMessage.error('未知的报告类型')
      return
    }
    // 获取下拉选择框的options数据
    const options = ref<any[]>([])
    const params = {}
    switch (reportType) {
      // case PressureReportType['MAINQUESTION']:
      //   params['classId'] = 'd799cf8309fa17df5bb87766fc10e00b'
      //   break
      // case PressureReportType['INSPECTIONPLAN']:
      //   // 检验方案
      //   params['type'] = '6'
      //   break
      case PressureReportType['WORKINSTRUCTION']:
        // 作业指导书
        params['reportType'] = '700'
        break
      default:
        return
    }
    // 获取指定项目类型的报告
    const response = await getPressureReportTemplateListNoLimit({...params, pageNo: 1, pageSize: 100, status: 200})
    options.value = response?.data?.list || response?.list || response || []
    if([PressureReportType['INSPECTIONPLAN'], PressureReportType['WORKINSTRUCTION']].includes(reportType)) {
      curReportType.value = reportType
      // 检验方案 & 作业指导书 调整修改逻辑其他的保持不变
      const newParams = {
        title: PressureReportTypeMap[reportType],
        options: options.value.map(item => ({
          ...item,
          label: item.tbName,
          value: item.id
        })),
        formData: {
          ...row,
          orderId: taskOrderDetail.value.id,
          // templateId: dialogSelectedValue.value,
        }
      }
      // 添加检验方案逻辑
      // if(reportType === PressureReportType['INSPECTIONPLAN']) {
      //   addInspectionplanRef.value?.open(newParams, '添加检验方案')
      //   return
      // }
      addBookAndCheckSchemeRef.value?.open(newParams, reportType)
      return
    }

    // 4. 显示自定义弹窗
    ElMessageBox({
      title: '关联项目模板',
      message: h(createElSelectFormDialog(options.value, '项目模板')),
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      showCancelButton: true,
      customClass: 'customPromptStyle',
      beforeClose: (action: Action, instance, done) => {
        if((dialogSelectedValue.value && action === 'confirm') || action === 'cancel') {
          done()
        } else {
          ElMessage.error('请选择项目模板')
        }
      }
    }).then(async () => {
      if(dialogSelectedValue.value) {
        if (params['type'] == '700') {
          // 这里去打开模板
          editOperationReportVisible.value = true
          editOperationReportTypeTitle.value = PressureReportTypeMap[reportType]
          editOperationReportParams.value = {
            ...editOperationReportParams.value,
            templateId: dialogSelectedValue.value,
            orderId: taskOrderDetail.value.id,
          }
          dialogSelectedValue.value = ''
        }
      }
    }).catch((error) => {
      dialogSelectedValue.value = ''
    });

  } catch (error) {
    // 处理接口错误
    ElMessage({
      type: 'error',
      message: 'Failed to load options'
    });
    console.error('API error:', error);
  }
}

// 添加作业指导书
const handleSuccessReport = async (info) => {
  const reportList = filterReportType(info.reportRespVOList);
  const templateIds = (reportList || []).filter(item=>item.templateId === info.templateId)
  if (templateIds.length > 0){
    ElMessage.error('该设备已存在该作业指导书')
    return
  }
  if(!info) return handleEditOperationReportList()
  // 如果选择的是模板，则还是走之前的逻辑，打开葡萄城进行编辑提交
  if(info?.addType === '2' && info.id){
    // 这里去打开模板
    editOperationReportTypeTitle.value = PressureReportTypeMap[unref(curReportType)]
    editOperationReportParams.value = {
      ...editOperationReportParams.value,
      templateId: info.templateId,
      orderId: taskOrderDetail.value.id,
      orderItemId: info.mainID,
      // 操作指导书，初始化编制人和编制时间
      // prepareJson: JSON.stringify({
      //   prepareName: unref(userInfo)?.nickname,
      //   prepareDate: dayjs().format('YYYY年MM月DD'),
      // })
    }
    isWorkBookEdit.value = true
    //添加操作指导书
    if (!editOperationReportParams.value.reportId) {
      // 初次编辑模板 需要添加报告
      // newReportId 返回的是reportId
      const params: Recordable = {
        orderId: editOperationReportParams.value.orderId,
        templateId: editOperationReportParams.value.templateId,
        prepareId: unref(userInfo)?.id,
        prepareName: unref(userInfo)?.nickname,
        orderItemId: editOperationReportParams.value.orderItemId
      }
      editOperationReportParams.value.reportId = await BoilerTaskOrderApi.addMajorIssues(params)
    }
    editWorkBookReportVisible.value = true
  }
}

const handleEditOperationReportList = () => {
  // 重新获取列表数据
  // operationReportPageNo.value = 1
  // handleGetOperationReportAuditList()
  // editOperationReportParams.value = initEditOperationReportParams.value
  emit('refresh');
}

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 isCustomFileUrl = ref(false)
const handleResubmitDocs = async (row) => {
  if(row.reportType === PressureReportType.MAINQUESTION){
    return handleMainquestionAddReport(row.reportType, 'edit', row)
  }
  // 如果是检验方案走检验方案的逻辑
  if(row.reportType === PressureReportType['INSPECTIONPLAN']) {
    // 检验方案
    editInspectionplanParams.value = {
      reportId: row.id,
      templateId: row.templateId,
      orderId: taskOrderDetail.value.id,
      prepareJson: row.prepareJson || ''
    }
    inspectionplanDetail.value = row
    isEdit.value = 'edit'
    AddInspectionplanDetailVisible.value = true
    return
  }
  isCustomFileUrl.value = !row.templateId

  // 重新提交
  editOperationReportTypeTitle.value = PressureReportTypeMap[row.reportType]
  editOperationReportParams.value = {
    ...editOperationReportParams.value,
    reportId: row.id,
    templateId: row.templateId,
    orderId: taskOrderDetail.value.id,
    prepareJson: row.prepareJson
  }
  // 作业指导书 重新提交审批
  if(row.reportType === PressureReportType['WORKINSTRUCTION']) {
    return  handleWorkBookDetail(row, true)
  }
  editOperationReportVisible.value = true
}

const handleCancelDocs = async (item) => {
  // 作废项目
  try {
    const { value: voidReason } = await ElMessageBox.prompt(
      `确定要作废项目 ${item.reportName} 吗？`,
      '作废项目',
      {
        confirmButtonText: '确认作废',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入作废原因',
        inputType: 'textarea',
        inputValidator: (value: string) => {
          if (!value || !value.trim()) {
            return '作废原因不能为空'
          }
          if (value.trim().length < 5) {
            return '作废原因至少需要5个字符'
          }
          if (value.trim().length > 200) {
            return '作废原因不能超过200个字符'
          }
          return true
        },
        inputErrorMessage: '请输入有效的作废原因'
      }
    )
    if (voidReason && voidReason.trim()) {
      const params: Recordable = {
        id: item.id,
        reportType: item.reportType,
        reason: voidReason.trim()
      }
      // 如果类型是检验方案/操作指导书作废，多传递一个isDelete字段
      if([PressureReportType['INSPECTIONPLAN'], PressureReportType['WORKINSTRUCTION'], PressureReportType.MAINQUESTION].includes(item.reportType)) {
        params.isDelete = true
      }
      await BoilerTaskOrderApi.cancelReport(params)

      ElMessage.success(`成功作废项目 ${item.reportName}`)
      handleGetOperationReportAuditList()
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('作废项目失败:', error)
      ElMessage.error('作废项目失败，请稍后重试')
    }
  }
}

</script>

<style lang="scss" scoped>
.loading-text {
  text-align: center;
  padding: 20px;
  color: #909399;
}
:deep(.el-descriptions__label) {
  width: 10%;
}
:deep(.el-descriptions__content) {
  width: 20%;
}
.leader-tag {
  display: inline-block;
  width: 16px;
  height: 16px;
  line-height: 14px;
  text-align: center;
  border: 1px solid #4475d6;
  font-size: 12px;
  margin-right: 4px;
  color: #4475d6;
}
.app-container { // Ensure this class is defined if not globally available
  padding: 20px; // Example padding
}

// 操作按钮对齐样式
.operation-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.custom-block.tip {
  padding: 0 6px;
  background-color: var(--block-warning-bg-color);
  border-left: 5px solid var(--el-color-primary);
  margin: 15px 0;
}

.el-row {
  margin: 1px;
}
</style>
