<template>
  <view class="inspect-project-container">
    <scroll-view class="scroll-list" scroll-y>
      <view class="report-list">
        <view v-for="([part, reportArr], index) in reportGroupedList" :key="index">
          <!-- 暂时注释掉的部件分组逻辑 -->
          <!-- <view v-if="part.id != null" class="part-card">
            <view class="part-card-header">
              <text class="part-card-header-text">{{ part.partName }}</text>
              <view class="part-card-header-btn-group">
                <view>复制</view>
                <view>增加</view>
                <view>删除</view>
              </view>
            </view>
            <view v-for="item in reportArr" :key="item.id" class="report-item">
              <view class="item-top" @click="handleSelectProject(item)">
                <view class="top-left">
                  <radio
                    :checked="selectedProjects.includes(item.id)"
                    color="#4B8CD9"
                    @click.stop="handleSelectProject(item)"
                  />
                  <text class="report-name">{{ item.reportName }}</text>
                  <view
                    class="type-tag"
                    :style="{ backgroundColor: getReportTypeColor(item.reportType) }"
                  >
                    <text class="type-tag-text">{{ getReportTypeIcon(item.reportType) }}</text>
                  </view>
                </view>
                <text class="status-text" :style="{ color: getStatusColor(item, useOnline) }">
                  {{ getStatusText(item, useOnline) }}
                </text>
              </view>

              <view class="item-center">
                <view class="center-row">
                  <text class="label">检验结论：</text>
                  <view
                    class="conclusion-box"
                    :class="{
                      'conclusion-error': isConclusionError(getRecordJson(item).reportConclusion),
                    }"
                    @click="handleUpdateConclusion(item, 'reportConclusion')"
                  >
                    <text
                      class="conclusion-text"
                      :class="{
                        'conclusion-error-text': isConclusionError(
                          getRecordJson(item).reportConclusion,
                        ),
                      }"
                    >
                      {{ getRecordJson(item).reportConclusion || '无' }}
                    </text>
                  </view>

                  <view class="right-area">
                    <view
                      v-if="item.reportType === PressureReportType.SINGLE && item.instructionTempId"
                      class="instruction-tag"
                      :class="{ 'instruction-tag-error': !item.instructionId }"
                      @click="handleAssociationOperation(item)"
                    >
                      <text
                        class="instruction-text"
                        :class="{ 'instruction-text-error': !item.instructionId }"
                      >
                        {{ item.instructionId ? '已' : '未' }}关联操作指导书
                      </text>
                    </view>

                    <text v-if="item.reportType === 100" class="inspector-name">
                      主检人：{{ equipment?.mainCheckerUser?.nickname || '无' }}
                    </text>
                    <view
                      v-else-if="!isOffline && canModifyChecker"
                      class="inspector-btn"
                      @click="handleExChangeItemChecker(item)"
                    >
                      <text class="inspector-label">检验员：</text>
                      <text class="inspector-value">
                        {{ item.checkUsers?.[0]?.nickname || '无' }}
                      </text>
                    </view>
                    <text v-else class="inspector-name">
                      检验员：{{ item.checkUsers?.[0]?.nickname || '无' }}
                    </text>
                  </view>
                </view>

                <view class="center-row">
                  <text class="label">检验结果：</text>
                  <view class="result-box" @click="handleUpdateConclusion(item, 'reportResult')">
                    <text class="result-text">{{ getRecordJson(item).reportResult || '-' }}</text>
                  </view>
                </view>

                <view class="center-row">
                  <text class="label">费用金额：</text>

                  <view class="fee-area">
                    <view
                      v-if="
                        (useOnline === '1' ? shouldShowFeeInput(item.taskStatus) : true) &&
                        [
                          PressureReportType.MAIN,
                          PressureReportType.SUB,
                          PressureReportType.SINGLE,
                        ].includes(item.reportType)
                      "
                      class="fee-btns"
                    >
                      <view class="fee-value-box">
                        <text class="fee-value">
                          {{ typeof item.fee === 'number' && !isNaN(item.fee) ? item.fee : '0' }}
                        </text>
                      </view>
                      <view class="fee-btn" @click="handleCalcFee(item)">
                        <text class="fee-btn-text">费用录入</text>
                      </view>
                    </view>
                    <text v-else class="fee-none">无</text>
                  </view>

                  <view class="action-btns">
                    <template v-if="useOnline === '1'">
                      <view
                        v-if="shouldShowSign(item)"
                        class="action-btn sign-btn"
                        @click="handleSign(item)"
                      >
                        <text class="action-btn-text">签 名</text>
                      </view>

                      <view
                        v-if="shouldShowAttachmentUpload(item.taskStatus)"
                        class="action-btn attachment-btn"
                        @click="handleUploadFile(item)"
                      >
                        <text class="action-btn-text">附件上传</text>
                      </view>

                      <view
                        v-if="
                          isEditable(item) &&
                          shouldShowRecordInput(item.taskStatus) &&
                          item.reportType !== PressureReportType.SUGGUESTION
                        "
                        class="action-btn record-btn"
                        @click="handleRouteToInputWebview(item)"
                      >
                        <text class="action-btn-text">记录录入</text>
                      </view>

                      <view
                        v-if="
                          isEditable(item) &&
                          shouldShowReInput(item.taskStatus) &&
                          item.reportType !== PressureReportType.SUGGUESTION
                        "
                        class="action-btn re-input-btn"
                        @click="handleRouteToInputWebview(item)"
                      >
                        <text class="action-btn-text">重新录入</text>
                      </view>

                      <view
                        v-if="isEditable(item) && shouldShowSubmitCheck(item.taskStatus)"
                        class="action-btn submit-check-btn"
                        @click="handleSubmitCheck(item)"
                      >
                        <text class="action-btn-text">提交校核</text>
                      </view>

                      <view
                        v-if="isEditable(item) && shouldShowSubmitReport(item.taskStatus)"
                        class="action-btn submit-report-btn"
                        @click="showSelectReportUserPopup(item)"
                      >
                        <text class="action-btn-text">提交报告</text>
                      </view>
                    </template>

                    <template v-else>
                      <view class="action-btn attachment-btn" @click="handleUploadFile(item)">
                        <text class="action-btn-text">附件上传</text>
                      </view>

                      <view
                        v-if="item.reportType !== PressureReportType.SUGGUESTION"
                        class="action-btn record-btn"
                        @click="handleRouteToInputWebview(item)"
                      >
                        <text class="action-btn-text">
                          {{ !item.localReportUrl ? '记录录入' : '重新录入' }}
                        </text>
                      </view>

                      <view
                        class="action-btn submit-check-btn"
                        @click="uploadFileAndSubmitCheckItemCallback.callback(item)"
                      >
                        <text class="action-btn-text">
                          {{ item.hasSyncedData ? '重新上传' : '上传' }}
                        </text>
                      </view>

                      <view
                        v-if="
                          item.reportType !== PressureReportType.SUGGUESTION &&
                          ((useOnline === '1' && item.reportUrl) ||
                            (useOnline !== '1' &&
                              item.hasSyncedData &&
                              item.localReportUrl &&
                              item.reportUrl))
                        "
                        class="action-btn submit-check-btn"
                        @click="handleSubmitCheck(item)"
                      >
                        <text class="action-btn-text">提交校核</text>
                      </view>
                    </template>
                  </view>
                </view>
              </view>
            </view>
          </view> -->

          <!-- 如果开放了部件分组的模板，这里要加上一个 v-else 指令 -->
          <view v-for="item in reportArr" :key="item.id" class="report-item">
            <view class="item-top" @click="handleSelectProject(item)">
              <view class="top-left">
                <radio
                  :checked="selectedProjects.includes(item.id)"
                  color="#4B8CD9"
                  @click.stop="handleSelectProject(item)"
                />
                <text class="report-name">{{ item.reportName }}</text>
                <view
                  class="type-tag"
                  :style="{ backgroundColor: getReportTypeColor(item.reportType) }"
                >
                  <text class="type-tag-text">{{ getReportTypeIcon(item.reportType) }}</text>
                </view>
              </view>
              <text class="status-text" :style="{ color: getStatusColor(item, useOnline) }">
                {{ getStatusText(item, useOnline) }}
              </text>
            </view>

            <view class="item-center">
              <view class="center-row">
                <text class="label">检验结论：</text>
                <view
                  class="conclusion-box"
                  :class="{
                    'conclusion-error': isConclusionError(item.reportConclusion),
                  }"
                  @click="handleUpdateConclusion(item, 'reportConclusion')"
                >
                  <text
                    class="conclusion-text"
                    :class="{
                      'conclusion-error-text': isConclusionError(
                        item.reportConclusion
                      ),
                    }"
                  >
                    {{ item.reportConclusion || '无' }}
                  </text>
                </view>

                <view class="right-area">
                  <view
                    v-if="item.reportType === PressureReportType.SINGLE && item.instructionTempId"
                    class="instruction-tag"
                    :class="{ 'instruction-tag-error': !item.instructionId }"
                    @click="handleAssociationOperation(item)"
                  >
                    <text
                      class="instruction-text"
                      :class="{ 'instruction-text-error': !item.instructionId }"
                    >
                      {{ item.instructionId ? '已' : '未' }}关联操作指导书
                    </text>
                  </view>

                  <text v-if="item.reportType === 100" class="inspector-name">
                    主检人：{{ equipment?.mainCheckerUser?.nickname || '无' }}
                  </text>
                  <view
                    v-else-if="!isOffline && canModifyChecker"
                    class="inspector-btn"
                    @click="handleExChangeItemChecker(item)"
                  >
                    <text class="inspector-label">检验员：</text>
                    <text class="inspector-value">
                      {{ item.checkUsers?.[0]?.nickname || '无' }}
                    </text>
                  </view>
                  <text v-else class="inspector-name">
                    检验员：{{ item.checkUsers?.[0]?.nickname || '无' }}
                  </text>
                </view>
              </view>

              <view class="center-row">
                <text class="label">检验结果：</text>
                <view class="result-box" @click="handleUpdateConclusion(item, 'reportResult')">
                  <text class="result-text">{{ item.reportResult || '-' }}</text>
                </view>
              </view>

              <view class="center-row">
                <text class="label">费用金额：</text>

                <view class="fee-area">
                  <view
                    v-if="
                      (useOnline === '1' ? shouldShowFeeInput(item.taskStatus) : true) &&
                      [
                        PressureReportType.MAIN,
                        PressureReportType.SUB,
                        PressureReportType.SINGLE,
                      ].includes(item.reportType)
                    "
                    class="fee-btns"
                  >
                    <view class="fee-value-box">
                      <text class="fee-value">
                        {{ typeof item.fee === 'number' && !isNaN(item.fee) ? item.fee : '0' }}
                      </text>
                    </view>
                    <view class="fee-btn" @click="handleCalcFee(item)">
                      <text class="fee-btn-text">费用录入</text>
                    </view>
                  </view>
                  <text v-else class="fee-none">无</text>
                </view>

                <view class="action-btns">
                  <template v-if="useOnline === '1'">
                    <view
                      v-if="shouldShowSign(item)"
                      class="action-btn sign-btn"
                      @click="handleSign(item)"
                    >
                      <text class="action-btn-text">签 名</text>
                    </view>

                    <view
                      v-if="shouldShowAttachmentUpload(item.taskStatus)"
                      class="action-btn attachment-btn"
                      @click="handleUploadFile(item)"
                    >
                      <text class="action-btn-text">附件上传</text>
                    </view>

                    <view
                      v-if="
                        isEditable(item) &&
                        shouldShowRecordInput(item.taskStatus) &&
                        item.reportType !== PressureReportType.SUGGUESTION
                      "
                      class="action-btn record-btn"
                      @click="handleRouteToInputWebview(item)"
                    >
                      <text class="action-btn-text">记录录入</text>
                    </view>

                    <view
                      v-if="
                        isEditable(item) &&
                        shouldShowReInput(item.taskStatus) &&
                        item.reportType !== PressureReportType.SUGGUESTION
                      "
                      class="action-btn re-input-btn"
                      @click="handleRouteToInputWebview(item)"
                    >
                      <text class="action-btn-text">重新录入</text>
                    </view>

                    <view
                      v-if="isEditable(item) && shouldShowSubmitCheck(item.taskStatus)"
                      class="action-btn submit-check-btn"
                      @click="handleSubmitCheck(item)"
                    >
                      <text class="action-btn-text">提交校核</text>
                    </view>

                    <view
                      v-if="isEditable(item) && shouldShowSubmitReport(item.taskStatus)"
                      class="action-btn submit-report-btn"
                      @click="showSelectReportUserPopup(item)"
                    >
                      <text class="action-btn-text">提交报告</text>
                    </view>
                  </template>

                  <template v-else>
                    <view class="action-btn attachment-btn" @click="handleUploadFile(item)">
                      <text class="action-btn-text">附件上传</text>
                    </view>

                    <view
                      v-if="item.reportType !== PressureReportType.SUGGUESTION"
                      class="action-btn record-btn"
                      @click="handleRouteToInputWebview(item)"
                    >
                      <text class="action-btn-text">
                        {{ !item.localReportUrl ? '记录录入' : '重新录入' }}
                      </text>
                    </view>

                    <view
                      class="action-btn submit-check-btn"
                      @click="uploadFileAndSubmitCheckItemCallback.callback(item)"
                    >
                      <text class="action-btn-text">
                        {{ item.hasSyncedData ? '重新上传' : '上传' }}
                      </text>
                    </view>

                    <view
                      v-if="
                        item.reportType !== PressureReportType.SUGGUESTION &&
                        ((useOnline === '1' && item.reportUrl) ||
                          (useOnline !== '1' &&
                            item.hasSyncedData &&
                            item.localReportUrl &&
                            item.reportUrl))
                      "
                      class="action-btn submit-check-btn"
                      @click="handleSubmitCheck(item)"
                    >
                      <text class="action-btn-text">提交校核</text>
                    </view>
                  </template>
                </view>
              </view>
            </view>
          </view>
        </view>

        <view v-if="!reportGroupedList || reportGroupedList.size === 0" class="empty-state">
          <text class="empty-text">暂无检验项目</text>
        </view>
      </view>
    </scroll-view>

    <view class="bottom-bar">
      <view class="select-all-box" @click="handleSelectAll">
        <checkbox
          class="square-checkbox"
          :checked="selectAll"
          color="#4B8CD9"
          @click.stop="handleSelectAll"
        />
        <text class="select-all-text">{{ selectAll ? '取消全选' : '全选' }}</text>
      </view>

      <view class="action-buttons">
        <view class="operate-btn delete-btn" @click="handleDelReport">
          <text class="operate-btn-text">作废项目</text>
        </view>

        <view class="operate-btn guide-btn" @click="showAddWorkInstructionPopup">
          <text class="operate-btn-text">添加指导书</text>
        </view>

        <!-- 电站锅炉的添加部件按钮 -->
        <!-- <view
          class="operate-btn part-btn"
          v-if="equipment?.boilerType === '1' && taskOrder?.checkType === 100"
        >
          <text class="operate-btn-text">添加部件</text>
        </view> -->

        <view class="operate-btn add-btn" @click="showCheckProjectPopup">
          <text class="operate-btn-text">添加项目</text>
        </view>

        <view v-if="useOnline !== '1'" class="operate-btn upload-btn" @click="handleCheckReport">
          <text class="operate-btn-text">上传</text>
        </view>
      </view>
    </view>

    <TipsPopup ref="tipsPopupRef" />

    <CalcCheckItemPopup
      v-if="showCalcPopup"
      ref="calcCheckItemPopupRef"
      :check-item="selectedCheckItem"
      @hide="hideCalcPopup"
      @update-render-item="handleUpdateRenderItem"
    />

    <ExchangeChecker
      v-if="showExchangePopup"
      ref="exchangeCheckerPopupRef"
      :check-users="dataSource?.checkUsers"
      :current-checker="editCheckItem?.checkUsers?.[0]"
      :check-item-id="currentCheckItemId"
      @hide="hideExchangePopup"
      @update-check-item-checker="handleUpdateChecker"
    />

    <UpdateConclusionPopup
      v-if="showConclusionPopup"
      ref="updateConclusionPopupRef"
      :check-item="currentCheckItem"
      :field-key="currentFieldKey"
      @hide="hideConclusionPopup"
      @confirm="handleUpdateConclusionConfirm"
    />

    <view v-if="showSelectReportPopup" class="popup-overlay" @click="closeSelectReportPopup">
      <view class="popup-content" @click.stop>
        <text class="popup-title">确认提交报告？</text>
        <!-- <text class="popup-title">选择审核人</text>
        <picker :range="recheckUserGroupList" range-key="label" @change="onReportUserChange">
          <view class="picker-value">
            <text>{{ currentReckUser?.label || '请选择' }}</text>
          </view>
        </picker> -->
        <view class="popup-actions">
          <button class="action-btn cancel-btn" @click="closeSelectReportPopup">取消</button>
          <button class="action-btn confirm-btn" @click="handleSubmitReport">确定</button>
        </view>
      </view>
    </view>

    <view v-if="showSelectTemplatePopup" class="popup-overlay" @click="closeSelectTemplatePopup">
      <view class="popup-content" @click.stop>
        <text class="popup-title">选择模板</text>
        <picker :range="templateList" range-key="label" @change="onTemplateChange">
          <view class="picker-value">
            <text>{{ selectedTemplate?.label || '请选择' }}</text>
          </view>
        </picker>
        <view class="popup-actions">
          <button class="action-btn cancel-btn" @click="closeSelectTemplatePopup">取消</button>
          <button class="action-btn confirm-btn" @click="handleConfirmTemplate">确定</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import {
  PressureCheckerMyTaskStatus,
  PressureReportType,
  PressureCheckerMyTaskStatusMap,
} from '@/utils/dictMap'
import { isCheckItemEditable, isAssignedToOthers } from '@/utils/equipmentPermissions'

