<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '管线集列表（分配项目）',
    navigationStyle: 'custom',
    disableScroll: true,
    'app-plus': {
      bounce: 'none',
    },
  },
}
</route>

<template>
  <view class="equipment-list-container">
    <NavBar title="管道工程列表" />

    <scroll-view
      class="list-scroll"
      scroll-y
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <wd-collapse v-model="expandedNames" @change="handleCollapseChange">
        <wd-collapse-item
          v-for="pipeSet in pipeSetList"
          :key="pipeSet.id"
          :title="pipeSet.equipName + '(' + pipeSet.productNo + ')'"
          :name="pipeSet.id"
        >
          <template #title>
            <view class="pipe-set-header" @click.stop>
              <view class="row">
                <view v-if="orderId" class="checkbox-wrapper" @click="handleSelectPipeSet(pipeSet)">
                  <view class="checkbox" :class="{ checked: selectedPipeSetMap[pipeSet.id] }">
                    <image
                      v-if="selectedPipeSetMap[pipeSet.id]"
                      class="check-icon"
                      src="/static/images/white-check.png"
                      mode="aspectFit"
                    />
                  </view>
                </view>
                <view class="cell-top-left" @click="handleSelectPipeSet(pipeSet)">
                  <text class="equip-name">{{ pipeSet.equipName }}({{ pipeSet.projectNo }})</text>
                  <text class="main-checker">主检人：{{ mainCheckerUser.nickname || '' }}</text>
                  <view
                    class="status-tag"
                    :class="
                      pipeSet?.taskStatus !== PressureCheckerMyTaskStatus.CONFIRMED
                        ? 'status-pending'
                        : 'status-done'
                    "
                  >
                    <text class="status-text">
                      {{ PressureCheckerMyTaskStatusMap[pipeSet?.taskStatus] }}
                    </text>
                  </view>
                </view>
                <view class="expand-arrow" @click.stop="toggleCollapse(pipeSet.id)">
                  <image
                    class="arrow-icon"
                    :class="{ 'arrow-expanded': expandedNames.includes(pipeSet.id) }"
                    :src="iconMap.ArrowRight"
                  />
                </view>
              </view>
            </view>
          </template>

          <view v-if="!pipeSetChildren[pipeSet.id]" class="loading-text">加载中...</view>
          <view v-else-if="pipeSetChildren[pipeSet.id].length === 0" class="empty-text-small">
            <text>暂无下级管线</text>
          </view>
          <view v-else>
            <view
              v-for="childPipe in pipeSetChildren[pipeSet.id]"
              :key="childPipe.id"
              class="child-pipe-cell"
            >
              <view
                class="child-pipe-top"
                @click="handleSelectChildPipe(childPipe, pipeSet.id, pipeSet.mainID)"
              >
                <view class="row">
                  <view v-if="orderId" class="checkbox-wrapper">
                    <view class="checkbox" :class="{ checked: selectedChildPipeMap[childPipe.id] }">
                      <image
                        v-if="selectedChildPipeMap[childPipe.id]"
                        class="check-icon"
                        src="/static/images/white-check.png"
                        mode="aspectFit"
                      />
                    </view>
                  </view>
                  <view class="cell-top-left">
                    <text class="child-pipe-name">
                      {{ childPipe.equipName || childPipe.pipeName || '' }}({{ childPipe.pipeNo }})
                    </text>
                  </view>
                </view>
              </view>

              <view
                class="child-pipe-info"
                @click="handleRouteToEquipmentDetail(childPipe, 'EQUIPMENT')"
              >
                <view class="info-box">
                  <text class="info-label">
                    设备注册代码:
                    <text class="info-value">{{ childPipe.pipeRegCode || '' }}</text>
                  </text>
                </view>
              </view>

              <view class="cell-bottom">
                <view
                  v-if="childPipe.isClaim"
                  class="record-btn blue-btn"
                  @click="handleRouteToEquipmentDetail(childPipe, 'INSPECT')"
                >
                  <text class="blue-btn-text">记录录入</text>
                </view>
              </view>
            </view>
          </view>
        </wd-collapse-item>
      </wd-collapse>

      <view v-if="loading && pipeSetList.length === 0" class="loading-text">加载中...</view>
      <view v-if="!loading && pipeSetList.length === 0" class="empty-text">
        <text>暂无数据</text>
      </view>
    </scroll-view>

    <view v-if="orderId" class="bottom-operate">
      <view class="select-all" @click="handleSelectAllPipeSet">
        <view class="checkbox" :class="{ checked: selectAllPipeSet }">
          <image
            v-if="selectAllPipeSet"
            class="check-icon"
            src="/static/images/white-check.png"
            mode="aspectFit"
          />
        </view>
        <text class="select-all-text">全选项目</text>
      </view>
      <view class="btn-group">
        <button class="operate-btn blue-btn" @click="showMoreOperate = true">更多操作</button>
        <button
          class="operate-btn blue-btn"
          :class="{ 'btn-disabled': selectedChildPipes.length > 0 }"
          :style="selectedChildPipes.length > 0 ? { opacity: 0.5 } : {}"
          @click="selectedChildPipes.length === 0 && showCheckProjectPopup()"
        >
          添加项目
        </button>
      </view>
    </view>

    <view v-if="showMoreOperate" class="more-operate-overlay" @click="showMoreOperate = false">
      <view class="more-operate-panel" :class="{ 'more-panel-show': showMoreOperate }">
        <view
          class="more-btn-item"
          :class="{ disabled: !canInform }"
          @click="canInform && createInform()"
        >
          <view class="more-btn-inner more-btn-border">
            <text class="more-btn-text" :style="{ color: canInform ? 'rgb(51,51,51)' : '#ccc' }">
              重大问题线索
            </text>
          </view>
        </view>
        <view
          class="more-btn-item"
          :class="{ disabled: !canSuspend }"
          @click="canSuspend && showSuspendPopupFunc()"
        >
          <view class="more-btn-inner more-btn-border">
            <text class="more-btn-text" :style="{ color: canSuspend ? 'rgb(51,51,51)' : '#ccc' }">
              客户拒检
            </text>
          </view>
        </view>
        <view
          class="more-btn-item"
          :class="{ disabled: !canAddInspectionplan }"
          @click="canAddInspectionplan && showAddInspectionplanPopup()"
        >
          <view class="more-btn-inner more-btn-border">
            <text
              class="more-btn-text"
              :style="{ color: canAddInspectionplan ? 'rgb(51,51,51)' : '#ccc' }"
            >
              检验方案
            </text>
          </view>
        </view>
        <view
          class="more-btn-item"
          :class="{ disabled: !canUpdateContact }"
          @click="canUpdateContact && handleUpdateContact()"
        >
          <view class="more-btn-inner more-btn-border">
            <text
              class="more-btn-text"
              :style="{ color: canUpdateContact ? 'rgb(51,51,51)' : '#ccc' }"
            >
              修改安全管理员
            </text>
          </view>
        </view>
      </view>
    </view>

    <view v-if="showSuspendPopup" class="popup-mask" @click="closeSuspendPopup">
      <view class="popup-content suspend-popup" @click.stop>
        <text class="popup-title">客户拒检</text>
        <view class="form-item">
          <text class="form-label">拒检类别</text>
          <wd-picker
            v-model="suspendReasonDict"
            :columns="refuseCategoryColumns"
            placeholder="请选择拒检类别"
          />
        </view>
        <textarea
          v-if="suspendReasonDict === '5'"
          v-model="suspendReason"
          class="suspend-textarea"
          placeholder="请输入拒绝检验原因"
        />
        <view class="popup-actions suspend-actions">
          <button class="action-btn cancel-btn" @click="closeSuspendPopup">取消</button>
          <button class="action-btn confirm-btn" @click="suspendCheck(1)">上报市局</button>
          <button class="action-btn warn-btn" @click="suspendCheck(0)">无需上报</button>
        </view>
      </view>
    </view>

    <view v-if="showInspectionplanPopup" class="popup-mask" @click="closeInspectionplanPopup">
      <view class="popup-content inspectionplan-popup" @click.stop>
        <text class="popup-title">添加检验方案</text>
        <view class="tab-row">
          <view
            :class="['tab-item', { active: inspectionPlanType === 'commPlan' }]"
            @click="inspectionPlanType = 'commPlan'"
          >
            通用
          </view>
          <view
            :class="['tab-item', { active: inspectionPlanType === 'selfPlan' }]"
            @click="inspectionPlanType = 'selfPlan'"
          >
            自编
          </view>
        </view>
        <view class="form-item">
          <text class="form-label">
            {{ inspectionPlanType === 'commPlan' ? '检验方案' : '模板封面' }}
          </text>
          <wd-picker
            custom-style="background-color: #f5f5f5;border: #d3d2d2 solid 1px;border-radius: 4px;"
            v-model="selectedTemplateId"
            :columns="templateListColumn"
            @confirm="onTemplateChange"
          />
        </view>
        <view class="form-item">
          <text class="form-label">检验方案名称</text>
          <input v-model="inspectionplanName" class="form-input" placeholder="请输入检验方案名称" />
        </view>
        <view class="popup-actions">
          <button class="action-btn cancel-btn" @click="closeInspectionplanPopup">取消</button>
          <button class="action-btn confirm-btn" @click="addInspectionplanConfirm">确定</button>
        </view>
      </view>
    </view>

    <UpdateSafetyManagerPopup
      v-if="showUpdateContactPopup"
      :safe-manager="currentSafeManager.name"
      :safe-manager-phone="currentSafeManager.phone"
      @hide="showUpdateContactPopup = false"
      @confirm="handleUpdateSafetyManagerConfirm"
    />

    <view
      v-if="showCheckProject"
      class="popup-mask"
      @click="closeCheckProjectPopup"
      @touchmove.stop.prevent
    >
      <view class="popup-content check-project-popup" @click.stop @touchmove.stop>
        <view class="popup-header">
          <text class="popup-title">添加检验项目</text>
          <text class="popup-close" @click="closeCheckProjectPopup">✕</text>
        </view>
        <PipeCheckProject
          v-if="showCheckProject"
          :propject-list="checkProjectList"
          :select-templates="selectTemplates"
          use-online="1"
          :equip-data="equipDataForPopup"
          @change="handleCheckProjectChange"
          @confirm="handleCheckProjectConfirm"
          @cancel="closeCheckProjectPopup"
        />
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { pressure2NotVerifyPageApi } from '@/api/task'
import { useUserStore } from '@/store/user'
import {
  PressureCheckerMyTaskStatus,
  PressureCheckerMyTaskStatusMap,
  PressureReportType,
  EquipmentType,
} from '@/utils/dictMap'
import { getStrDictOptions } from '@/utils/dictStoreUtil'
import iconMap from '@/utils/imagesMap'
import dayjs from 'dayjs'
import UpdateSafetyManagerPopup from '@/pages/unClaim/components/UpdateSafetyManagerPopup.vue'
import { TaskOrderFuncName, requestFunc } from '@/api/ApiRouter/taskOrder'
import {
  getPipeDetailByOrderItemId,
  getPipeTaskItemListByOrderId,
  addInspectProject,
  getInputIdByEquipId,
} from '@/api/pipe/pipeTaskOrder'
import { updateEquipPipeSafetyManager } from '@/api/pipe/pipeEquip'
import NavBar from '@/components/NavBar/NavBar.vue'
import PipeCheckProject from '@/pages/taskOnline/components/PipeCheckProject.vue'

