<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"
    >
      <view v-for="item in equipmentList" :key="item.id" class="equipment-cell">
        <view class="cell-top" @click="handleSelectEquipment(item)">
          <view class="row">
            <view v-if="orderId" class="checkbox-wrapper">
              <view class="checkbox" :class="{ checked: selectedMap[item.id] }">
                <image
                  v-if="selectedMap[item.id]"
                  class="check-icon"
                  src="/static/images/white-check.png"
                  mode="aspectFit"
                />
              </view>
            </view>
            <view class="cell-top-left">
              <text class="equip-name">{{ item.equipName }}({{ item.productNo }})</text>
              <text class="main-checker">主检人：{{ item?.mainCheckerUser?.nickname || '' }}</text>
              <view
                class="status-tag"
                :class="
                  item?.taskStatus !== PressureCheckerMyTaskStatus.CONFIRMED
                    ? 'status-pending'
                    : 'status-done'
                "
              >
                <text class="status-text">
                  {{ PressureCheckerMyTaskStatusMap[item?.taskStatus] }}
                </text>
              </view>
            </view>
          </view>
        </view>

        <view class="cell-center" @click="handleRouteToEquipmentDetail(item, 'EQUIPMENT')">
          <view class="info-box">
            <text class="info-label">
              设备注册代码:
              <text class="info-value">{{ item.equipCode }}</text>
            </text>
            <text class="info-label">
              费用：
              <text class="info-value">{{ handleCalcTotalFee(item?.reportDOList) }}</text>
            </text>
          </view>
        </view>

        <view class="cell-bottom">
          <view
            v-if="!item.isClaim && item.taskStatus === PressureCheckerMyTaskStatus.RECORD_INPUT"
            class="claim-btn"
            :class="item.isClaim ? 'white-btn' : 'blue-btn'"
            @click="fetchClaimEquipments(item.id + '', item.isClaim)"
          >
            <text :class="item.isClaim ? 'white-btn-text' : 'blue-btn-text'">
              {{ item.isClaim ? '取消认领' : '认领' }}
            </text>
          </view>
          <view
            v-if="item.isClaim"
            class="record-btn blue-btn"
            @click="handleRouteToEquipmentDetail(item, 'INSPECT')"
          >
            <text class="blue-btn-text">记录录入</text>
          </view>
        </view>
      </view>

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

    <view v-if="orderId" class="bottom-operate">
      <view class="select-all" @click="handleSelectAll">
        <view class="checkbox" :class="{ checked: selectAll }">
          <image
            v-if="selectAll"
            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 white-btn"
          @click="showBatchClaimPopup({ text: '是否取消认领已选择的设备？', isClaim: true })"
        >
          取消认领
        </button> -->
        <button
          class="operate-btn white-btn"
          @click="showBatchClaimPopup({ text: '是否认领已选择的设备？', isClaim: false })"
        >
          批量认领
        </button>
        <button class="operate-btn blue-btn" @click="showCheckProjectPopup">添加项目</button>
      </view>
    </view>

    <view v-if="showTipsPopup" class="popup-mask" @click="closeTipsPopup">
      <view class="popup-content tips-popup" @click.stop>
        <text class="tips-text">{{ tipsPopupData.text }}</text>
        <view class="popup-actions">
          <button class="action-btn cancel-btn" @click="closeTipsPopup">取消</button>
          <button class="action-btn confirm-btn" @click="handleBatchClaim">确定</button>
        </view>
      </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 && showAddSpacePopup()"
        >
          <view class="more-btn-inner">
            <text class="more-btn-text" :style="{ color: canInform ? 'rgb(51,51,51)' : '#ccc' }">
              添加有限空间记录
            </text>
          </view>
        </view>
        <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: !canAddInspectionplan }"
          @click="canAddInspectionplan && handleUpdateContact()"
        >
          <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>
    </view>

    <view v-if="showSuspendPopup" class="popup-mask" @click="closeSuspendPopup">
      <view class="popup-content suspend-popup" @click.stop>
        <text class="popup-title">客户拒检</text>
        <textarea
          v-model="suspendReason"
          class="suspend-textarea"
          placeholder="请输入中止检验原因"
        />
        <view class="popup-actions">
          <button class="action-btn cancel-btn" @click="closeSuspendPopup">取消</button>
          <button class="action-btn confirm-btn" @click="suspendCheck">确定</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="form-item">
          <text class="form-label">模板封面</text>
          <wd-picker
            v-model="selectedTemplateId"
            :columns="templateListColumn"
            @change="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>

    <view v-if="showUpdateContactPopup" class="popup-mask" @click="showUpdateContactPopup = false">
      <view class="popup-content" @click.stop>
        <UpdateContactPopup
          :ids="selectedEquipIds"
          :safe-manager="currentItem?.safeManager || ''"
          :safe-manager-phone="currentItem?.safeManagerPhone || ''"
          :safe-manager-id-number="currentItem?.safeManagerIdNumber || ''"
          :operator-id-number="currentItem?.operatorIdNumber || ''"
          @hide="showUpdateContactPopup = false"
          @refresh="refreshList"
        />
      </view>
    </view>

    <view v-if="showSpaceTemplatePopup" class="popup-mask" @click="showSpaceTemplatePopup = false">
      <view class="popup-content" @click.stop>
        <text class="popup-title">选择模板</text>
        <scroll-view scroll-y class="template-scroll">
          <view
            v-for="tpl in spaceTemplateList"
            :key="tpl.id"
            class="template-item"
            :class="{ active: selectedSpaceTemplateId === tpl.id }"
            @click="selectedSpaceTemplateId = tpl.id"
          >
            <text>{{ tpl.name }}</text>
          </view>
        </scroll-view>
        <view class="popup-actions">
          <button class="action-btn cancel-btn" @click="showSpaceTemplatePopup = false">
            取消
          </button>
          <button class="action-btn confirm-btn" @click="confirmSpaceTemplate">确定</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import {
  getTaskEquipmentList,
  cancelClaim,
  confirmTaskClaim,
  batchClaim,
  orderItemMajorCheck,
  getEquipmentsTemplateJSONData,
  taskOrderItemSuspendApi,
  notVerifyPageApi,
  addMajorIssuesApi,
} from '@/api/task'
import { useUserStore } from '@/store/user'
import { useConfigStore } from '@/store/config'
import {
  PressureCheckerMyTaskStatus,
  PressureCheckerMyTaskStatusMap,
  EquipmentType,
} from '@/utils/dictMap'
// import { createBusinessConfig } from '@/pages/webview/common/config/businessEditorConfig'
import { setSpreadsheetEditParams } from '@/common/global'
import { formatDate } from '@/utils/index'
import dayjs from 'dayjs'
import UpdateContactPopup from '@/pages/unClaim/components/UpdateContactPopup.vue'
import * as signApis from '@/api/sign'
import { TaskOrderFuncName, requestFunc } from '@/api/ApiRouter/taskOrder'
import NavBar from '@/components/NavBar/NavBar.vue'