import {
  getApprovalDetail,
  getUserGroupUserList,
  pressure2NotVerifyPageApi,
} from '@/api/task'
import { cancelBoilerInSpectProject, addBoilerMajorIssues, submitBoilerReport } from '@/api/boiler/boilerTaskOrder'

import { updateBoilerTaskOrderItemReportConclusion } from '@/api/boiler/boilerTaskOrderReport'
import TipsPopup from './inspectProjectComponent/TipsPopup.vue'
import CalcCheckItemPopup from './inspectProject/component/calcCheckItemPopup.vue'
import ExchangeChecker from './inspectProject/component/ExchangeChecker.vue'
import UpdateConclusionPopup from './inspectProject/component/UpdateConclusionPopup.vue'
import eventBus from '@/utils/eventBus'
import { useUserStore } from '@/store/user'

interface CheckConclusionItem {
  value: string
  id: string
}

interface CheckItem {
  id: string
  reportName: string
  localReportUrl?: string
  prepareJson?: string | object
  reportType?: number
  recordJson?: string
  [key: string]: any
}

interface Props {
  reportList: CheckItem[]
  taskOrder: StringAnyObj
  equipment: StringAnyObj
  dataSource: any
  orderId: string
  orderItemId: string
  useOnline?: string
  isMainChecker?: boolean
  canModifyAssignments?: boolean
  updateReportList?: (reportList: CheckItem[]) => void
  fetchGetEquipmentDetail?: () => void
  refreshDetail?: () => void
  showSelectUserPopup?: (checkItem: CheckItem) => void
  handleAssociationOperationManual?: (checkItem: CheckItem) => void
  showCheckProjectPopupFn?: () => void
}

