<template>
  <!-- 我的任务详情 -->
  <div class="task-detail-layout" :class="{ 'fullscreen-mode': isFullscreen }">
    <div class="detail-header">
      <div class="flex items-center pl-14px flex-[0_0_450px]">
        任务详情
        <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" plain @click="() => toTaskOrderDetail()">任务单</el-button>
      </div>
      <el-divider direction="vertical" class="mx-10px" />
      <div id="teleport-btn" ref="teleportBtnRef" class="teleport-btn"></div>
<!--      <el-button class="ml-10px" type="primary" size="small" plain @click="handleToggleFullscreen">-->
<!--        {{ isFullscreen ? '退出全屏' : '全屏' }}-->
<!--      </el-button>-->
      <div class="detail-header-back">
        <el-button circle type="default" plain @click="handleToggleFullscreen">
        <Icon
          :icon="isFullScreen ? 'radix-icons:exit-full-screen' : 'radix-icons:enter-full-screen'"
          color="var(--el-color-info)"
          hover-color="var(--el-color-primary)"
        />
      </el-button>
        <el-button type="default" plain @click="() => handleBack()">返回</el-button></div>
    </div>
    <div class="task-detail-container flex">
      <!-- 左侧：检验项目列表 -->
      <div class="left-panel flex-[0_0_400px]">
        <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>
          </template>

          <!-- 检验项目列表组件 -->
          <InspectionItemList
            :report-list="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"
            @set-pipe-detail="setPipeDetail"
            @sync-all-report="handleSyncReportData"
            @sort-report="handleRefresh"
            @refresh="handleRefresh"
            @correlation-report="handleCorrelationReport"
            @template-confirm="handleTemplateConfirm"
            @apply-template="handleApplyTemplate"
            @update-template="handleUpdateTemplateUrl"
            @getData="getData"
          />
        </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"
          :is-fullscreen="isFullscreen"
          @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]"
    :reportList="reportList"
    :allReportList="allReportList"
    :taskOrderItem="taskOrderItem"
    :checkUsers="checkUsers"
    @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?.nickname).join('、') || '暂无'
        }}
      </div>
    </div>

    <CheckerSelectBox :checkUsers="checkUsers" 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>

  <!-- 设置管线对话框 -->
  <el-dialog
    v-model="setPipeDetailDialogVisible"
    title="设置对应管线"
    width="40%"
    :before-close="handleCancelSetPipeDetail"
  >
    <div class="mb-4" v-if="selectedItem">
      <div class="text-sm text-gray-600 mb-2">
        项目：{{ selectedItem.reportName || '检验项目' }}
      </div>
      <el-select
        v-model="selectedPipeDetail"
        placeholder="请选择对应管线"
        clearable
        filterable
        style="width: 100%"
      >
        <el-option
          v-for="pipe in pipeDetailList"
          :key="pipe.id"
          :label="pipe.pipeNo + '-' + pipe.pipeName"
          :value="pipe.id"
        />
      </el-select>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancelSetPipeDetail">取消</el-button>
        <el-button type="primary" @click="handleConfirmSetPipeDetail"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 设备档案弹窗 -->
   <EquipPipeForm ref="EquipPipeFormRef" :selectedItem="selectedItem" :allReportList="allReportList" />

  <!-- 设备选择弹窗 -->
  <el-dialog
    v-model="equipmentSelectDialogVisible"
    title="选择设备"
    width="600px"
  >
    <div class="equipment-list">
      <div 
        v-for="equip in equipmentList" 
        :key="equip.id"
        class="equipment-item"
        @click="handleEquipmentClick(equip)"
      >
        {{ equip.projectNo }} - {{ equip.projectName }}
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="equipmentSelectDialogVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

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

defineOptions({ name: 'PipeCheckerTaskDetail' })

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

const teleportBtnRef = ref<HTMLDivElement>()

// 全屏控制
const isFullscreen = ref(true)
const handleToggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value
}