interface PopupData {
  text: string
  isClaim: boolean
}

defineOptions({ name: 'TaskOnlinePipeEquipmentList' })

const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)

const orderId = ref('')
const orderNo = ref('')
const pipeSetList = ref<any[]>([])
const loading = ref(false)
const refreshing = ref(false)

const expandedNames = ref<string[]>([])
const pipeSetChildren = ref<Record<string, any[]>>({})
const pipeSetChildrenLoading = ref<Record<string, boolean>>({})

const selectedPipeSets = ref<any[]>([])
const selectedPipeSetMap = ref<Record<string, boolean>>({})
const selectAllPipeSet = ref(false)

const selectedChildPipes = ref<any[]>([])
const selectedChildPipeMap = ref<Record<string, boolean>>({})

const canInform = ref(false)
const canSuspend = ref(false)
const canAddInspectionplan = ref(false)
const canUpdateContact = ref(false)

const showMoreOperate = ref(false)
const showSuspendPopup = ref(false)
const suspendReason = ref('')
const suspendReasonDict = ref('')
const refuseCategoryColumns = computed(() => {
  return getStrDictOptions('refuseInspectedCategory').value.map((item: any) => ({
    label: item.label,
    value: item.value,
  }))
})

const showInspectionplanPopup = ref(false)
const inspectionPlanType = ref('commPlan')
const inspectionplanName = ref('')
const selectedTemplate = ref<any>(null)
const selectedTemplateId = ref('')
const templateList = ref<any[]>([])
const optionsResult = ref<any[]>([])
const filteredTemplateList = computed(() => {
  if (inspectionPlanType.value === 'commPlan') {
    return optionsResult.value.filter(
      (item) => item.reportType === 900 && (item.pjType === 3 || item.pjType === 5),
    )
  } else if (inspectionPlanType.value === 'selfPlan') {
    return optionsResult.value.filter((item) => item.reportType === 500 && item.pjType === 5)
  }
  return []
})
const templateListColumn = computed(() => [
  filteredTemplateList.value.map((item) => ({ label: item.tbName, value: item.id })),
])