const props = withDefaults(defineProps<Props>(), {
  reportList: () => [],
  useOnline: '1',
  dataSource: {
    partList: [],
  },
  isMainChecker: false,
  canModifyAssignments: false,
})

const reportGroupedList = computed(() => {
  const groupedList: Map<any, any> = new Map()

  if (!props.dataSource?.partList) {
    return groupedList
  }
  // 按照 partType 排序
  const sortedPartList = [...props.dataSource.partList].sort((a, b) => {
    const typeA = parseInt(a.partType) || 0
    const typeB = parseInt(b.partType) || 0
    return typeA - typeB
  })

  sortedPartList.forEach((item) => {
    if (!groupedList.has(item)) {
      groupedList.set(item, [])
    }
    // 如果item.id为空，添加itemPartId为'0'或空的报告
    if (!item.id) {
      const equipReport = props.reportList.filter(
        (report) => !report.itemPartId || report.itemPartId === '0',
      )
      groupedList.set(item, equipReport)
    } else {
      const partReport = props.reportList.filter((report) => report.itemPartId === item.id)
      groupedList.set(item, partReport)
    }
  })

  return groupedList
})

const emit = defineEmits<{
  updateReportList: [list: CheckItem[]]
  refresh: []
}>()

const selectAll = ref(false)
const selectedProjects = ref<string[]>([])
const selectedCheckItem = ref<any>(null)
const editCheckItem = ref<any>(null)
const currentCheckItemId = ref('')
const currentCheckItem = ref<any>(null)
const currentFieldKey = ref<'reportConclusion' | 'reportResult'>('reportConclusion')
const refreshing = ref(false)
const isOffline = ref(false)