// 基础数据
const taskId = ref<string | null>(null)
const orderId = ref<string | null>(null)
const loading = ref(true)
const taskInfo = ref<PipeTaskOrderDetailVO | null>(null)
const allReportList = ref<ReportItemVO[]>([])
const reportList = ref<ReportItemVO[]>([])
const historyList = ref<any[]>([])
const checkUsers = ref<UserVO[]>([])
const taskOrderItem = ref<PipeTaskOrderOrderItemVO | 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 setPipeDetailDialogVisible = ref(false)
const pipeDetailList = ref([])
const selectedPipeDetail = ref('')
const selectedCheckers = ref<string[]>([])
const selectedCheckersInfo = ref<any[]>([])
async function getOrderHistoryVersion(id: string) {
  try {
    const response = await PipeTaskOrderApi.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 selectedNewInspectionItem = 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
}))

const handleAddItem = () => {
  selectedNewInspectionItem.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 PipeTaskOrderApi.addReportV3(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 fetchTaskDetail11(id: string) {
  loading.value = true
  try {
    //debugger;
    const response = await PipeTaskOrderApi.getTaskOrderOrderItem(id)
    taskInfo.value = response.taskOrder
    checkUsers.value = response.checkUsers
    taskOrderItem.value = response.taskOrderItem
    // 过滤报告列表 - 只显示状态 >= 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 false
      }
      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[]) => {
  selectedCheckers.value = checkerInfo
}

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

  try {

    if (selectedCheckers.value.length < 1){
      ElMessage.error('请选择检验员！');
      return;
    }

    const updateData = {
      id: selectedItem.value.id,
      userList: selectedCheckers.value.map(item => item.id)
    }

    console.log('updateData', updateData)
    await PipeTaskOrderApi.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 handleCancelSetPipeDetail = () => {
  setPipeDetailDialogVisible.value = false
  selectedPipeDetail.value = ''
}

const handleConfirmSetPipeDetail = async () => {

  if (!selectedPipeDetail.value) {
    ElMessage.warning('请选择对应管线')
    return
  }

  try {
    const params = {
      id: selectedItem.value.id,
      pipeDetailId: selectedPipeDetail.value
    }
    await PipeTaskOrderApi.setPipeDetail(params)
    ElMessage.success('成功设置报告对应管线')
    setPipeDetailDialogVisible.value = false
    await handleRefresh()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('报告设置对应管线失败:', error)
      ElMessage.error('报告设置对应管线失败，请稍后重试')
    }
  }
}

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

// 应用项目回调
const handleApplyTemplate = (defaultJson: Recordable) => {
  statusOperationPanelRef.value?.handleApplyTemplate(defaultJson)
}
// 更新模板回调
const handleUpdateTemplateUrl = (item: ReportItemVO) => {
  statusOperationPanelRef.value?.handleUpdateTemplateUrl(item)
}

const getData = (callback: (data: Recordable) => void) => {
  const data = statusOperationPanelRef.value?.getData()
  callback(data)
}

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

  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)
  }
  if (selectedCheckersInfo.value.length == 0){
    selectedCheckersInfo.value = item.checkUsers
  }
  selectedCheckers.value = [...new Set(currentCheckers)]
  // selectedCheckers.value = []
  modifyCheckerDialogVisible.value = true
}

//设置对应管线
const setPipeDetail = async (item: ReportItemVO) => {
  selectedItem.value = item
  selectedPipeDetail.value = selectedItem.value.pipeDetailId || ''
  //获取管线
  const params = {
    orderId: orderId.value
  }
  const response = await PipeTaskOrderApi.getDetailByOrderId(params)
  pipeDetailList.value = response || []
  setPipeDetailDialogVisible.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 PipeTaskOrderApi.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
  const orderIdQuery = route.query.orderId
  if (typeof idFromQuery === 'string' && idFromQuery) {
    taskId.value = idFromQuery
    if (orderIdQuery) {
      orderId.value = orderIdQuery
    }
    await fetchTaskDetail(idFromQuery)
    await getOrderHistoryVersion(idFromQuery)
    const activeDetailItemId= localStorage.getItem('activePipeDetailItemId')
    if (activeDetailItemId){
      await handleItemSelect(reportList.value.find( item=> item.id === activeDetailItemId))
      localStorage.removeItem('activePipeDetailItemId')
    }
  } else {
    taskInfo.value = null
    loading.value = false
  }
})();

