<template>
  <!-- 我的任务详情 -->
  <div class="task-detail-layout">
    <div class="detail-header">
      <div class="flex items-center pl-14px flex-[0_0_520px]">
        任务详情
        <el-checkbox class="flex-1 flex items-center justify-center" v-model="isShowOnlyMyItems" size="small" @change="handleShowOnlyMyItems">只看我</el-checkbox>
        <el-checkbox class="flex-1 flex items-center justify-center" v-model="isShowConcludeItems" size="small" @change="handleShowConcludeItemsItems">报告未办结</el-checkbox>
        <el-button class="ml-15px" type="primary" size="small" plain @click="() => handleViewEquipment()">查看设备档案</el-button>
        <el-button class="ml-15px" type="primary" size="small" v-if="showGenerateReport" plain @click="() => handleGenerateReportPdf()">
          出具报告</el-button>
        <el-button class="ml-15px" type="primary" size="small" plain @click="() => toTaskOrderDetail()">任务单</el-button>
      </div>
      <el-divider direction="vertical" class="mx-10px" />
      <div id="teleport-btn" ref="teleportBtnRef" class="teleport-btn"></div>
      <div class="detail-header-back"><el-button type="default" plain @click="() => handleBack()">返回</el-button></div>
    </div>
    <div class="task-detail-container flex">
      <!-- 左侧：检验项目列表 -->
      <div class="left-panel flex-[0_0_450px]">
        <ContentWrap title="检验项目清单" class="h-full flex flex-col" :bodyStyle="{padding: '10px', flex: 1, overflow: 'hidden'}">
          <template #header>
            <el-button @click="handleAddItem" type="primary" size="small" :disabled="taskInfo?.taskStatus === PressureTaskOrderTaskStatus['REPORT_END'] || canAddReportItem">添加检验项目</el-button>
            <el-button @click="handleAddItemPart" type="primary" size="small" v-if="taskOrderItem?.boilerType !== '2'"
                       :disabled="taskInfo?.taskStatus === PressureTaskOrderTaskStatus['REPORT_END'] || canAddReportItem">
              添加检验部件</el-button>
          </template>

          <!-- 检验项目列表组件 -->
          <InspectionItemList
            :report-list="reportList"
            :report-group-list="groupReportList(reportList)"
            :orderInfo="taskInfo"
            :equipmentIds="[taskOrderItem?.equipId]"
            :orderItemIds="[taskOrderItem?.id]"
            :selected-item="selectedItem"
            @item-select="handleItemSelect"
            :task-order-item="taskOrderItem"
            @modify-checker="handleModifyCheckerForItem"
            @void-item="handleVoidItem"
            @sort-report="handleRefresh"
            @sync-all-report="handleSyncReportData"
            @refresh="handleRefresh"
            @correlation-report="handleCorrelationReport"
            @template-confirm="handleTemplateConfirm"
          />
        </ContentWrap>
      </div>
      <div class="right-panel flex-1 overflow-hidden">
        <StatusOperationPanel
          ref="statusOperationPanelRef"
          v-model:selected-item="selectedItem"
          :task-info="taskInfo"
          :task-order-item="taskOrderItem"
          :report-list="reportList"
          :history-list="historyList"
          :taskId="taskId"
          :teleportBtnRef="teleportBtnRef"
          @refresh="handleRefresh"
          @modify-checker="handleModifyChecker"
          @template-confirm="handleTemplateConfirm"
          @item-select="handleItemSelect"
        />
      </div>
    </div>
  </div>

  <AddOrEditCheckItemForEquipment
    v-if="selectedNewInspectionItem"
    v-model="selectedNewInspectionItem"
    :orderInfo="taskInfo"
    :selectedIds="selectedReportIds"
    :equipmentIds="[taskOrderItem?.equipId]"
    :orderItemIds="[taskOrderItem?.id]"
    :reportList="reportList"
    :allReportList="allReportList"
    @refresh="() => handleRefresh()"
  />

  <AddOrEditCheckPartForEquipment
    v-if="selectedNewInspectionItemPart"
    v-model="selectedNewInspectionItemPart"
    :orderInfo="taskInfo"
    :selectedIds="selectedReportIds"
    :equipmentIds="[taskOrderItem?.equipId]"
    :orderItemIds="[taskOrderItem?.id]"
    :reportList="reportList"
    :allReportList="allReportList"
    :selectedItemPartIds="selectedItemPartIds"
    @refresh="() => handleRefresh()"
  />

  <!-- 修改检验员对话框 -->
  <el-dialog
    v-model="modifyCheckerDialogVisible"
    title="修改检验员"
    width="80%"
    :before-close="handleCancelModifyChecker"
  >
    <div class="mb-4" v-if="selectedItem">
      <div class="text-sm text-gray-600 mb-2">
        项目：{{ selectedItem.reportName || '检验项目' }}
      </div>
      <div class="text-sm text-gray-600">
        当前检验员：{{
          selectedCheckersInfo.map((item) => item.member?.nickname).join('、') || '暂无'
        }}
      </div>
    </div>

    <CheckerSelect v-model="selectedCheckers" :max="1" @change="handleCheckerChange" />

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancelModifyChecker">取消</el-button>
        <el-button type="primary" @click="handleConfirmModifyChecker"> 确认修改 </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 设备档案弹窗 -->
   <EquipBoilerForm ref="EquipBoilerFormRef" :selectedItem="selectedItem" :allReportList="allReportList" />