const showUpdateContactPopup = ref(false)
const currentItem = ref<any>({})

const showCheckProject = ref(false)
const checkProjectList = ref<any[][]>([])
const selectTemplates = ref<Record<string, any[]>>({})
const currentSelectedItems = ref<any[]>([])
const equipDataForPopup = ref<any>({})
const mainCheckerUser = ref<any>({})

const currentSafeManager = computed(() => ({
  name: currentItem.value?.securityMan || '',
  phone: currentItem.value?.securityManPhone || '',
}))

onLoad((options: any) => {
  orderId.value = options?.orderId || ''
  orderNo.value = options?.orderNo || ''
})

onShow(() => {
  fetchPipeSetList()
})

const fetchPipeSetList = async () => {
  loading.value = true
  try {
    const res = await getPipeTaskItemListByOrderId({ id: orderId.value })
    pipeSetList.value = res?.data?.orderItems || []
    mainCheckerUser.value = res?.data?.manager
  } catch (error) {
    console.error('获取管道工程列表失败:', error)
  } finally {
    loading.value = false
  }
}

const onRefresh = async () => {
  refreshing.value = true
  await fetchPipeSetList()
  refreshing.value = false
}

const refreshList = async () => {
  await fetchPipeSetList()
  // 刷新已展开的管道设备的子数据
  const expanded = expandedNames.value
  if (expanded.length) {
    pipeSetChildren.value = {}
    await Promise.all(expanded.map((id) => fetchPipeSetChildren(id)))
  }
}