// 监听设备编辑成功事件
const handleEquipmentEditSuccess = async () => {
  console.log('收到设备编辑成功事件，同步报表')
  try {
    await PipeTaskOrderApi.syncAllReportDataByOrderId({
      orderId: orderId.value
    })
    ElMessage.success('报表数据同步成功')
    // 同步成功后刷新页面数据
    await handleRefresh()
  } catch (error) {
    console.error('同步报表数据失败:', error)
    ElMessage.error('同步报表数据失败')
  }
}

// 注册事件监听
emitter.on('equipment-edit-success', handleEquipmentEditSuccess)

// 组件卸载时移除监听器，避免重复调用
onUnmounted(() => {
  emitter.off('equipment-edit-success', handleEquipmentEditSuccess)
})

watch(() => route.path, async () => {
  if (route.path === '/gdjy/my-task/pipe/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 EquipPipeFormRef = ref<InstanceType<typeof EquipPipeForm>>()
const equipmentSelectDialogVisible = ref(false)
const equipmentList = ref<any[]>([])

const handleViewEquipment = async () => {
  try {
    // 获取订单关联的所有设备
    const res = await PipeTaskOrderApi.getEquipsByOrderId(orderId.value)
    equipmentList.value = res || []
    
    if (equipmentList.value.length === 0) {
      ElMessage.warning('暂无设备信息')
      return
    }
    
    // 如果只有一个设备，直接跳转到编辑页
    if (equipmentList.value.length === 1) {
      router.push({
        name: 'PipeEquipmentForm',
        query: {
          type: 'update',
          id: equipmentList.value[0].id
        }
      })
    } else {
      // 如果有多个设备，显示选择弹窗
      equipmentSelectDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取设备列表失败:', error)
    ElMessage.error('获取设备列表失败')
  }
}

const handleEquipmentClick = (equip: any) => {
  equipmentSelectDialogVisible.value = false
  // 延时300ms后再跳转，让弹窗关闭动画完成
  setTimeout(() => {
    router.push({
      name: 'PipeEquipmentForm',
      query: {
        type: 'update',
        id: equip.id
      }
    })
  }, 300)
}

const toTaskOrderDetail = () => {
  isFullscreen.value = false
  router.push({
    name: 'PipeTaskOrderView',
    query: {
      id: orderId.value,
      type: 'checker'
    }
  })
}

const handleSyncReportData = async () => {

  try {
    const response = await PipeTaskOrderApi.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 PipeTaskOrderApi.getTaskOrderOrderItem(id)
    taskInfo.value = response.taskOrder
    checkUsers.value = response.checkUsers
    taskOrderItem.value = response.taskOrderItem || {}
    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 [200].includes(v.status)
      }
      // 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 [200].includes(v.status)
      }
      // 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 [200].includes(v.status)
      }
      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;
  transition: all 0.3s ease;

  &.fullscreen-mode {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw !important;
    height: 100vh !important;
    z-index: 500;
    background: var(--el-bg-color);
  }

  .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;
}

.equipment-list {
  max-height: 400px;
  overflow-y: auto;
}

.equipment-item {
  padding: 12px 16px;
  margin-bottom: 8px;
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    background-color: var(--el-color-primary-light-9);
    border-color: var(--el-color-primary);
    color: var(--el-color-primary);
  }
  
  &:last-child {
    margin-bottom: 0;
  }
}
</style>