</template>

<script setup lang="ts">
import {onMounted, ref} from 'vue'
import { useRoute } from 'vue-router'
import {ElLoading, ElMessage, ElMessageBox} from 'element-plus'
import {
  BoilerTaskOrderApi,
  BoilerTaskOrderDetailVO, 
  ReportItemVO,
  BoilerTaskOrderOrderItemVO
} from '@/api/pressure2/boilertaskorder'
import { UserVO } from '@/api/system/user'
import { PressureCheckerMyTaskStatus, PressureReportType } from '@/utils/constants'
import CheckerSelect from '@/views/pressure2/equipboilerscheduling/components/CheckerSelect.vue'
import InspectionItemList from './components/InspectionItemList.vue'
import StatusOperationPanel from './components/StatusOperationPanel.vue'
import { useUserStore } from '@/store/modules/user'
import AddOrEditCheckItemForEquipment from '@/views/pressure2/boilertaskorder/components/AddOrEditCheckItemForEquipment.vue'
import AddOrEditCheckPartForEquipment from '@/views/pressure2/boilertaskorder/components/AddOrEditCheckPartForEquipment.vue'
import { PressureTaskOrderTaskStatus } from '@/utils/constants'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { useEmitt } from '@/hooks/web/useEmitt'
import EquipBoilerForm from '@/components/EquipBoilerForm/index.vue'
import {PipeTaskOrderApi, PipeTaskOrderDetailVO} from "@/api/pressure2/pipetaskorder";

defineOptions({ name: 'BoilerCheckerTaskDetail' })

const tagsViewStore = useTagsViewStore()
const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const { emitter } = useEmitt()

const teleportBtnRef = ref<HTMLDivElement>()

// 基础数据
const taskId = ref<string | null>(null)
const loading = ref(true)
const taskInfo = ref<BoilerTaskOrderDetailVO | null>(null)
const allReportList = ref<ReportItemVO[]>([])
const reportList = ref<ReportItemVO[]>([])
const partList = ref<ReportItemVO[]>([])
const historyList = ref<any[]>([])
const checkUsers = ref<UserVO[]>([])
const taskOrderItem = ref<BoilerTaskOrderOrderItemVO | null>(null)

// 主报告处于 报告审核审核/报告审批/报告办结,是则不能添加检验项目
const canAddReportItem = computed(()=>{
  const disabledStatus = [PressureCheckerMyTaskStatus.REPORT_AUDIT, PressureCheckerMyTaskStatus.REPORT_APPROVE, PressureCheckerMyTaskStatus.REPORT_END]
  const mainReport = unref(reportList).find(x => x.reportType === PressureReportType['MAIN'])
  // console.log(mainReport, 'mainReport')
  return mainReport && disabledStatus.includes(mainReport.taskStatus)
})