interface PopupData {
  text: string
  isClaim: boolean
}

defineOptions({ name: 'TaskOnlineEquipmentList' })

const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)
const equipType = useConfigStore().getEquipType()

const orderId = ref('')
const orderNo = ref('')
const equipmentList = ref<any[]>([])
const loading = ref(false)
const refreshing = ref(false)
const selectAll = ref(false)
const selectedEquipments = ref<any[]>([])
const selectedMap = ref<Record<string, boolean>>({})

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

const showTipsPopup = ref(false)
const tipsPopupData = ref<PopupData>({ text: '', isClaim: false })

const showMoreOperate = ref(false)
const showSuspendPopup = ref(false)
const suspendReason = ref('')

const showInspectionplanPopup = ref(false)
const inspectionplanName = ref('')
const selectedTemplate = ref<any>(null)
const selectedTemplateId = ref('')
const templateList = ref<any[]>([])
const templateListColumn = computed(() => [
  templateList.value.map((item) => ({ label: item.name, value: item.id })),
])

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

const showSpaceTemplatePopup = ref(false)
const spaceTemplateList = ref<any[]>([])
const selectedSpaceTemplateId = ref('')

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

onShow(() => {
  fetchCheckerOnlineEquipmentList()
})

const selectedEquipIds = computed(() => selectedEquipments.value.map((item) => item.equipId))