const showCalcPopup = ref(false)
const showExchangePopup = ref(false)
const showConclusionPopup = ref(false)
const showSelectReportPopup = ref(false)

const tipsPopupRef = ref<any>(null)
const calcCheckItemPopupRef = ref<any>(null)
const exchangeCheckerPopupRef = ref<any>(null)
const updateConclusionPopupRef = ref<any>(null)

const currentReportItem = ref<any>(null)
const recheckUserGroupList = ref<any[]>([])
const currentReckUser = ref<any>(null)

const showSelectTemplatePopup = ref(false)
const templateList = ref<any[]>([])
const selectedTemplate = ref<any>(null)

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

const canModifyChecker = computed(() => {
  return props.canModifyAssignments && props.isMainChecker
})

const isNetworkConnected = ref(true)
onMounted(() => {
  checkNetworkStatus()
  initSelected()
  setupEventListeners()
})

onUnmounted(() => {
  removeEventListeners()
})

const checkNetworkStatus = () => {
  isOffline.value = !isNetworkConnected.value
}

const setupEventListeners = () => {
  eventBus.on('RefreshInspectProject', () => {
    initSelected()
    props.fetchGetEquipmentDetail?.()
  })

  eventBus.on('webViewSaved', (data: any) => {
    initSelected()
    if (props.useOnline === '1' && data.isOnline) {
      const updatedReportList = (props.reportList || []).map((item: any) => {
        if (item.id === data.checkItemId) {
          return {
            ...item,
            reportUrl: data.reportUrl,
            bindingPathSchema: data.bindingPathSchema,
            prepareJson: data.prepareJson,
          }
        }
        return item
      })
      emit('updateReportList', updatedReportList)
      props.refreshDetail?.()
    } else {
      props.fetchGetEquipmentDetail?.()
    }
  })

  uni.$on('onNetworkStatusChange', (connected: boolean) => {
    isOffline.value = !connected
  })
}

const removeEventListeners = () => {
  eventBus.off('RefreshInspectProject')
  eventBus.off('webViewSaved')
  uni.$off('onNetworkStatusChange')
}

const onRefresh = async () => {
  if (props.useOnline !== '1') return

  refreshing.value = true
  try {
    props.refreshDetail?.()
  } catch (error) {
    console.error('下拉刷新失败:', error)
  } finally {
    refreshing.value = false
  }
}

const initSelected = () => {
  selectAll.value = false
  selectedProjects.value = []
}

const handleSelectAll = () => {
  selectAll.value = !selectAll.value
  if (selectAll.value) {
    selectedProjects.value = props.reportList.map((item) => item.id)
  } else {
    selectedProjects.value = []
  }
}

const handleSelectProject = (item: CheckItem) => {
  const index = selectedProjects.value.indexOf(item.id)
  if (index === -1) {
    selectedProjects.value.push(item.id)
  } else {
    selectedProjects.value.splice(index, 1)
  }
  selectAll.value = selectedProjects.value.length === props.reportList.length
}

const getRecordJson = (item: CheckItem): Record<string, any> => {
  try {
    return item.recordJson && typeof item.recordJson === 'string' ? JSON.parse(item.recordJson) : {}
  } catch {
    return {}
  }
}

const isConclusionError = (conclusion: string): boolean => {
  return /不合格|不符合/.test(conclusion || '')
}

const getReportTypeIcon = (reportType?: number): string | null => {
  switch (reportType) {
    case PressureReportType.MAIN:
      return '主'
    case PressureReportType.SINGLE:
      return '独'
    case PressureReportType.SUB:
      return '子'
    case PressureReportType.SUGGUESTION:
    case PressureReportType.MAINQUESTION:
    case PressureReportType.WORKINSTRUCTION:
      return '附'
    default:
      return null
  }
}

const getReportTypeColor = (reportType?: number): string => {
  switch (reportType) {
    case PressureReportType.MAIN:
      return 'rgb(68,127,241)'
    case PressureReportType.SINGLE:
      return 'rgb(230,162,60)'
    case PressureReportType.SUB:
      return 'rgb(145,213,255)'
    case PressureReportType.SUGGUESTION:
    case PressureReportType.MAINQUESTION:
    case PressureReportType.WORKINSTRUCTION:
      return '#fff'
    default:
      return '#fff'
  }
}

const getStatusText = (item: CheckItem, useOnline?: string): string => {
  if (useOnline === '1') {
    if (
      item.taskStatus === PressureCheckerMyTaskStatus.RECORD_CHECK &&
      item.recheckStatus === 200
    ) {
      return '校核已通过'
    }
    return PressureCheckerMyTaskStatusMap[item.taskStatus] || '待录入'
  } else {
    return !item.localReportUrl ? '待录入' : '已录入'
  }
}