// 选择状态
const selectedItem = ref<ReportItemVO | null>(null)

// 对话框状态
const addItemDialogVisible = ref(false)
const modifyCheckerDialogVisible = ref(false)
const selectedCheckers = ref<string[]>([])
const selectedCheckersInfo = ref<any[]>([])
async function getOrderHistoryVersion(id: string) {
  try {
    const response = await BoilerTaskOrderApi.getSafetyCheckRecordVersionPage({
      // id: id,
      pageNo: 1,
      pageSize: 100,
      businessType: 0,
      orderItemReportId: selectedItem.value?.id
    })
    //console.log('response', response)
    historyList.value = response.list || []
    //console.log('historyList.value', historyList.value)
  } catch (error) {
    console.error('获取历史版本失败:', error)
    ElMessage.error('获取历史版本失败')
  }
}

// 添加检验项目弹窗表单字段
const addInspectionItemForm = ref({
  templateId: [],
  checker: {}
})

const groupReportList = () =>{
  const list = {};
  partList.value.forEach(item => {
    list[item.partType] = reportList.value.filter(report => report.itemPartId === item.partType)
  });
  return list;
}

const selectedNewInspectionItem = ref(false)
const selectedNewInspectionItemPart = ref(false)
const handleRemoveTag = (value) => {
  addInspectionItemForm.value.templateId = addInspectionItemForm.value.templateId.filter((x: any) => x?.name !== value)
}
const handleClearSelectedInspectionItem = () => {
  addInspectionItemForm.value.templateId = []
}

// 检验员列表弹窗
const checkerSelectVisible = ref(false)
const currentSelectedCheckerIds = ref([])
const confirmCheckerSelect = () => {
  checkerSelectVisible.value = false
}

const handleSelectedNewChecker = () => {
  checkerSelectVisible.value = true
}

const handleInspectionItemCheckerChange = (checkerInfo) => {
  addInspectionItemForm.value.checker = checkerInfo?.[0]?.member
}


// 添加检验项目
const selectedReportIds = computed(() => reportList.value.map(x => {
  return x.reportType === 600 ? x.id : x.templateId || x.id
}))
// 锅炉部件ID
const selectedItemPartIds = computed(() => partList.value.map(x => {
  return x.partType
}))
const handleAddItem = () => {
  selectedNewInspectionItem.value = true
  addInspectionItemForm.value.checker = userStore.getUser
}

const handleAddItemPart = () => {
  selectedNewInspectionItemPart.value = true
  addInspectionItemForm.value.checker = userStore.getUser
}

const selectedInspectionItem = computed(() => {
  const selectedList = addInspectionItemForm.value.templateId.length > 0 ? addInspectionItemForm.value.templateId : []
  return selectedList.map((item:any ) => item?.name || item?.reportName)
})

const handleConfirmAddItems = async (selectedItems) => {
  //console.log('selectedItems', selectedItems)
  addInspectionItemForm.value.templateId = selectedItems
  // await handleRefresh()
}

// 确认添加项目
const handleConfirmToAddItem = async () => {
  try {
    const params = {
      orderItemId: taskOrderItem.value?.id ,
      templateIds: addInspectionItemForm.value.templateId.map((x: any) => x?.id),
      checkId: addInspectionItemForm.value.checker?.id
    }
    const result = await BoilerTaskOrderApi.addReportV2(params)
    if(result) {
      ElMessage.success(`成功添加 ${addInspectionItemForm.value.templateId.length} 个检验项目`)
      handleCloseNewInspectionItem()
      await handleRefresh()
    }
  } catch (error) {
    ElMessage.error('添加检验项目失败')
  }
}
// 关闭添加项目弹窗
const handleCloseNewInspectionItem = () => {
  selectedNewInspectionItem.value = false
  addInspectionItemForm.value = {
    templateId: [],
    checker: {}
  }
}