const handleCollapseChange = ({ value }: any) => {
  const newNames = Array.isArray(value) ? value : [value]
  const added = newNames.find((name: string) => !expandedNames.value.includes(name))
  expandedNames.value = newNames
  if (added && !pipeSetChildren.value[added]) {
    fetchPipeSetChildren(added)
  }
}

const toggleCollapse = (pipeSetId: string) => {
  const isExpanded = expandedNames.value.includes(pipeSetId)
  if (isExpanded) {
    expandedNames.value = expandedNames.value.filter((id) => id !== pipeSetId)
  } else {
    expandedNames.value = [...expandedNames.value, pipeSetId]
    if (!pipeSetChildren.value[pipeSetId]) {
      fetchPipeSetChildren(pipeSetId)
    }
  }
}

const fetchPipeSetChildren = async (pipeSetId: string) => {
  pipeSetChildrenLoading.value[pipeSetId] = true
  try {
    const pipeSet = pipeSetList.value.find((item) => item.id === pipeSetId)
    const mainID = pipeSet?.mainID || pipeSetId
    const res = await getPipeDetailByOrderItemId({ orderItemId: mainID })
    pipeSetChildren.value[pipeSetId] = res?.data || []
  } catch (error) {
    console.error('获取管道设备失败:', error)
    pipeSetChildren.value[pipeSetId] = []
  } finally {
    pipeSetChildrenLoading.value[pipeSetId] = false
  }
}

const handleSelectPipeSet = (item: any) => {
  if (!orderId.value) return
  const isSelected = !selectedPipeSetMap.value[item.id]
  selectedPipeSetMap.value[item.id] = isSelected
  if (isSelected) {
    selectedPipeSets.value.push(item)
  } else {
    selectedPipeSets.value = selectedPipeSets.value.filter((ele) => ele.id !== item.id)
  }
  updateOperateStatus()
  selectAllPipeSet.value = selectedPipeSets.value.length === pipeSetList.value.length
}

const handleSelectChildPipe = (childPipe: any, pipeSetId: string, orderItemId: string) => {
  if (!orderId.value) return
  const isSelected = !selectedChildPipeMap.value[childPipe.id]
  selectedChildPipeMap.value[childPipe.id] = isSelected
  if (isSelected) {
    selectedChildPipes.value.push({ ...childPipe, pipeSetId, orderItemId })
  } else {
    selectedChildPipes.value = selectedChildPipes.value.filter((ele) => ele.id !== childPipe.id)
  }
  updateOperateStatus()
}

const handleSelectAllPipeSet = () => {
  const newSelectAll = !selectAllPipeSet.value
  selectAllPipeSet.value = newSelectAll
  selectedPipeSets.value = []
  const newMap: Record<string, boolean> = {}
  for (const item of pipeSetList.value) {
    newMap[item.id] = newSelectAll
    if (newSelectAll) {
      selectedPipeSets.value.push(item)
    }
  }
  selectedPipeSetMap.value = newMap
  updateOperateStatus()
}

const updateOperateStatus = () => {
  const hasChildPipeSelected = selectedChildPipes.value.length > 0
  if (hasChildPipeSelected) {
    canInform.value = false
    canAddInspectionplan.value = false
    canUpdateContact.value = false
    canSuspend.value = selectedChildPipes.value.length >= 1
  } else {
    canInform.value = selectedPipeSets.value.length === 1
    canAddInspectionplan.value = selectedPipeSets.value.length >= 1
    canUpdateContact.value = selectedPipeSets.value.length === 1
    canSuspend.value = false
  }
}