const getStatusColor = (item: CheckItem, useOnline?: string): string => {
  if (useOnline === '1') {
    if (
      item.taskStatus === PressureCheckerMyTaskStatus.RECORD_CHECK &&
      item.recheckStatus === 200
    ) {
      return '#52C41A'
    }
    return '#4B8CD9'
  } else {
    return !item.localReportUrl ? '#FF3535' : '#4B8CD9'
  }
}

const shouldShowFeeInput = (taskStatus?: number): boolean => {
  return taskStatus !== undefined
}

const shouldShowSign = (item: CheckItem): boolean => {
  return item.isSignFunction === 1 && item.taskStatus === PressureCheckerMyTaskStatus.RECORD_INPUT
}

const shouldShowAttachmentUpload = (taskStatus?: number): boolean => {
  // return taskStatus !== undefined
  return false
}

const shouldShowRecordInput = (taskStatus?: number): boolean => {
  return taskStatus === PressureCheckerMyTaskStatus.CONFIRMED
}

const shouldShowReInput = (taskStatus?: number): boolean => {
  return taskStatus === PressureCheckerMyTaskStatus.RECORD_INPUT
}

const shouldShowSubmitCheck = (taskStatus?: number): boolean => {
  return taskStatus === PressureCheckerMyTaskStatus.RECORD_INPUT
}

const shouldShowSubmitReport = (taskStatus?: number): boolean => {
  return taskStatus === PressureCheckerMyTaskStatus.REPORT_INPUT
}

const isEditable = (item: CheckItem): boolean => {
  return isCheckItemEditable(item, userInfo.value, props.equipment)
}

const isAssignedToOther = (item: CheckItem): boolean => {
  return isAssignedToOthers(item, userInfo.value)
}

const handleRouteToInputWebview = (item: CheckItem) => {
  const userId =
    item.reportType === PressureReportType.MAIN
      ? props.equipment?.mainCheckerUser?.id
      : item?.checkUsers?.[0]?.id

  if (userId && userId !== userInfo.value?.id) {
    uni.showToast({ title: '已分配项目不支持记录录入', icon: 'error' })
    return
  }

  uni.navigateTo({
    url: `/pages/editor/equipCheckRecordEditor?userId=${userInfo.value?.id}&orderItemId=${props.orderItemId}&checkItemId=${item?.id}&templateId=${item.templateId}&equipCode=${item.equipCode}&useOnline=${props.useOnline}&reportUrl=${item.reportUrl || ''}`,
  })
}

const handleCalcFee = (item: CheckItem) => {
  const mainCheckerId =
    item.reportType === PressureReportType.MAIN
      ? props.equipment?.mainCheckerUser?.id
      : item?.checkUsers?.[0]?.id

  if (mainCheckerId && mainCheckerId !== userInfo.value?.id) {
    uni.showToast({ title: '只能主检人进行费用录入', icon: 'error' })
    return
  }

  if (item.taskStatus === PressureCheckerMyTaskStatus.REPORT_END) {
    uni.showToast({ title: '报告已办结，不能录入费用', icon: 'error' })
    return
  }

  selectedCheckItem.value = item
  showCalcPopup.value = true
}

const hideCalcPopup = () => {
  showCalcPopup.value = false
  selectedCheckItem.value = null
}

const handleUpdateRenderItem = async (calcData: any) => {
  await updateBoilerTaskOrderItemReportConclusion(calcData)
  const report = props.reportList.find(item => item.id === calcData.id)
  const feeKey = 'fee'
  report[feeKey] = calcData[feeKey]
  props.refreshDetail()
  showCalcPopup.value = false
  // const updatedList = props.reportList.map((x) => {
  //   if (x.id === calcData.id) {
  //     return {
  //       ...x,
  //       fee: calcData.fee,
  //       feeCalculateJson: calcData.feeCalculateJson,
  //     }
  //   }
  //   return x
  // })
  // emit('updateReportList', updatedList)
  // initSelected()
}

const handleExChangeItemChecker = (item: CheckItem) => {
  if (item.isLocal) {
    uni.showToast({ title: '本地项目不能修改检验员,请上传', icon: 'error' })
    return
  }

  editCheckItem.value = item
  currentCheckItemId.value = item.id
  showExchangePopup.value = true
}

const hideExchangePopup = () => {
  showExchangePopup.value = false
  editCheckItem.value = null
  currentCheckItemId.value = ''
}

const handleUpdateChecker = async (checker: any, checkItemId: string) => {
  console.log('checker......', checker, checkItemId)
  // try {
  //   const newChecker = typeof checker === 'string' ? JSON.parse(checker) : checker
  //   if (!newChecker.id) {
  //     console.warn('Checker missing id')
  //     return
  //   }

  //   const { handleUpdateReportCheckUsers } = await import('@/api/task')
  //   const result = await handleUpdateReportCheckUsers(newChecker, checkItemId)

  //   if (result) {
  //     uni.showToast({ title: '更新检验员成功' })
  //     hideExchangePopup()
  //     props.refreshDetail?.()
  //   }
  // } catch (error) {
  //   console.error('更新检验员失败:', error)
  //   uni.showToast({ title: '更新检验员失败', icon: 'error' })
  // }
}

const handleUpdateConclusion = (item: CheckItem, fieldKey: 'reportConclusion' | 'reportResult') => {
  if (item.isLocal) {
    uni.showToast({ title: '本地项目不能修改检验结论', icon: 'error' })
    return
  }

  const canUpdate = [
    PressureCheckerMyTaskStatus.CONFIRMED,
    PressureCheckerMyTaskStatus.RECORD_INPUT,
  ].includes(item.taskStatus)
  if (!canUpdate) return

  currentCheckItem.value = item
  currentFieldKey.value = fieldKey
  showConclusionPopup.value = true
}

const hideConclusionPopup = () => {
  showConclusionPopup.value = false
  currentCheckItem.value = null
  currentFieldKey.value = 'reportConclusion'
}

const handleUpdateConclusionConfirm = async (conclusionData: any) => {
  await updateBoilerTaskOrderItemReportConclusion(conclusionData)
  // 先前端缓存结果，让响应更快，从而可以不引入Loading动画表达中间过渡
  for (const key in conclusionData) {
    if (!Object.hasOwn(conclusionData, key)) continue;
    const element = conclusionData[key];
    currentCheckItem.value[key] = element
  }
  props.refreshDetail()
  showConclusionPopup.value = false
}

const handleSubmitCheck = (item: CheckItem) => {
  const { isSignFunction, signFunctionUrl, reportType } = item

  if (isSignFunction === 1 && !signFunctionUrl) {
    uni.showToast({
      title: '客户未签名，不支持提交校核',
      icon: 'none',
    })
    return
  }

  props.showSelectUserPopup?.(item)
}

