<!--案件流转管理-->
<template>
  <div class="min-h-screen bg-[#f0f2f6] p-5">
    <div class="mb-5 rounded-[20px] bg-white px-6 py-4">
      <div class="flex flex-wrap gap-6">
        <div class="min-w-[120px] cursor-pointer rounded-2xl px-4 py-2 text-center" :class="{ 'bg-[#ecf5ff]': statusFilter === '' }" @click="filterStatus('')">
          <div class="text-[26px] font-bold">{{ totalCases }}</div>
          <div>全部案件</div>
        </div>
        <div class="min-w-[120px] cursor-pointer rounded-2xl px-4 py-2 text-center" :class="{ 'bg-[#ecf5ff]': statusFilter === 'pending' }" @click="filterStatus('pending')">
          <div class="text-[26px] font-bold text-[#e6a23c]">{{ pendingCount }}</div>
          <div>待核查</div>
        </div>
        <div class="min-w-[120px] cursor-pointer rounded-2xl px-4 py-2 text-center" :class="{ 'bg-[#ecf5ff]': statusFilter === 'processing' }" @click="filterStatus('processing')">
          <div class="text-[26px] font-bold">{{ processingCount }}</div>
          <div>办理中</div>
        </div>
        <div class="min-w-[120px] cursor-pointer rounded-2xl px-4 py-2 text-center" :class="{ 'bg-[#ecf5ff]': statusFilter === 'completed' }" @click="filterStatus('completed')">
          <div class="text-[26px] font-bold">{{ completedCount }}</div>
          <div>已办结</div>
        </div>
      </div>
    </div>

    <div class="flex gap-5">
      <div class="w-[380px] flex flex-col overflow-hidden rounded-[20px] bg-white" v-loading="loading">
        <div class="flex items-center justify-between gap-3 border-b border-[#e9ecef] px-4 py-4 font-600">
          <span>案件列表</span>
          <div class="flex items-center gap-2">
            <el-input
              v-model="searchCaseNo"
              placeholder="案件编号"
              :prefix-icon="Search"
              clearable
              size="small"
              class="w-[140px]"
              @keyup.enter="loadCases"
            />
            <el-input
              v-model="searchEquipmentLocation"
              placeholder="设备位置描述"
              :prefix-icon="Location"
              clearable
              size="small"
              class="w-[140px]"
              @keyup.enter="loadCases"
            />
          </div>
        </div>
        <div class="flex-1 overflow-y-auto p-3">
          <div
            v-for="caseItem in paginatedCases"
            :key="caseItem.caseId"
            class="mb-2 flex cursor-pointer items-center gap-3 rounded-[14px] border border-transparent bg-[#fafbfc] p-3"
            :class="{ 'border-[#409eff] bg-[#ecf5ff]': selectedCase?.caseId === caseItem.caseId }"
            @click="selectCase(caseItem)"
          >
            <div class="case-level">
              <el-tag :type="caseItem.levelTag" size="small">{{ caseItem.levelText }}</el-tag>
            </div>
            <div class="flex-1">
              <div class="mb-1 font-600">{{ caseItem.caseNo }}</div>
              <div class="flex items-center gap-1 text-[12px] text-[#6c757d]"><el-icon><Location /></el-icon> 设备编号 {{ caseItem.deviceCode || '—' }}</div>
              <div class="text-[11px] text-[#aaa]">{{ caseItem.createTimeText }}</div>
            </div>
            <div class="case-status">
              <el-tag :type="caseItem.statusTag" size="small">{{ caseItem.statusText }}</el-tag>
            </div>
          </div>
          <el-empty v-if="!paginatedCases.length" description="暂无案件数据" :image-size="80" />
        </div>
        <div class="border-t border-[#eee] p-3 text-center">
          <el-pagination small layout="prev, pager, next" :total="filteredCases.length" :page-size="pageSize" v-model:current-page="currentPage" />
        </div>
      </div>

      <div class="max-h-[calc(100vh-140px)] flex-1 overflow-y-auto rounded-[20px] bg-white p-5" v-if="selectedCase" v-loading="detailLoading">
        <div class="mb-5 flex gap-5">
          <div class="flex-1">
            <div class="mb-[14px] flex items-center gap-2 text-[16px] font-600">
              <span><el-icon><InfoFilled /></el-icon> 案件信息</span>
            </div>
            <el-descriptions :column="1" border>
              <el-descriptions-item label="案件编号">{{ selectedCase.caseNo }}</el-descriptions-item>
              <el-descriptions-item label="案件等级">
                <el-tag :type="selectedCase.levelTag">{{ selectedCase.levelText }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="案件来源">{{ selectedCase.sourceText }}</el-descriptions-item>
              <el-descriptions-item label="案件描述">{{ selectedCase.caseDesc || '—' }}</el-descriptions-item>
              <el-descriptions-item label="案件状态">{{ selectedCase.statusText }}</el-descriptions-item>
              <el-descriptions-item label="立案时间">{{ selectedCase.createTimeText }}</el-descriptions-item>
              <el-descriptions-item label="核查时间">{{ selectedCase.verifyTimeText }}</el-descriptions-item>
              <el-descriptions-item label="办结时间">{{ selectedCase.finishTimeText }}</el-descriptions-item>
              <el-descriptions-item label="处置结果">{{ selectedCase.handleResult || '—' }}</el-descriptions-item>
            </el-descriptions>
          </div>
          <div class="flex-1">
            <div class="mb-[14px] flex items-center gap-2 text-[16px] font-600"><el-icon><Monitor /></el-icon> 设备信息</div>
            <el-descriptions :column="1" border>
              <el-descriptions-item label="设备编号">{{ selectedCase.deviceCode || '—' }}</el-descriptions-item>
              <el-descriptions-item label="设备类别">{{ selectedCase.equipmentTypeName || '—' }}</el-descriptions-item>
              <el-descriptions-item label="运维状态">{{ selectedCase.currentStatusText }}</el-descriptions-item>
              <el-descriptions-item label="在线状态">{{ selectedCase.onlineStatusText }}</el-descriptions-item>
              <el-descriptions-item label="报警状态">{{ selectedCase.alarmStatusText }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </div>

        <div class="mt-6 border-t border-[#e9ecef] pt-4">
          <div class="mb-[14px] flex items-center gap-2 text-[16px] font-600"><el-icon><Picture /></el-icon> 案件附件</div>
          <div class="flex flex-wrap gap-3" v-if="selectedCase.attachImages.length">
            <el-image
              v-for="(img, idx) in selectedCase.attachImages"
              :key="idx"
              :src="img"
              fit="cover"
              class="h-[80px] w-[100px] cursor-pointer rounded-lg object-cover"
              :preview-src-list="selectedCase.attachImages"
              preview-teleported
            />
          </div>
          <el-empty v-else description="暂无案件附件" :image-size="80" />
        </div>
      </div>

      <div v-else class="flex flex-1 items-center justify-center rounded-[20px] bg-white">
        <el-empty description="请从左侧选择案件进行核查" :image-size="140" />
      </div>
    </div>
  </div>
</template>

<script setup>
import {computed, onMounted, ref} from 'vue'
import {InfoFilled, Location, Monitor, Picture, Search} from '@element-plus/icons-vue'
import {getManholeCaseDetail, getManholeCasePage} from '@/api/pipeNetwork/basic'

const cases = ref([])
const loading = ref(false)
const detailLoading = ref(false)
const searchCaseNo = ref('')
const searchEquipmentLocation = ref('')
const statusFilter = ref('')
const currentPage = ref(1)
const pageSize = 5
const selectedCase = ref(null)

function formatDateTime(value) {
  if (!value) return '—'
  return String(value).replace('T', ' ')
}

function getCaseLevelMeta(level) {
  const map = {
    1: { text: '严重', tag: 'danger' },
    2: { text: '一般', tag: 'warning' },
    3: { text: '轻微', tag: 'info' }
  }
  return map[Number(level)] || { text: '—', tag: 'info' }
}

function getCaseStatusMeta(status) {
  const map = {
    1: { key: 'pending', text: '待核查', tag: 'danger' },
    2: { key: 'processing', text: '办理中', tag: 'warning' },
    3: { key: 'completed', text: '已办结', tag: 'success' },
    4: { key: 'closed', text: '误报关闭', tag: 'info' }
  }
  return map[Number(status)] || { key: '', text: '—', tag: 'info' }
}

function getCaseSourceText(source) {
  const map = {
    1: '系统自动报警',
    2: '运维巡检上报',
    3: '人工投诉上报',
    4: '平台录入'
  }
  return map[Number(source)] || '—'
}

function splitAttachUrls(value) {
  if (!value) return []
  return String(value)
    .split(/[,\n;]/)
    .map(item => item.trim())
    .filter(Boolean)
}

function getOnlineStatusText(status) {
  const map = {
    0: '离线',
    1: '在线'
  }
  return map[Number(status)] || '—'
}

function getAlarmStatusText(status) {
  const map = {
    0: '正常',
    1: '报警'
  }
  return map[Number(status)] || '—'
}

function getCurrentStatusText(status) {
  const map = {
    1: '在用',
    2: '闲置',
    3: '维修',
    4: '报废',
    5: '待入库'
  }
  return map[Number(status)] || '—'
}

function normalizeCase(item) {
  const levelMeta = getCaseLevelMeta(item.caseLevel)
  const statusMeta = getCaseStatusMeta(item.caseStatus)
  return {
    ...item,
    levelText: levelMeta.text,
    levelTag: levelMeta.tag,
    statusKey: statusMeta.key,
    statusText: statusMeta.text,
    statusTag: statusMeta.tag,
    sourceText: getCaseSourceText(item.caseSource),
    createTimeText: formatDateTime(item.createTime),
    verifyTimeText: formatDateTime(item.verifyTime),
    finishTimeText: formatDateTime(item.finishTime),
    updateTimeText: formatDateTime(item.updateTime),
    attachImages: splitAttachUrls(item.attachUrl),
    currentStatusText: getCurrentStatusText(item.equipmentStatus?.currentStatus),
    onlineStatusText: getOnlineStatusText(item.equipmentStatus?.onlineStatus),
    alarmStatusText: getAlarmStatusText(item.equipmentStatus?.alarmStatus),
    statusUpdateTimeText: formatDateTime(item.equipmentStatus?.statusUpdateTime)
  }
}

const filteredCases = computed(() => {
  if (!statusFilter.value) return cases.value
  return cases.value.filter(item => item.statusKey === statusFilter.value)
})

const paginatedCases = computed(() => {
  const start = (currentPage.value - 1) * pageSize
  return filteredCases.value.slice(start, start + pageSize)
})

const totalCases = computed(() => cases.value.length)
const pendingCount = computed(() => cases.value.filter(item => item.statusKey === 'pending').length)
const processingCount = computed(() => cases.value.filter(item => item.statusKey === 'processing').length)
const completedCount = computed(() => cases.value.filter(item => item.statusKey === 'completed').length)

async function loadCases() {
  loading.value = true
  try {
    const caseNo = searchCaseNo.value.trim()
    const equipmentLocation = searchEquipmentLocation.value.trim()
    const res = await getManholeCasePage({
      pageNum: 1,
      pageSize: 200,
      caseNo: caseNo || undefined,
      equipmentLocation: equipmentLocation || undefined
    })
    const records = Array.isArray(res?.data?.records) ? res.data.records : []
    cases.value = records.map(item => normalizeCase(item))
    currentPage.value = 1
    const first = filteredCases.value[0]
    if (!first) {
      selectedCase.value = null
      return
    }
    if (selectedCase.value) {
      const matched = cases.value.find(item => item.caseId === selectedCase.value.caseId)
      if (matched) {
        await selectCase(matched)
        return
      }
    }
    await selectCase(first)
  } catch (error) {
    cases.value = []
    selectedCase.value = null
  } finally {
    loading.value = false
  }
}

async function selectCase(caseItem) {
  detailLoading.value = true
  try {
    const res = await getManholeCaseDetail(caseItem.caseId)
    const detail = res?.data || caseItem
    selectedCase.value = normalizeCase(detail)
  } catch (error) {
    selectedCase.value = caseItem
  } finally {
    detailLoading.value = false
  }
}

function filterStatus(status) {
  statusFilter.value = status
  currentPage.value = 1
  const first = filteredCases.value[0]
  if (first) {
    selectCase(first)
  } else {
    selectedCase.value = null
  }
}

onMounted(() => {
  loadCases()
})
</script>