const initSelect = () => {
  selectedPipeSets.value = []
  selectedPipeSetMap.value = {}
  selectAllPipeSet.value = false
  selectedChildPipes.value = []
  selectedChildPipeMap.value = {}
  updateOperateStatus()
}

const showCheckProjectPopup = async () => {
  if (selectedChildPipes.value.length) {
    return uni.showToast({ title: '选中管道设备时不可添加项目', icon: 'error' })
  }
  if (!selectedPipeSets.value.length) {
    return uni.showToast({ title: '请先选择管道工程', icon: 'error' })
  }

  try {
    uni.showLoading({ title: '加载中...' })
    const firstSelectedPipeSet = selectedPipeSets.value[0]
    if (firstSelectedPipeSet) {
      equipDataForPopup.value = {
        taskOrder: {
          id: orderId.value,
          checkType: firstSelectedPipeSet.checkType,
        },
        taskOrderItem: firstSelectedPipeSet,
        reportList: firstSelectedPipeSet.reportRespVOList || [],
      }
    }

    const projectList: any[][] = []
    for (const item of selectedPipeSets.value) {
      if (item.reportRespVOList || item.reportDOList) {
        projectList.push(item.reportRespVOList || item.reportDOList)
      }
    }
    checkProjectList.value = projectList
    uni.hideLoading()
  } catch (error) {
    uni.hideLoading()
    console.error('加载管道工程详情失败:', error)
    return uni.showToast({ title: '加载失败', icon: 'error' })
  }

  selectTemplates.value = {}
  currentSelectedItems.value = []
  showCheckProject.value = true
}

const closeCheckProjectPopup = () => {
  showCheckProject.value = false
  currentSelectedItems.value = []
}

const handleCheckProjectChange = (selectedItems: any[]) => {
  currentSelectedItems.value = selectedItems
}

const handleCheckProjectConfirm = async (itemList: any[]) => {
  const reqList = []
  selectedPipeSets.value.forEach((item: any) => {
    itemList.forEach((project: any) => {
      reqList.push({
        connectId: project.connectId,
        fee: project.fee,
        templateId: project.templateId,
        type: project.type,
        orderItemId: item.mainID,
      })
    })
  })
  closeCheckProjectPopup()
  uni.showLoading({ title: '提交中...' })
  try {
    await addInspectProject({
      itemList: reqList,
      type: 200,
      orderId: orderId.value,
    })
    initSelect()
    await fetchPipeSetList()
  } catch (error) {
    console.error('添加检验项目失败:', error)
    uni.showToast({ title: '添加项目失败', icon: 'error' })
  } finally {
    uni.hideLoading()
  }
}

const showSuspendPopupFunc = () => {
  const networkType = uni.getNetworkType?.()
  if (networkType === 'none') {
    return uni.showToast({ title: '当前网络连接不可用，请检查网络设置后重新操作', icon: 'error' })
  }
  if (!selectedChildPipes.value.length) {
    return uni.showToast({ title: '请先选择管道设备', icon: 'error' })
  }
  showMoreOperate.value = false
  suspendReasonDict.value = ''
  suspendReason.value = ''
  showSuspendPopup.value = true
}

const closeSuspendPopup = () => {
  showSuspendPopup.value = false
  suspendReasonDict.value = ''
  suspendReason.value = ''
}

const suspendCheck = async (flag: number) => {
  if (!suspendReasonDict.value) {
    return uni.showToast({ title: '请选择拒检类别', icon: 'error' })
  }
  if (suspendReasonDict.value === '5' && !suspendReason.value.trim()) {
    return uni.showToast({ title: '请输入拒绝检验原因', icon: 'error' })
  }
  uni.showLoading({ title: '加载中' })
  try {
    const reqData = {
      orderItemDetails: selectedChildPipes.value.map((item: any) => ({
        id: item.id,
        equipPipeId: item.orderItemId,
      })),
      reason: suspendReason.value,
      reasonDict: suspendReasonDict.value,
      flag,
    }
    const result = await requestFunc(
      TaskOrderFuncName.BatchSuspendEquip,
      EquipmentType.PIPE,
      reqData,
    )
    uni.hideLoading()
    if (result?.code === 0) {
      initSelect()
      refreshList()
      uni.showToast({ title: '中止检验成功', icon: 'success' })
      uni.$emit('RefreshOrder')
    } else {
      const msg = result?.msg || '中止检验失败'
      uni.showToast({ title: msg, icon: 'error' })
    }
  } catch (error) {
    uni.showToast({ title: '中止检验失败', icon: 'error' })
  } finally {
    uni.hideLoading()
    closeSuspendPopup()
  }
}