const showSelectReportUserPopup = async (item: CheckItem) => {
  if (props.useOnline !== '1') {
    uni.showToast({ title: '离线模式不支持提交报告', icon: 'none' })
    return
  }

  currentReportItem.value = item
  // await getAuditUserGroupList(item)
  showSelectReportPopup.value = true
}

const getAuditUserGroupList = async (checkItem: any) => {
  try {
    const groupRes: any = await getApprovalDetail({})
    const { recheckId, approveUser, yearCheckRecheckJson } = groupRes?.data || {}

    const yearCheckRecheckJsonData = yearCheckRecheckJson ? JSON.parse(yearCheckRecheckJson) : {}
    const { checkType } = props.taskOrder || {}
    const { reportType } = checkItem || {}
    const isYearCheckType = checkType === 200 && reportType === PressureReportType.MAIN

    const category = isYearCheckType ? 201 : 200
    const filterId = isYearCheckType ? yearCheckRecheckJsonData.yearCheckRecordAuditId : recheckId

    const userRes: any = await getUserGroupUserList({ category, status: 0 })
    const list = (userRes?.data || []).map((item: any) => ({
      ...item,
      label: item.nickname,
      value: item.id,
    }))
    const defaultItem = list.find((item: any) => item.value === filterId) || {}

    currentReckUser.value = defaultItem
    recheckUserGroupList.value = list
  } catch (error) {
    console.error('获取审核人列表失败:', error)
    uni.showToast({ title: '获取审核人列表失败', icon: 'error' })
  }
}

const onReportUserChange = (e: any) => {
  const index = e.detail.value
  currentReckUser.value = recheckUserGroupList.value[index]
}

const handleSubmitReport = async () => {
  // if (!currentReckUser.value) {
  //   uni.showToast({ title: '请选择审核人', icon: 'error' })
  //   return
  // }

  if (!currentReportItem.value) {
    uni.showToast({ title: '报告信息丢失，请重试', icon: 'error' })
    return
  }

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

    const params = {
      id: currentReportItem.value.id,
      approveId: userInfo.value?.id,
      reportType: currentReportItem.value.reportType,
    }

    const result: any = await submitBoilerReport(params)

    uni.hideLoading()

    if (result?.code === 0) {
      uni.showToast({ title: '提交报告成功', icon: 'success' })
      showSelectReportPopup.value = false
      props.fetchGetEquipmentDetail?.()
      props.refreshDetail?.()
      currentReportItem.value = null
    } else {
      uni.showToast({ title: result?.msg || '提交失败', icon: 'error' })
    }
  } catch (error: any) {
    uni.hideLoading()
    console.error('提交报告失败:', error)
    uni.showToast({ title: error?.msg || '提交失败，请重试', icon: 'error' })
  }
}

const closeSelectReportPopup = () => {
  showSelectReportPopup.value = false
  currentReportItem.value = null
}

const handleSign = (item: CheckItem) => {
  const { unitContact, unitPhone } = props.taskOrder || {}

  uni.navigateTo({
    url: `/pages/sign-report/index?reportId=${item.id}&pushName=${unitContact}&pushPhone=${unitPhone}`,
  })
}

const handleUploadFile = (item: CheckItem) => {
  const userId =
    item.reportType === PressureReportType.MAIN
      ? props.equipment?.mainCheckerUser?.id
      : item?.checkUsers?.[0]?.id

  const readOnly = isAssignedToOther(item)

  const fileList = props.reportList?.map((i: any) => ({
    checkItemId: i?.id,
    reportName: i?.reportName,
    image: i.image,
    video: i.video,
    attachment: i.attachment,
  }))

  uni.navigateTo({
    url: `/pages/uploadFile/UploadFile?isEdit=${!readOnly}&checkItemId=${item?.id}&fileList=${encodeURIComponent(JSON.stringify(fileList))}&useOnline=${props.useOnline}&readOnly=${readOnly}`,
  })
}

const handleAssociationOperation = (item: CheckItem) => {
  props.handleAssociationOperationManual?.(item)
}

const showAddWorkInstructionPopup = async () => {
  try {
    const result = await pressure2NotVerifyPageApi({ reportType: PressureReportType.WORKINSTRUCTION, status: 200, pageNo: 1, pageSize: 9999 })
    const list = (result?.data || []).map((item: any) => ({
      ...item,
      label: item.tbName || '',
      value: item.id || '',
    }))

    if (!list.length) {
      uni.showToast({ title: '暂无指导书模板', icon: 'error' })
      return
    }

    templateList.value = list
    selectedTemplate.value = null
    showSelectTemplatePopup.value = true
  } catch (error) {
    console.error('获取操作指导书模板失败:', error)
    uni.showToast({ title: '获取操作指导书模板失败', icon: 'error' })
  }
}

const closeSelectTemplatePopup = () => {
  showSelectTemplatePopup.value = false
  selectedTemplate.value = null
}

const onTemplateChange = (e: any) => {
  const index = e.detail.value
  selectedTemplate.value = templateList.value[index]
}

const handleConfirmTemplate = async () => {
  if (!selectedTemplate.value) {
    uni.showToast({ title: '请选择模板', icon: 'error' })
    return
  }

  try {
    uni.showLoading({ title: '添加中...' })

    const params = {
      orderId: props.orderId,
      orderItemId: props.orderItemId,
      templateId: selectedTemplate.value.value,
      prepareId: userInfo.value?.id || '',
      prepareName: userInfo.value?.nickname || '',
    }

    const result = await addBoilerMajorIssues(params)

    if (result.code !== 0) {
      uni.hideLoading()
      uni.showToast({ title: result?.msg || '添加失败', icon: 'error' })
      return
    }

    const newReportId = result?.data || ''
    if (!newReportId) {
      uni.hideLoading()
      uni.showToast({ title: '添加失败', icon: 'error' })
      return
    }
    
    uni.navigateTo({
      url: `/pages/editor/workInstructionEditor?templateId=${selectedTemplate.value.value}&refId=${newReportId}`,
    })
  } catch (error) {
    uni.hideLoading()
    console.error('添加指导书失败:', error)
    uni.showToast({ title: '添加指导书失败', icon: 'error' })
  } finally {
    uni.hideLoading()
    closeSelectTemplatePopup()
    props.refreshDetail?.()
  }
}

const showCheckProjectPopup = () => {
  props.showCheckProjectPopupFn?.()
}