const fetchCheckerOnlineEquipmentList = async () => {
  loading.value = true
  const apiParams: any = {
    orderId: orderId.value,
    pageSize: 999,
    pageNo: 1,
    taskStatusList: [400, 500, 510],
  }
  try {
    const equipmentListData = await requestFunc(
      TaskOrderFuncName.TaskEquipList,
      equipType,
      apiParams,
    )
    equipmentList.value = equipmentListData?.data?.list || []
  } catch (error) {
    console.error('获取设备列表失败:', error)
  } finally {
    loading.value = false
  }
}

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

const refreshList = () => {
  fetchCheckerOnlineEquipmentList()
}

const handleSelectEquipment = (item: any) => {
  if (!orderId.value) return
  const isSelected = !selectedMap.value[item.id]
  selectedMap.value[item.id] = isSelected
  if (isSelected) {
    selectedEquipments.value.push(item)
  } else {
    selectedEquipments.value = selectedEquipments.value.filter((ele) => ele.id !== item.id)
  }
  updateOperateStatus()
  selectAll.value = selectedEquipments.value.length === equipmentList.value.length
}

const handleSelectAll = () => {
  const newSelectAll = !selectAll.value
  selectAll.value = newSelectAll
  selectedEquipments.value = []
  const newMap: Record<string, boolean> = {}
  for (const item of equipmentList.value) {
    newMap[item.id] = newSelectAll
    if (newSelectAll) {
      selectedEquipments.value.push(item)
    }
  }
  selectedMap.value = newMap
  updateOperateStatus()
}

const updateOperateStatus = () => {
  canInform.value = selectedEquipments.value.length === 1
  canAddInspectionplan.value = selectedEquipments.value.length > 0
  const hasUnClaim =
    selectedEquipments.value.length > 0
      ? selectedEquipments.value.some((equipments) => !equipments.isClaim)
      : true
  canSuspend.value = !hasUnClaim
}

const initSelect = () => {
  selectedEquipments.value = []
  selectedMap.value = {}
  selectAll.value = false
  updateOperateStatus()
}

const showBatchClaimPopup = (popupData: PopupData) => {
  const networkType = uni.getNetworkTypeSync?.()
  if (networkType === 'none') {
    return uni.showToast({ title: '暂无网络无法认领，请联网后认领设备', icon: 'error' })
  }
  if (!selectedEquipments.value.length) {
    return uni.showToast({
      title: `请选择要批量${popupData.isClaim ? '取消认领' : '认领'}的设备`,
      icon: 'error',
    })
  }
  tipsPopupData.value = popupData
  showTipsPopup.value = true
}

const closeTipsPopup = () => {
  showTipsPopup.value = false
}

const handleBatchClaim = async () => {
  closeTipsPopup()
  const ids = selectedEquipments.value.map((item: any) => item.id)
  const params: { ids: string[]; isCancel?: true } = { ids }
  if (tipsPopupData.value.isClaim) {
    params.isCancel = true
  }
  try {
    const result = await batchClaim(params)
    updateClaim(result, ids, !tipsPopupData.value.isClaim)
  } catch (error) {
    uni.showToast({ title: '操作失败', icon: 'error' })
  }
}

const fetchClaimEquipments = async (equipmentId: string, isClaim: boolean) => {
  const networkType = uni.getNetworkTypeSync?.()
  if (networkType === 'none') {
    return uni.showToast({ title: '暂无网络无法认领，请联网后认领设备', icon: 'error' })
  }
  const currentUserInfo = userInfo.value
  if (!currentUserInfo) {
    return uni.redirectTo({ url: '/pages/login/login' })
  }
  try {
    let result: any
    if (isClaim) {
      result = await requestFunc(TaskOrderFuncName.EquipmentConfirmClaim, equipType, { id: equipmentId })
    } else {
      result = await requestFunc(TaskOrderFuncName.EquipmentCancelClaim, equipType, { id: equipmentId })
    }
    updateClaim(result, [equipmentId], !isClaim)
  } catch (error) {
    uni.showToast({ title: '操作失败', icon: 'error' })
  }
}