const createInform = async () => {
  const networkType = uni.getNetworkType?.()
  if (networkType === 'none') {
    return uni.showToast({ title: '无网络连接，请联网重试' })
  }
  if (!orderId.value) return

  if (selectedPipeSets.value.length !== 1) {
    return uni.showToast({ title: '只能选择一个管道工程添加重大问题线索', icon: 'error' })
  }

  const selectedPipeSet = selectedPipeSets.value[0]
  const majorIssue = selectedPipeSet.reportRespVOList?.find(
    (item: any) => item.reportType == PressureReportType.MAINQUESTION,
  )
  if (majorIssue) {
    return uni.showToast({ title: '该管道工程已添加了重大问题线索', icon: 'error' })
  }

  uni.showLoading({ title: '提交中...', mask: true })
  try {
    const orderFormResp = await requestFunc(TaskOrderFuncName.GetOrderForm, EquipmentType.PIPE, {
      orderId: orderId.value,
      businessType: 400,
      orderItemId: selectedPipeSet.mainID,
    })
    const templateId = orderFormResp?.data?.templateId || ''
    const reqData = {
      orderFormEnterReqVO: {
        businessType: 400,
        modifiedReason: '',
        orderId: orderId.value,
        orderItemId: selectedPipeSet.mainID,
      },
      orderId: orderId.value,
      orderItemId: selectedPipeSet.mainID,
      prepareId: userInfo.value?.id || '',
      prepareName: userInfo.value?.nickname || '',
      templateId: templateId,
    }
    const addMajorIssueResp = await requestFunc(
      TaskOrderFuncName.AddMajorIssues,
      EquipmentType.PIPE,
      reqData,
    )
    if (addMajorIssueResp?.code !== 0) {
      return uni.showToast({ title: addMajorIssueResp?.msg || '操作失败', icon: 'error' })
    }
    const refId = addMajorIssueResp?.data || ''
    uni.navigateTo({
      url: `/pages/editor/mainQuestionEditor?templateId=${templateId}&refId=${refId}`,
    })
  } catch (error) {
    uni.hideLoading()
    uni.showToast({ title: '操作失败', icon: 'error' })
  } finally {
    uni.hideLoading()
  }
}

const showAddInspectionplanPopup = async () => {
  if (!canAddInspectionplan.value) {
    if (selectedChildPipes.value.length) {
      return uni.showToast({ title: '选中管道设备时不可添加检验方案', icon: 'error' })
    }
    return uni.showToast({ title: '请先选择管道工程', icon: 'error' })
  }
  showMoreOperate.value = false
  showInspectionplanPopup.value = true
  inspectionPlanType.value = 'commPlan'
  inspectionplanName.value = ''
  selectedTemplate.value = null
  try {
    const result = await pressure2NotVerifyPageApi({
      type: '6',
      reportType: 600,
      status: 200,
      pageNo: 1,
      pageSize: 9999,
    })
    optionsResult.value = result?.data || []
  } catch (error) {
    console.error('获取模板列表失败:', error)
  }
}

const closeInspectionplanPopup = () => {
  showInspectionplanPopup.value = false
}

const onTemplateChange = (selected) => {
  selectedTemplate.value = selected.selectedItems.label
  selectedTemplateId.value = selected.selectedItems.value
}

const addInspectionplanConfirm = async () => {
  if (!selectedTemplate.value) {
    return uni.showToast({ title: '请选择模板封面', icon: 'error' })
  }
  if (!inspectionplanName.value.trim()) {
    return uni.showToast({ title: '请输入检验方案名称', icon: 'error' })
  }
  closeInspectionplanPopup()
  uni.showLoading({ title: '提交中...', mask: true })
  try {
    const reqData = {
      orderId: orderId.value,
      orderItemIds: selectedPipeSets.value.map((item) => item.mainID),
      prepareId: userInfo.value?.id || '',
      prepareJson: JSON.stringify({
        prepareName: userInfo.value?.nickname || '',
        prepareDate: dayjs().format('YYYY年MM月DD日'),
      }),
      prepareName: userInfo.value?.nickname || '',
      reportName: inspectionplanName.value.trim(),
      templateId: selectedTemplateId.value,
    }
    const res = await requestFunc(TaskOrderFuncName.AddMajorIssues, EquipmentType.PIPE, reqData)
    if (res?.code !== 0) {
      return uni.showToast({ title: res?.msg || '操作失败', icon: 'error' })
    }
    uni.navigateTo({
      url: `/pages/editor/inspectionPlanEditor?templateId=${selectedTemplateId.value}&refId=${res?.data || ''}`,
    })
  } catch (error) {
    uni.hideLoading()
    uni.showToast({ title: '操作失败', icon: 'error' })
  }
}