// 获取任务详情数据
async function fetchTaskDetail1(id: string) {
  loading.value = true
  try {
    //debugger;
    const response = await BoilerTaskOrderApi.getTaskOrderOrderItem(id)
    taskInfo.value = response.taskOrder
    checkUsers.value = response.checkUsers
    taskOrderItem.value = response.taskOrderItem
    partList.value = response.partList
    // 过滤报告列表 - 只显示状态 >= CONFIRMED 的项目 已认领 400
    const filteredReportList = response.reportList.filter(
      (item) => item.taskStatus >= PressureCheckerMyTaskStatus.CONFIRMED
    ).filter(v=> {
      // 如果是检验方案和指导书
      if([600, 700].includes(v.reportType as number)){
        return [200].includes(v.status)
      }
      return true
    })
    allReportList.value = response.reportList.filter(v=> {
      // 如果是检验方案和指导书
      if([600, 700].includes(v.reportType as number)){
        return [200, 400].includes(v.status)
      }
      return true
    })
    reportList.value = filteredReportList

    // 智能选择：保持当前选中项目或选择第一个项目
    if (reportList.value.length > 0) {
      let targetItem: ReportItemVO | undefined = undefined

      // 如果当前有选中项目，尝试在新列表中找到相同的项目
      if (selectedItem.value) {
        targetItem = reportList.value.find((item) => item.id === selectedItem.value?.id)
      }

      // 如果当前选中项目不存在于新列表中，或者没有选中项目，选择第一个项目
      if (!targetItem) {
        targetItem = reportList.value[0]
      }

      selectedItem.value = targetItem
    }
    //console.log('reportList.value', reportList.value)
  } catch (error) {
    console.error('获取任务详情失败:', error)
    ElMessage.error('获取任务详情失败')
    taskInfo.value = null
    reportList.value = []
  } finally {
    loading.value = false
  }
}

// 项目选择事件处理
const handleItemSelect = async (item: ReportItemVO) => {
  selectedItem.value = item
  await getOrderHistoryVersion(taskId.value)
}

// 刷新数据
const handleRefresh = async () => {
  if (taskId.value) {
    await fetchTaskDetail(taskId.value)
    await getOrderHistoryVersion(taskId.value)
  }
}

// 修改检验员
const handleModifyChecker = (item?: ReportItemVO) => {
  const targetItem = item || selectedItem.value
  if (!targetItem) {
    ElMessage.warning('请先选择要修改检验员的项目')
    return
  }

  // 如果传入了item参数，更新选中项目
  if (item) {
    selectedItem.value = item
  }

  const currentCheckers: string[] = []
  if (targetItem.checkUsers && targetItem.checkUsers.length > 0) {
    const checkerIds = targetItem.checkUsers.map((user) => String(user.id))
    currentCheckers.push(...checkerIds)
  }

  //selectedCheckers.value = [...new Set(currentCheckers)]
  selectedCheckers.value = []
  modifyCheckerDialogVisible.value = true
}

const handleCheckerChange = (checkerInfo: any[]) => {
  selectedCheckersInfo.value = checkerInfo
}

const handleConfirmModifyChecker = async () => {
  if (!selectedItem.value) {
    ElMessage.warning('请选择项目')
    return
  }

  try {
    // 按团队分组处理检验员信息
    const groupedByTeam: Record<string, { leaderId: string | null; userIds: string[] }> = {}
    selectedCheckersInfo.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 updateData = {
      id: selectedItem.value.id,
      teamList: teamList
    }

    await BoilerTaskOrderApi.updateReportUsers(updateData)

    ElMessage.success('成功修改检验员')
    modifyCheckerDialogVisible.value = false
    await handleRefresh()
  } catch (error: any) {
    console.error('修改检验员失败:', error)
    ElMessage.error('修改检验员失败，请稍后重试')
  }
}

const handleCancelModifyChecker = () => {
  modifyCheckerDialogVisible.value = false
  selectedCheckers.value = []
  selectedCheckersInfo.value = []
}