const handleCheckReport = async () => {
  if (selectedProjects.value.length === 0) {
    uni.showToast({ title: '请选择要上传的项目', icon: 'error' })
    return
  }

  try {
    const itemArray = selectedProjects.value
      .map((id) => props.reportList.find((i) => i.id === id))
      .filter(Boolean)

    for (const checkItem of itemArray) {
      const userId =
        checkItem.reportType === PressureReportType.MAIN
          ? props.equipment?.mainCheckerUser?.id
          : checkItem?.checkUsers?.[0]?.id

      if (userId && userId !== userInfo.value?.id) {
        uni.showToast({ title: '已分配项目不支持上传', icon: 'error' })
        return
      }
    }

    const { checkedCheckItemhasSubmited } = await import('@/api/task')
    const promiseArr = itemArray.map((item) => checkedCheckItemhasSubmited({ id: item.id }))
    const result = await Promise.all(promiseArr)

    const checkNameArr = []
    for (const res of result) {
      if (res?.code === 0 && res?.data?.isSubmit) {
        checkNameArr.push(res?.data.checkName)
      }
    }

    if (checkNameArr?.length) {
      tipsPopupRef.value?.show({
        text: `检验员：${checkNameArr.join('、')}已经提交过，确定要覆盖吗？`,
        confirm: handleBatchUpload,
      })
    } else {
      handleBatchUpload()
    }
  } catch (error) {
    console.error('批量上传失败:', error)
    uni.showToast({ title: '项目检验失败', icon: 'error' })
  }
}

const handleBatchUpload = async () => {
  try {
    uni.showLoading({ title: '上传中...' })

    const itemArray = selectedProjects.value
      .map((id) => props.reportList.find((i) => i.id === id))
      .filter(Boolean)

    const params: any = { addList: [], updateList: [] }

    itemArray.forEach((item) => {
      const dic = {
        orderId: props.orderId,
        orderItemId: props.orderItemId,
        reportUrl: item.reportUrl || '',
        dataJson: '',
        prepareUrl: '',
        prepareJson: item.prepareJson || '',
        modifiedReason: '',
        templateId: item.templateId,
        reportType: item.reportType,
        equipAddress: props.equipment?.equipAddress || '',
        equipLatitude: props.equipment?.equipLatitude || '',
        equipLongitude: props.equipment?.equipLongitude || '',
        fee: item?.fee || 0,
      }

      if (item.isLocal) {
        dic.localId = item.id
        params.addList.push(dic)
      } else {
        dic.id = item.id
        params.updateList.push(dic)
      }
    })

    const { postCheckItemRecordEnter } = await import('@/api/task')
    const postResult = await postCheckItemRecordEnter(params)

    uni.hideLoading()

    if (postResult.data) {
      uni.showToast({ title: '提交成功', icon: 'success' })
      props.refreshDetail?.()
      initSelected()
    } else {
      uni.showToast({ title: postResult?.msg || '提交失败', icon: 'error' })
    }
  } catch (error) {
    uni.hideLoading()
    console.error('批量上传失败:', error)
    uni.showToast({ title: '批量上传失败', icon: 'error' })
  }
}

const handleDelReport = () => {
  if (selectedProjects.value.length === 0) {
    uni.showToast({ title: '请选择要作废的项目', icon: 'error' })
    return
  }

  // 主检人可以作废所有项目（未提交校核的项目，且不包括主项目），检验人只能作废自己的项目
  // 目前在 equipmentDetail 中会过滤掉不可见的报告，所以不需要根据身份检查作废项目的权限

  const hasMain = selectedProjects.value.some((id) => {
    const item = props.reportList.find((i) => i.id === id)
    return item?.reportType === PressureReportType.MAIN
  })

  if (hasMain) {
    uni.showToast({ title: '主报告不能作废', icon: 'error' })
    return
  }

  const hasReportEnd =
    props.useOnline === '1' &&
    selectedProjects.value.some((id) => {
      const item = props.reportList.find((i) => i.id === id)
      return item?.taskStatus >= PressureCheckerMyTaskStatus.RECORD_CHECK
    })

  if (hasReportEnd) {
    uni.showToast({ title: '已提交校核的项目不能作废', icon: 'error' })
    return
  }

  tipsPopupRef.value?.show({
    text: '是否作废已选择的检验项目？',
    showInput: true,
    inputPlaceholder: '请输入作废理由',
    confirm: async (reason?: string) => {
      try {
        uni.showLoading({ title: '作废中...' })

        const cancelIds = selectedProjects.value
        let result = null

        if (props.useOnline === '1') {
          const cancelReq = []
          cancelIds.forEach((id) => {
            cancelReq.push({ id, reason: reason || '' })
          })
          const fetchResult = await cancelBoilerInSpectProject(cancelReq)
          result = fetchResult.data
        } else {
          uni.showToast({ title: '离线模式作废功能开发中', icon: 'none' })
          uni.hideLoading()
          return
        }

        uni.hideLoading()

        if (result) {
          props.refreshDetail?.()
          initSelected()
          uni.showToast({ title: '作废成功', icon: 'success' })
        } else {
          uni.showToast({ title: '作废失败', icon: 'error' })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('作废失败:', error)
        uni.showToast({ title: '作废失败', icon: 'error' })
      }
    },
  })
}

const uploadFileAndSubmitCheckItemCallback = {
  callback: async (item: CheckItem) => {
    const userId =
      item.reportType === PressureReportType.MAIN
        ? props.equipment?.mainCheckerUser?.id
        : item?.checkUsers?.[0]?.id

    if (userId && userId !== userInfo.value?.id) {
      uni.showToast({ title: '已分配项目不支持上传', icon: 'error' })
      return
    }

    try {
      uni.showLoading({ title: '上传中...' })

      const params = {
        orderId: props.orderId,
        orderItemId: props.orderItemId,
        reportUrl: item.reportUrl || '',
        dataJson: '',
        prepareUrl: '',
        prepareJson: item.prepareJson || '',
        modifiedReason: '',
        templateId: item.templateId,
        reportType: item.reportType,
        fee: item?.fee || 0,
      }

      const newParams: any = {}
      if (item.isLocal) {
        params.localId = item.id
        newParams.addList = [params]
      } else {
        params.id = item.id
        newParams.updateList = [params]
      }

      const { postCheckItemRecordEnter } = await import('@/api/task')
      const postResult = await postCheckItemRecordEnter(newParams)

      uni.hideLoading()

      if (postResult.data) {
        uni.showToast({ title: '提交成功', icon: 'success' })
        props.refreshDetail?.()
      } else {
        uni.showToast({ title: postResult?.msg || '提交失败', icon: 'error' })
      }
    } catch (error) {
      uni.hideLoading()
      console.error('上传失败:', error)
      uni.showToast({ title: '上传失败', icon: 'error' })
    }
  },
}
</script>

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

.scroll-list {
  flex: 1;
  padding: 12px;
  padding-bottom: 80px;
}

.report-list {
  display: flex;
  flex-direction: column;
}

.report-item {
  padding: 15px;
  margin-bottom: 12px;
  background-color: #fff;
  border-radius: 5px;
}

.part-card {
  display: flex;
  flex-flow: column nowrap;
  margin: 0 0 12px 0;
  background-color: rgb(245, 245, 245);
  border-color: gray;
  border-style: solid;
  border-width: 0px;
  border-radius: 8px;

  .part-card-header {
    display: flex;
    flex-flow: row nowrap;
    align-items: center;
    justify-content: space-between;
    height: 30px;
    font-size: 16px;
    font-weight: 500;
    background-color: white;
    border-color: gray;
    border-style: solid;
    border-width: 0 0 1px 0;

    .part-card-header-text {
      margin: 8px;
    }

    .part-card-header-btn-group {
      display: flex;
      flex-flow: row nowrap;
      justify-content: flex-end;

      view {
        margin: 4px;
        color: rgb(47, 142, 255);
      }
    }
  }

  .report-item {
    padding: 12px 4%;
    margin: 0 0 8px 0;
  }
}

.item-top {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 10px;
  border-bottom: 1px solid rgb(244, 244, 244);
}

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

.report-name {
  margin-left: 8px;
  font-size: 15px;
  color: rgb(51, 51, 51);
}

.type-tag {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  margin-left: 10px;
  border-radius: 4px;
}

.type-tag-text {
  font-size: 12px;
  color: rgb(252, 255, 253);
}

.status-text {
  font-size: 15px;
}

.item-center {
  margin-top: 10px;
}

.center-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 10px;
}