const handleUpdateContact = () => {
  const current = selectedPipeSets.value[0]
  currentItem.value = current || {}
  showMoreOperate.value = false
  showUpdateContactPopup.value = true
}

const handleUpdateSafetyManagerConfirm = async (params: { name: string; phone: string }) => {
  if (selectedPipeSets.value.length < 1) {
    return uni.showToast({ title: '请选择管道工程', icon: 'error' })
  }

  try {
    uni.showLoading({ title: '提交中...' })

    const selectedPipeSet = selectedPipeSets.value[0]
    const results = await updateEquipPipeSafetyManager({
      id: selectedPipeSet.id,
      securityMan: params.name,
      securityManPhone: params.phone,
    })
    uni.hideLoading()

    const isSuccess = results?.code === 0
    if (isSuccess) {
      uni.showToast({ title: '修改成功', icon: 'success' })
      showUpdateContactPopup.value = false
      initSelect()
      await refreshList()
    } else {
      uni.showToast({ title: '修改失败', icon: 'none' })
    }
  } catch (error) {
    uni.hideLoading()
    console.error('修改安全管理员失败:', error)
    uni.showToast({ title: '修改失败', icon: 'none' })
  }
}

const handleRouteToEquipmentDetail = async (item: any, pageType: string) => {
  uni.showLoading({ title: '加载中' })
  const equipPipeId = item.equipPipeId
  const inputIdResp = await getInputIdByEquipId({ equipId: equipPipeId })
  if (inputIdResp.code != 0 || inputIdResp.data == '') {
    uni.showToast({ title: '查找设备信息失败', icon: 'none' })
    return
  }
  uni.hideLoading()
  const inputId = inputIdResp.data
  uni.navigateTo({
    url: `/pages/equipment/detail/equipmentDetail?orderId=${orderId.value}&orderItemId=${inputId}&equipId=${equipPipeId}&pageType=${pageType}&useOnline=1&canEdit=${true}`,
  })
}
</script>

<style lang="scss" scoped>
.equipment-list-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.list-scroll {
  flex: 1;
  overflow: hidden;
}

.pipe-set-header {
  flex: 1;
}

.expand-arrow {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  margin-left: 8px;
}

.arrow-icon {
  width: 21px;
  height: 21px;
}

.arrow-icon.arrow-expanded {
  transform: rotate(90deg);
}