const updateClaim = async (result: any, equipmentIds: string[], isClaim: boolean) => {
  if (result?.code === 0 && result?.data === true) {
    uni.showToast({ title: `${isClaim ? '认领' : '取消认领'}成功` })
    initSelect()
    await fetchCheckerOnlineEquipmentList()
  } else {
    const msg = result?.msg || `${isClaim ? '认领' : '取消认领'}失败`
    uni.showToast({ title: msg, icon: 'error' })
  }
}

const showCheckProjectPopup = () => {
  if (!selectedEquipments.value.length) {
    return uni.showToast({ title: '请先选择设备', icon: 'error' })
  }
  const ids = selectedEquipments.value.map((item: any) => item.id)
  uni.navigateTo({
    url: `/pages/equipment/detail/components/checkProjectPopup/addCheckProjectPopup?selectedEquipmentIds=${ids.join(',')}&useOnline=1`,
  })
}

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

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

const suspendCheck = async () => {
  if (!suspendReason.value.trim()) {
    return uni.showToast({ title: '请输入中止检验原因', icon: 'error' })
  }
  closeSuspendPopup()
  uni.showLoading({ title: '加载中' })
  const ids = selectedEquipments.value.map((item: any) => item.id)
  try {
    const result = await taskOrderItemSuspendApi({ orderItemIds: ids, reason: suspendReason.value })
    uni.hideLoading()
    if (result?.code === 0) {
      initSelect()
      fetchCheckerOnlineEquipmentList()
      uni.showToast({ title: '中止检验成功', icon: 'success' })
      uni.$emit('RefreshOrder')
    } else {
      const msg = result?.msg || '中止检验失败'
      uni.showToast({ title: msg, icon: 'error' })
    }
  } catch (error) {
    uni.hideLoading()
    uni.showToast({ title: '中止检验失败', icon: 'error' })
  }
}

const createInform = async () => {
  const networkType = uni.getNetworkType?.()
  if (networkType === 'none') {
    return uni.showToast({ title: '无网络连接，请联网重试' })
  }
  if (!orderId.value) return
  try {
    showMoreOperate.value = false
    const equipment = selectedEquipments.value[0]
    const majorcheckres = await orderItemMajorCheck({ orderItemIds: [equipment?.id] })
    const equipmentReportId =
      (equipment.reportDOList || []).find((item: any) => item.reportType === 500)?.id || ''
    if (majorcheckres.data[equipment?.id]) {
      const item = majorcheckres.data[equipment?.id]
      if (item.isSignature === '1') {
        uni.redirectTo({
          url: `/pages/sign-detail/index?orderId=${orderId.value}&type=ZXXX&orderItemId=${equipment?.id}&reportId=${equipmentReportId}`,
        })
      } else {
        uni.redirectTo({
          url: `/pages/sign/index?orderId=${orderId.value}&type=ZXXX&orderItemId=${equipment?.id}&reportId=${equipmentReportId}`,
        })
      }
      return
    }
    const configRes = await signApis.getGcConfig(
      {
        orderId: orderId.value,
        businessType: 400,
        orderItemId: equipment.id,
      },
      userInfo.value,
    )
    if (configRes?.code === 0) {
      const initJSONResult = await getEquipmentsTemplateJSONData({
        taskOrderNo: orderNo.value,
        templateId: configRes.data?.templateId,
        equipCode: equipment?.equipCode,
      })
      const dataStr = initJSONResult?.data ? JSON.parse(initJSONResult.data) : {}
      const { id, nickname, mobile } = userInfo.value || {}
      const params = {
        dataStr: JSON.stringify({
          ...dataStr,
          notifierSignName: nickname,
          notifierSignDate: dayjs().format('YYYY年MM月DD日'),
          notifierPhone: mobile,
        }),
        standardInitData: configRes.data?.standardInitData,
        templateUrl: configRes.data?.templateUrl,
        templateId: configRes.data?.templateId,
        orderItemId: equipment.id,
        prepareId: id || '',
        prepareName: nickname || '',
        translateInitData: '{}',
        reportId: equipmentReportId,
      }
      const businessConfig = createBusinessConfig('ZXXX')
      setSpreadsheetEditParams({
        routeType: 'ZXXX',
        orderId: orderId.value,
        gcConfig: params,
        businessConfig,
      })
      uni.navigateTo({
        url: `/pages/webview/generic-webview?businessType=ZXXX&orderId=${orderId.value}&templateId=${configRes.data?.id}&useOnline=1`,
      })
    } else {
      uni.showToast({ title: '获取配置信息失败' })
    }
  } catch (configError) {
    console.error('获取葡萄城配置信息失败:', configError)
    uni.showToast({ title: '获取配置信息失败，请重试' })
  }
}