const statusOperationPanelRef = ref<InstanceType<typeof StatusOperationPanel>>()
const handleCorrelationReport = ()=>{
  //console.log('selectedItem.value', selectedItem.value)
  statusOperationPanelRef.value?.handleShowAssociationOperationManual()
}

// 模板确认（从StatusOperationPanel传递上来）
const handleTemplateConfirm = (templateUrl?: string) => {
  handleRefresh()
}
const handleBack = () => {
  if(route.query?.type === 'BoilerMyTask') {
    emitter.emit('refresh-my-task-boiler')
  } else if(route.query?.type === 'BoilerReportPreparationList') {
    emitter.emit('refresh-report-preparation-list-boiler')
  } else if(route.query?.type === 'reportAudit') {
    emitter.emit('refresh-report-reportAudit-boiler')
  } else if(route.query?.type === 'reportRatify') {
    emitter.emit('refresh-report-reportRatify-boiler')
  }

  tagsViewStore.closeSelectedTag(route)
    router.push({
      name: route?.query?.type,
    })
}
// 修改检验员（单个项目）
const handleModifyCheckerForItem = (item: ReportItemVO) => {
  selectedItem.value = item

  const currentCheckers: string[] = []
  if (item.checkUsers && item.checkUsers.length > 0) {
    const checkerIds = item.checkUsers.map((user) => String(user.id))
    currentCheckers.push(...checkerIds)
  }

  //selectedCheckers.value = [...new Set(currentCheckers)]
  selectedCheckers.value = []
  modifyCheckerDialogVisible.value = true
}