.label {
  width: 80px;
  font-size: 15px;
  color: rgb(51, 51, 51);
}

.conclusion-box {
  min-width: 80px;
  padding: 10px;
  background-color: rgb(243, 245, 247);
  border: 1px solid rgb(187, 187, 187);
  border-radius: 4px;
}

.conclusion-error {
  background-color: #fff2f2;
  border-color: #ff3535;
}

.conclusion-text {
  font-size: 13px;
  color: #4b8cd9;
}

.conclusion-error-text {
  color: #ff3535;
}

.result-box {
  flex: 1;
  padding: 10px;
  background-color: rgb(243, 245, 247);
  border: 1px solid rgb(187, 187, 187);
  border-radius: 4px;
}

.result-text {
  font-size: 13px;
}

.right-area {
  display: flex;
  flex: 1;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: center;
  justify-content: flex-end;
}

.instruction-tag {
  padding: 4px 8px;
  margin-right: 8px;
  background-color: #f2f6ff;
  border: 1px solid #4b8cd9;
  border-radius: 4px;
}

.instruction-tag-error {
  background-color: #fff2f2;
  border-color: #ff3535;
}

.instruction-text {
  font-size: 12px;
  color: #4b8cd9;
}

.instruction-text-error {
  color: #ff3535;
}

.inspector-name {
  font-size: 15px;
  color: rgb(51, 51, 51);
}

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

.inspector-label {
  font-size: 15px;
  color: rgb(51, 51, 51);
}

.inspector-value {
  font-size: 15px;
  color: rgb(75, 140, 217);
}

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

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

.fee-value-box {
  padding: 4px 8px;
  margin-right: 3px;
  background-color: #f3f5f7;
  border: 1px solid rgb(182, 216, 236);
  border-radius: 4px;
}

.fee-value {
  font-size: 12px;
  color: rgb(75, 140, 217);
}

.fee-none {
  font-size: 12px;
  color: rgb(75, 140, 217);
}

.fee-btn {
  padding: 4px 8px;
  background-color: rgb(47, 142, 255);
  border: 1px solid rgb(47, 142, 255);
  border-radius: 4px;
}

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

.action-btns {
  display: flex;
  flex: 1;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: flex-end;
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 29px;
  padding: 0 5px;
  margin-left: 3px;
  background-color: #f3f5f7;
  border: 1px solid rgb(182, 216, 236);
  border-radius: 4px;
}

.action-btn-text {
  font-size: 12px;
  color: rgb(75, 140, 217);
}

.sign-btn {
  background-color: rgba(78, 185, 95, 1);
  border-color: rgba(78, 185, 95, 1);
}

.sign-btn .action-btn-text {
  color: rgb(222, 238, 255);
}

.attachment-btn {
  background-color: rgb(230, 162, 60);
  border-color: rgb(230, 162, 60);
}

.attachment-btn .action-btn-text {
  color: rgb(222, 238, 255);
}

.record-btn,
.re-input-btn {
  background-color: #f3f5f7;
}

.submit-check-btn,
.submit-report-btn {
  margin-right: 0;
  background-color: rgb(47, 142, 255);
  border-color: rgb(47, 142, 255);
}

.submit-check-btn .action-btn-text,
.submit-report-btn .action-btn-text {
  color: rgb(222, 238, 255);
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}

.empty-text {
  font-size: 14px;
  color: #999;
}

.bottom-bar {
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 100;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  height: 68px;
  padding: 0 12px;
  background-color: #fff;
  border-top: 1px solid rgb(244, 244, 244);
}

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

.square-checkbox {
  border-radius: 0 !important;
  transform: scale(0.9);
}

.select-all-text {
  margin-left: 10px;
  font-size: 15px;
  line-height: 1.4;
  color: rgb(51, 51, 51);
  white-space: pre-line;
}

.action-buttons {
  display: flex;
  flex: 2;
  flex-direction: row;
  align-items: center;
  justify-content: flex-end;
}

.operate-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 66px;
  height: 40px;
  padding: 0 5px;
  margin-left: 5px;
  border-radius: 4px;
}

.operate-btn-text {
  font-size: 14px;
  color: rgb(251, 253, 255);
}

.delete-btn {
  background-color: #ff4445;
}

.guide-btn {
  background-color: #e6a23c;
}

.part-btn {
  background-color: #e6a23c;
}

.add-btn {
  background-color: #e6a23c;
}

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

.popup-overlay {
  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: 300px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
}

.popup-title {
  display: block;
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: bold;
  color: #333;
  text-align: center;
}

.picker-value {
  padding: 10px;
  margin-bottom: 20px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.popup-actions {
  display: flex;
  justify-content: space-between;
}

.popup-actions .action-btn {
  flex: 1;
  padding: 10px 0;
  margin: 0 5px;
  font-size: 14px;
  text-align: center;
  border-radius: 4px;
}

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

.popup-actions .confirm-btn {
  color: #fff;
  background-color: #007aff;
}
</style>