.row {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.checkbox-wrapper {
  margin-right: 10px;
}

.checkbox {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 18px;
  height: 18px;
  border: 1px solid rgb(187, 187, 187);
  border-radius: 3px;
}

.checkbox.checked {
  background-color: #2f8eff;
  border-color: #2f8eff;
}

.check-icon {
  width: 12px;
  height: 12px;
}

.cell-top-left {
  display: flex;
  flex: 1;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
}

.equip-name {
  flex: 1;
  font-size: 16px;
  font-weight: bold;
  color: rgb(51, 51, 51);
}

.main-checker {
  flex-basis: 160px;
  flex-shrink: 0;
  font-size: 16px;
  font-weight: bold;
  color: rgb(51, 51, 51);
}

.status-tag {
  display: flex;
  flex-basis: 80px;
  flex-direction: row;
  flex-shrink: 0;
  align-items: center;
  justify-content: center;
  padding: 5px 0;
  border-radius: 4px;
}

.status-pending {
  background-color: rgba(230, 162, 60, 0.3);
  border: 1px solid rgba(230, 162, 60, 0.5);
}

.status-done {
  background-color: rgba(103, 194, 58, 0.3);
  border: 1px solid rgba(103, 194, 58, 0.5);
}

.status-text {
  font-size: 12px;
  color: rgb(202, 135, 35);
}

.status-done .status-text {
  color: rgb(80, 175, 33);
}

.child-pipe-cell {
  padding: 10px;
  margin-bottom: 8px;
  background-color: #fff;
  border: 1px solid #f0f0f0;
  border-radius: 5px;
}

.child-pipe-top {
  padding-bottom: 8px;
  margin-bottom: 8px;
  border-bottom: 1px solid rgb(244, 244, 244);
}

.child-pipe-name {
  flex: 1;
  font-size: 14px;
  font-weight: bold;
  color: rgb(51, 51, 51);
}

.child-pipe-info {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.info-box {
  display: flex;
  flex: 1;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 8px 12px;
  background-color: rgb(244, 244, 244);
  border-radius: 5px;
}

.info-label {
  margin-top: 4px;
  font-size: 12px;
  color: rgb(108, 108, 108);
}

.info-value {
  color: rgb(51, 51, 51);
}

.cell-bottom {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-end;
}

.claim-btn,
.record-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 75px;
  height: 29px;
  padding: 0 5px;
  margin-left: 5px;
  border-radius: 3px;
}

.blue-btn {
  color: white;
  background-color: rgb(47, 142, 255);
}

.white-btn {
  background-color: #fff;
  border: 1px solid rgb(217, 217, 217);
}

.blue-btn-text {
  font-size: 12px;
  color: rgb(222, 238, 255);
}

.white-btn-text {
  font-size: 12px;
  color: rgb(59, 59, 59);
}

.loading-text {
  padding: 15px;
  font-size: 14px;
  color: #999;
  text-align: center;
}

.empty-text-small {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px 0;
  font-size: 13px;
  color: #999;
}

.empty-text {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  font-size: 14px;
  color: #999;
}

.bottom-operate {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  height: 68px;
  padding: 8px 12px;
  background-color: #fff;
  border-top: 1px solid #eee;
}

.select-all {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.select-all-text {
  margin-left: 6px;
  font-size: 14px;
  color: #333;
}

.btn-group {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.btn-group > button {
  min-width: 70px;
  height: 32px;
  padding: 8px 4px;
  margin-left: 6px;
  font-size: 14px;
  line-height: 1;
  border: none;
  border-radius: 3px;
}

.operate-btn {
  display: flex;
  align-items: center;
  justify-content: center;
}

.popup-mask {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 0, 0, 0.5);
}

.popup-content {
  width: 80%;
  max-width: 320px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
}

.tips-text {
  display: block;
  margin-bottom: 20px;
  font-size: 16px;
  color: #333;
  text-align: center;
}

.popup-actions {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100px;
  height: 36px;
  font-size: 14px;
  border: none;
  border-radius: 4px;
}

.cancel-btn {
  color: #666;
  background-color: #f5f5f5;
}

.confirm-btn {
  color: #fff;
  background-color: #2f8eff;
}

.warn-btn {
  color: #fff;
  background-color: #e6a23c;
}

.suspend-actions {
  gap: 8px;
}

.suspend-actions .action-btn {
  flex: 1;
  width: auto;
}

.more-operate-overlay {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 998;
}

.more-operate-panel {
  position: fixed;
  right: 0;
  bottom: 68px;
  left: 0;
  z-index: 999;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
  transform: translateY(100%);
}

.more-panel-show {
  transform: translateY(0);
}

.more-btn-item {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 15px 10px;
  background-color: #fff;
}

.more-btn-inner {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  padding-top: 10px;
}

.more-btn-border {
  border-top: 1px solid #f4f5f6;
}

.more-btn-item.disabled {
  opacity: 1;
}

.more-btn-text {
  font-size: 14px;
  color: #333;
}

.suspend-popup .popup-title,
.inspectionplan-popup .popup-title {
  display: block;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: 500;
  color: #333;
  text-align: center;
}

.tab-row {
  display: flex;
  margin-bottom: 12px;
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #2f8eff;
}

.tab-item {
  flex: 1;
  padding: 8px 0;
  font-size: 14px;
  color: #2f8eff;
  text-align: center;
  background-color: #fff;
}

.tab-item.active {
  color: #fff;
  background-color: #2f8eff;
}

.suspend-textarea {
  box-sizing: border-box;
  width: 100%;
  height: 80px;
  padding: 8px;
  margin-bottom: 15px;
  font-size: 14px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.form-item {
  display: flex;
  flex-direction: column;
  margin-bottom: 12px;
}

.form-label {
  margin-bottom: 6px;
  font-size: 14px;
  color: #333;
}

.form-input {
  height: 46px;
  padding: 0 0 0 15px;
  font-size: 14px;
  background-color: #f5f5f5;
  border-radius: 4px;
  border: #d3d2d2 solid 1px;
}

::deep(.wd-collapse-item) {
  margin: 12px;
  margin-bottom: 0;
  overflow: hidden;
  background-color: #fff;
  border-radius: 5px;
}

::deep(.wd-collapse-item__title) {
  padding: 12px 15px;
  font-size: 15px;
}

::deep(.wd-collapse-item__title-wrapper) {
  background-color: #fff;
}

::deep(.wd-collapse-item__content) {
  padding: 10px;
}

::deep(.wd-collapse-item__arrow) {
  display: none;
}

.check-project-popup {
  width: 85%;
  max-width: none;
  height: 80vh;
  padding: 0;
  overflow: hidden;
}

.popup-header {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.popup-close {
  font-size: 20px;
  color: #999;
}
</style>