const showAddSpacePopup = async () => {
  if (!selectedEquipments.value.length) {
    return uni.showToast({ title: '请先选择设备', icon: 'error' })
  }
  try {
    const result = await notVerifyPageApi({ type: '10', status: 200, pageNo: 1, pageSize: 9999 })
    const list = (result?.data?.list || []).map((item: any) => {
      return { ...item, label: item.name || '', value: item.id || '' }
    })
    if (!list.length) {
      return uni.showToast({ title: '暂无有限空间记录模板', icon: 'error' })
    }
    spaceTemplateList.value = list
    selectedSpaceTemplateId.value = ''
    showMoreOperate.value = false
    showSpaceTemplatePopup.value = true
  } catch (error) {
    uni.showToast({ title: '获取有限空间记录模板失败' })
  }
}

const confirmSpaceTemplate = () => {
  if (!selectedSpaceTemplateId.value) {
    return uni.showToast({ title: '请选择一个模板', icon: 'error' })
  }
  const currentTemplate = spaceTemplateList.value.find(
    (item) => item.id === selectedSpaceTemplateId.value,
  )
  if (!currentTemplate) {
    return uni.showToast({ title: '模板不存在', icon: 'error' })
  }
  const currentRow = selectedEquipments.value[0]
  const defaultDataSource: Record<string, any> = {
    reportNo: currentTemplate.name,
    jyName: userInfo.value?.nickname || '',
    signName: userInfo.value?.nickname || '',
    signDate: formatDate(new Date(), 'YYYY年MM月DD日'),
  }
  const reportRespVOList = currentRow?.reportDOList || []
  const unitName = currentRow?.unitName || ''
  defaultDataSource.reportNo = reportRespVOList[0]?.reportNo || ''
  defaultDataSource.unitName = unitName
  const params = {
    dataStr: JSON.stringify({ ...defaultDataSource }),
    standardInitData: currentTemplate?.bindingPathSchema,
    templateUrl: currentTemplate?.recordTemplateUrl || '',
    templateId: currentTemplate?.id,
    orderId: orderId.value,
    orderItemId: currentRow.id,
    prepareId: userInfo.value?.id || '',
    prepareName: userInfo.value?.nickname || '',
    reportName: currentTemplate.name || '',
    translateInitData: '{}',
    cacheParams: {
      objId: `${currentRow.id}_${currentTemplate.id}`,
      type: 8,
      cachTime: currentRow.updateTime || currentRow.createTime,
    },
  }
  const businessConfig = createBusinessConfig('YXKJ')
  setSpreadsheetEditParams({
    routeType: 'YXKJ',
    orderId: orderId.value,
    gcConfig: params,
    businessConfig,
  })
  showSpaceTemplatePopup.value = false
  uni.navigateTo({
    url: `/pages/webview/generic-webview?businessType=YXKJ&orderId=${orderId.value}&templateId=${currentTemplate.id}&useOnline=1`,
  })
}

const createBusinessConfig = (name) => {

}

const showAddInspectionplanPopup = async () => {
  if (!canAddInspectionplan.value) {
    return uni.showToast({ title: '请先选择设备', icon: 'error' })
  }
  showMoreOperate.value = false
  showInspectionplanPopup.value = true
  inspectionplanName.value = ''
  selectedTemplate.value = null
  try {
    const result = await notVerifyPageApi({ type: '1', status: 200, pageNo: 1, pageSize: 9999 })
    templateList.value = result?.data?.list || []
  } catch (error) {
    console.error('获取模板列表失败:', error)
  }
}

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

const onTemplateChange = ({ selected }) => {
  const index = selected[0]
  selectedTemplate.value = templateList.value[index]
  selectedTemplateId.value = selectedTemplate.value?.id || ''
}