// 作废单个项目
const handleVoidItem = async (item: ReportItemVO) => {
  // 校验操作指导书是否关联了独走报告，如果有则进行二次确认
  if(item.reportType === PressureReportType.WORKINSTRUCTION){
    // 校验操作指导书是否关联了独走报告
    const hasWorkInstruction = reportList.value.some((reportItem) => reportItem.instructionId === item.id)
    if(hasWorkInstruction){
      const confirm = await ElMessageBox.confirm(
        `操作指导书 ${item.reportName} 已被检验项目关联，作废后将清除关联关系，是否确认？`,
        '确认作废',
        {
          confirmButtonText: '确认作废',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      if(confirm !== 'confirm') return
    }
  }
  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()) {
      await BoilerTaskOrderApi.cancelReport({
        id: item.id,
        reason: voidReason.trim()
      })

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

// 组件挂载时获取数据
(async () => {
  const idFromQuery = route.query.id
  if (typeof idFromQuery === 'string' && idFromQuery) {
    taskId.value = idFromQuery
    await fetchTaskDetail(idFromQuery)
    await getOrderHistoryVersion(idFromQuery)
    const activeDetailItemId= localStorage.getItem('activeBoilerDetailItemId')
      if (activeDetailItemId){
        await handleItemSelect(reportList.value.find( item=> item.id === activeDetailItemId))
        localStorage.removeItem('activeBoilerDetailItemId')
      }
  } else {
    taskInfo.value = null
    loading.value = false
  }
})();

const showGenerateReport = computed(() => {

  let flag = true;
  const mainReports = reportList.value.filter((item) => item.reportType === PressureReportType.MAIN)
  if (mainReports.length < 1) {
    flag = false
  }else{
    mainReports.forEach((item) => {
      console.log('mainReports', item.taskStatus<PressureCheckerMyTaskStatus.REPORT_INPUT)
      if(item.taskStatus < PressureCheckerMyTaskStatus.REPORT_INPUT){
        flag = false;
      }
    })
  }

  return flag;

})

const handleGenerateReportPdf = async () => {

  ElMessageBox.confirm(`确定要出具报告吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then( async () => {
    const loadingInstance = ElLoading.service({
      fullscreen: true,
      text: '出具中...'
    })
    try {
      loading.value = true
      // 获取PDF字节流
      const response = await BoilerTaskOrderApi.generateReportPdf({
        orderItemId: taskId.value
      }, { responseType: 'blob' }) // 确保以blob格式接收响应

      // 创建Blob对象
      const blob = new Blob([response], { type: 'application/pdf' })
      console.log(taskOrderItem.value)
      // 创建下载链接
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `检验报告_${taskOrderItem.value?.reportNo}.pdf` // 设置下载文件名

      // 触发下载
      document.body.appendChild(link)
      link.click()

      // 清理
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)

      ElMessage.success('报告下载成功')

      loading.value = false
    } catch (error) {
      console.error('下载PDF失败:', error)
      ElMessage.error('报告下载失败')
      loading.value = false
    } finally {
      // 关闭 Loading
      loadingInstance.close()
    }
  })
}

watch(() => route.path, async () => {
  if (route.path === '/gljy/my-task/boiler/detail') {
    const idFromQuery = route.query.id
    if (typeof idFromQuery === 'string' && idFromQuery) {
      taskId.value = idFromQuery
      await fetchTaskDetail(idFromQuery)
      await getOrderHistoryVersion(idFromQuery)
    } else {
      taskInfo.value = null
      loading.value = false
    }
  }
})

// 设备档案弹窗
const EquipBoilerFormRef = ref<InstanceType<typeof EquipBoilerForm>>()
const handleViewEquipment = () => {
  EquipBoilerFormRef.value.open(taskOrderItem.value?.equipId)
}

const toTaskOrderDetail = () => {
  router.push({
    name: 'BoilerTaskOrderView',
    query: {
      id: taskOrderItem.value?.orderId,
      type: 'checker'
    }
  })
}

const handleSyncReportData = async () => {

  try {
    const response = await BoilerTaskOrderApi.syncAllReportData({
      refId: selectedItem.value.id,
    })
    if (response){
      ElMessage.success('同步数据成功')
      handleRefresh()
    }else{
      ElMessage.error('同步数据失败，请稍后重试')
    }

  } catch (error: any) {
    console.error('同步数据失败:', error)
    ElMessage.error('同步数据失败，请稍后重试')
  }

}

//新加功能
const {id: userId = ''} = userStore.getUser || {}

const isMainChecker = () => {
  const {mainCheckerUser} = taskOrderItem.value
  const {id: mainCheckerUserId = ''} = mainCheckerUser || {}
  return mainCheckerUserId === userId
}
const isShowOnlyMyItems = ref(false)
const isShowConcludeItems = ref(false)

const handleShowOnlyMyItems = (value) => {
  isShowOnlyMyItems.value = value
  getReportList()
}
const handleShowConcludeItemsItems = (value) => {
  isShowConcludeItems.value = value
  getReportList()
}
const getReportList = (activeReportId = '')=>{
  // 当前登录人是主检人，显示所有报告，如果不是则需要根据检验员过滤对应的报告类型
  if(!isShowOnlyMyItems.value){
    reportList.value = isShowConcludeItems.value ?  filteredReportList.value.map( item => item )?.filter(
      (item) => item.taskStatus != PressureCheckerMyTaskStatus.REPORT_END) : filteredReportList.value.map( item => item )
  } else {
    const documentTypes = [
      PressureReportType.WORKINSTRUCTION,
      PressureReportType.INSPECTIONPLAN,
      PressureReportType.MAINQUESTION
    ]
    reportList.value = filteredReportList.value.filter(v=> {
      if(documentTypes.includes(v.reportType as number)){
        return true
      }
      return v.checkUsers ? v.checkUsers?.some(member=> member?.id === userId) : false
    })
    if (isShowConcludeItems.value) {
      reportList.value = reportList.value?.filter(item => item.taskStatus != PressureCheckerMyTaskStatus.REPORT_END)
    }
  }
  // 智能选择：保持当前选中项目或选择第一个项目
  if (reportList.value.length > 0) {
    let targetItem: ReportItemVO | undefined = undefined

    // 如果当前有选中项目，尝试在新列表中找到相同的项目
    if (selectedItem.value) {
      targetItem = reportList.value.find((item) => item.id === selectedItem.value?.id)
    }

    if(activeReportId) {
      targetItem = reportList.value.find((item) => item.id === activeReportId)
    }
    // 如果当前选中项目不存在于新列表中，或者没有选中项目，选择第一个项目
    if (!targetItem) {
      targetItem = reportList.value[0]
    }

    selectedItem.value = targetItem as ReportItemVO
  }

}
const filteredReportList = ref<ReportItemVO[]>([])
const filteredConcludeReportList = ref<ReportItemVO[]>([])
// 获取任务详情数据
async function fetchTaskDetail(id: string, activeReportId = '') {
  loading.value = true
  try {
    const response = await BoilerTaskOrderApi.getTaskOrderOrderItem(id)
    taskInfo.value = response.taskOrder
    checkUsers.value = response.checkUsers
    taskOrderItem.value = response.taskOrderItem || {}
    partList.value = response.partList
    const showAllReport = route.query?.showAllReport   //如果是所有报告，就不根据检验员过滤

    //暂不需要默认只看我的
    //if(!showAllReport) {isShowOnlyMyItems.value =  !isMainChecker()}
    isShowConcludeItems.value = false
    // 过滤报告列表 - 只显示状态 >= CONFIRMED 的项目 已认领 400
    filteredReportList.value = response.reportList.filter(
      (item) => item.taskStatus >= PressureCheckerMyTaskStatus.CONFIRMED
    ).filter(v=> {
      // 如果是检验方案和指导书
      if([600].includes(v.reportType as number)){
        return [200].includes(v.status)
      } else if( [500].includes(v.reportType as number)){
        return false
      }
      // if([700].includes(v.reportType as number)){
      //   return [200, 400].includes(v.status)
      // }
      return true
    })//.reverse()
    filteredConcludeReportList.value = response.reportList.filter(
      (item) => item.taskStatus >= PressureCheckerMyTaskStatus.REPORT_END
    ).filter(v=> {
      // 如果是检验方案和指导书
      if([600].includes(v.reportType as number)){
        return [200].includes(v.status)
      } else if( [500].includes(v.reportType as number)){
        return false
      }
      // if([700].includes(v.reportType as number)){
      //   return [200, 400].includes(v.status)
      // }
      return true
    })//.reverse()
    allReportList.value = response.reportList.filter(v=> {
      // 如果是检验方案和指导书
      if([600, 700].includes(v.reportType as number)){
        return [200, 400].includes(v.status)
      } else if([500].includes(v.reportType as number)){
        return false
      }
      return true
    })//.reverse()
    // 当前登录人是主检人，显示所有报告，如果不是则需要根据检验员过滤对应的报告类型
    getReportList(activeReportId)

  } catch (error) {
    console.error('获取任务详情失败:', error)
    ElMessage.error('获取任务详情失败')
    taskInfo.value = {} as PipeTaskOrderDetailVO
    reportList.value = []
  } finally {
    loading.value = false
  }
}

</script>

<style lang="scss" scoped>
.task-detail-layout {
  width: 100%;
  height: calc(
    97vh - var(--top-tool-height) - var(--tags-view-height) - var(--app-footer-height)
  ) !important;
  overflow: hidden;
  border: 1px solid var(--el-border-color);
  position: relative;

  .task-detail-container {
    align-items: stretch;
    height: calc(100% - 50px);
  }

  .detail-header {
    height: 42px;
    padding: 8px 14px;
    border-bottom: 1px solid var(--el-border-color);
    display: flex;
    justify-content: flex-start;
    align-items: center;
    &-back {
      flex: 1;
      display: flex;
      justify-content: flex-end;
    }
  }

  .left-panel {
    height: 100%;
    border: 1px solid var(--el-border-color);
    border-width: 0 1px 0 0;

    .v-content-wrap {
      border: 0;
    }

    :deep(.el-card__header) {
      .items-center {
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        gap: 10px;
      }

      .font-700 {
        font-weight: normal;
      }

      .pl-20px {
        flex-grow: unset;
        padding-left: 0;
      }
    }
  }

  .right-panel {
    height: 100%;
    padding: 10px 10px 0;
    box-sizing: border-box;
  }
}
.checker-box {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 12px;
}
</style>