const addInspectionplanConfirm = async () => {
  const templateId = selectedTemplate.value?.id
  if (!templateId) {
    return uni.showToast({ title: '请选择模板封面', icon: 'error' })
  }
  if (!inspectionplanName.value.trim()) {
    return uni.showToast({ title: '请输入检验方案名称', icon: 'error' })
  }
  closeInspectionplanPopup()
  await handleSuccessInspectionplan({ templateId, reportName: inspectionplanName.value.trim() })
}

const handleSuccessInspectionplan = async (info: any) => {
  try {
    uni.showLoading({ title: '添加中' })
    const resultData = await getEquipmentsTemplateJSONData({
      taskOrderNo: orderNo.value,
      templateId: info.templateId,
      equipCode: selectedEquipments.value[0].equipCode,
    })
    const defaultUser: Record<string, any> = {
      prepareName: userInfo.value?.nickname || '',
      prepareDate: dayjs().format('YYYY年MM月DD日'),
    }
    const initJSONResult = resultData?.data || ''
    const prepareJson = initJSONResult
      ? { ...JSON.parse(initJSONResult), ...defaultUser }
      : defaultUser
    const addParams = {
      orderId: orderId.value,
      templateId: info.templateId,
      prepareJson: JSON.stringify(prepareJson),
      prepareId: userInfo.value?.id,
      prepareName: userInfo.value?.nickname,
      orderItemIds: selectedEquipments.value.map((item) => item.id),
      reportName: info.reportName,
    }
    const result = await addMajorIssuesApi(addParams)
    const newReportId = result?.data || ''
    if (!newReportId) {
      uni.hideLoading()
      return uni.showToast({ title: '添加失败', icon: 'error' })
    }
    const url = `/pages/inspectionplanDetail/inspectionplanDetail?reportId=${newReportId}&reportName=${info.reportName}&orderId=${orderId.value}&templateId=${info.templateId}&prepareJson=${encodeURIComponent(JSON.stringify(prepareJson))}`
    uni.navigateTo({ url })
  } catch (error) {
    uni.showToast({ title: '添加检验方案失败', icon: 'error' })
  } finally {
    uni.hideLoading()
  }
}

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

const handleRouteToEquipmentDetail = (item: any, pageType: string) => {
  uni.navigateTo({
    url: `/pages/equipment/detail/equipmentDetail?orderId=${orderId.value}&orderItemId=${item.id}&equipId=${item.equipId}&pageType=${pageType}&useOnline=1&canEdit=${true}`,
  })
}

const handleCalcTotalFee = (reportDOList: any) => {
  if (!reportDOList || !Array.isArray(reportDOList)) return 0
  return reportDOList
    .filter((x: any) => x.fee && !isNaN(x.fee) && typeof x.fee === 'number')
    .reduce((sum: number, item: any) => sum + item.fee, 0)
}

const goBack = () => {
  uni.navigateBack()
}
</script>

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

.navigate-view {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  height: 44px;
  padding: 0 12px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
}

.navigate-left {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
}

.back-icon {
  width: 20px;
  height: 20px;
}

.navigate-title {
  flex: 1;
  font-size: 17px;
  font-weight: 500;
  color: #333;
  text-align: center;
}

.navigate-right {
  width: 40px;
}

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

.equipment-cell {
  padding: 12px;
  margin: 12px;
  margin-bottom: 0;
  background-color: #fff;
  border-radius: 5px;
}

.cell-top {
  padding-bottom: 10px;
  margin-bottom: 10px;
  border-bottom: 1px solid rgb(244, 244, 244);
}

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

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

.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: 8px;
  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;
  margin-top: 10px;
}

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

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

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

.picker-value {
  padding: 8px;
  font-size: 14px;
  color: #333;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.form-input {
  padding: 8px;
  font-size: 14px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.template-scroll {
  max-height: 200px;
  margin-bottom: 15px;
}

.template-item {
  padding: 10px;
  font-size: 14px;
  color: #333;
  border-bottom: 1px solid #eee;
}

.template-item.active {
  color: #2f8eff;
  background-color: #f0f8ff;
}
</style>
