<!--办结工单-->
<template>
  <div class="min-h-screen bg-[#f0f2f6] p-5">
    <div class="mb-5 flex flex-wrap items-center justify-between gap-3 rounded-2xl bg-white px-6 py-4 shadow-[0_2px_8px_rgba(0,0,0,0.04)]">
      <div class="flex items-center gap-3">
        <el-icon><CircleCheck /></el-icon>
        <span class="text-[20px] font-600 text-[#1f2d3d]">已办结工单</span>
        <el-tag type="success" effect="dark">已完成 {{ completedOrdersCount }}</el-tag>
      </div>
      <div class="flex flex-wrap items-center gap-3">
        <el-input
          v-model="searchOrderNo"
          placeholder="工单编号"
          clearable
          :prefix-icon="Search"
          class="w-[140px]"
          @keyup.enter="loadOrders"
        />
        <el-input
          v-model="searchCaseNo"
          placeholder="案件编号"
          clearable
          :prefix-icon="Search"
          class="w-[140px]"
          @keyup.enter="loadOrders"
        />
        <el-select v-model="orderLevelFilter" placeholder="优先级" clearable class="w-[120px]">
          <el-option label="紧急" :value="1" />
          <el-option label="一般" :value="2" />
          <el-option label="低" :value="3" />
        </el-select>
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="办结开始"
          end-placeholder="办结结束"
          value-format="YYYY-MM-DD"
          class="w-[280px]"
        />
        <el-button type="primary" :icon="Refresh" @click="loadOrders">刷新</el-button>
      </div>
    </div>

    <div class="mb-5 flex flex-wrap gap-4">
      <div
        class="min-w-[110px] cursor-pointer rounded-xl bg-white px-6 py-3 text-center shadow-[0_1px_4px_rgba(0,0,0,0.05)] transition-all duration-200 hover:-translate-y-[2px] hover:shadow-[0_4px_12px_rgba(0,0,0,0.1)]"
        :class="timeFilter === 'week' ? 'border-2 border-[#67c23a] bg-[#f0f9f0]' : 'border-2 border-transparent'"
        @click="setTimeFilter('week')"
      >
        <div class="text-[28px] font-bold text-[#2c3e50]">{{ weeklyCompleted }}</div>
        <div class="mt-1 text-[13px] text-[#606266]">本周办结</div>
      </div>
      <div
        class="min-w-[110px] cursor-pointer rounded-xl bg-white px-6 py-3 text-center shadow-[0_1px_4px_rgba(0,0,0,0.05)] transition-all duration-200 hover:-translate-y-[2px] hover:shadow-[0_4px_12px_rgba(0,0,0,0.1)]"
        :class="timeFilter === 'month' ? 'border-2 border-[#67c23a] bg-[#f0f9f0]' : 'border-2 border-transparent'"
        @click="setTimeFilter('month')"
      >
        <div class="text-[28px] font-bold text-[#2c3e50]">{{ monthlyCompleted }}</div>
        <div class="mt-1 text-[13px] text-[#606266]">本月办结</div>
      </div>
      <div
        class="min-w-[110px] cursor-pointer rounded-xl bg-white px-6 py-3 text-center shadow-[0_1px_4px_rgba(0,0,0,0.05)] transition-all duration-200 hover:-translate-y-[2px] hover:shadow-[0_4px_12px_rgba(0,0,0,0.1)]"
        :class="timeFilter === 'all' ? 'border-2 border-[#67c23a] bg-[#f0f9f0]' : 'border-2 border-transparent'"
        @click="setTimeFilter('all')"
      >
        <div class="text-[28px] font-bold text-[#2c3e50]">{{ completedOrdersCount }}</div>
        <div class="mt-1 text-[13px] text-[#606266]">全部办结</div>
      </div>
    </div>

    <div class="rounded-2xl bg-white p-4 shadow-[0_2px_8px_rgba(0,0,0,0.04)]">
      <el-table :data="paginatedOrders" stripe border class="w-full" row-class-name="cursor-pointer" v-loading="loading" @row-click="handleRowClick">
        <el-table-column type="index" label="序号" width="55" align="center" />
        <el-table-column prop="orderNo" label="工单编号" min-width="170" />
        <el-table-column prop="caseNo" label="关联案件编号" min-width="170" />
        <el-table-column prop="orderLevelText" label="优先级" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.orderLevelTag" size="small">{{ row.orderLevelText }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="orderTypeText" label="工单类型" width="110" />
        <el-table-column prop="orderDesc" label="问题描述" min-width="220" show-overflow-tooltip />
        <el-table-column prop="deviceCode" label="设备编号" width="150" />
        <el-table-column prop="realFinishTimeText" label="办结时间" width="170" />
        <el-table-column label="操作" width="120" fixed="right" align="center">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click.stop="viewDetail(row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="mt-4 flex justify-end border-t border-[#e9ecef] pt-3">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredOrders.length"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
        />
      </div>
    </div>

    <el-drawer v-model="detailDrawerVisible" :title="`工单详情 - ${currentOrder?.orderNo || ''}`" size="560px" direction="rtl">
      <div v-if="currentOrder" class="p-2" v-loading="detailLoading">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="工单编号">{{ currentOrder.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="关联案件编号">{{ currentOrder.caseNo || '—' }}</el-descriptions-item>
          <el-descriptions-item label="设备编号">{{ currentOrder.deviceCode || '—' }}</el-descriptions-item>
          <el-descriptions-item label="工单状态">
            <el-tag :type="currentOrder.orderStatusTag">{{ currentOrder.orderStatusText }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="优先级">
            <el-tag :type="currentOrder.orderLevelTag">{{ currentOrder.orderLevelText }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="工单类型">{{ currentOrder.orderTypeText }}</el-descriptions-item>
          <el-descriptions-item label="问题描述">{{ currentOrder.orderDesc || '—' }}</el-descriptions-item>
          <el-descriptions-item label="设备类别">{{ currentOrder.equipmentTypeName || '—' }}</el-descriptions-item>
          <el-descriptions-item label="派单时间">{{ currentOrder.dispatchTimeText }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentOrder.createTimeText }}</el-descriptions-item>
          <el-descriptions-item label="计划完成时间">{{ currentOrder.planFinishTimeText }}</el-descriptions-item>
          <el-descriptions-item label="延期原因">{{ currentOrder.delayedReason || '—' }}</el-descriptions-item>
          <el-descriptions-item label="延期截止时间">{{ currentOrder.delayedDeadlineText }}</el-descriptions-item>
          <el-descriptions-item label="验收时间">{{ currentOrder.verifyTimeText }}</el-descriptions-item>
          <el-descriptions-item label="办结时间">{{ currentOrder.realFinishTimeText }}</el-descriptions-item>
          <el-descriptions-item label="处置结果">{{ currentOrder.repairResult || '—' }}</el-descriptions-item>
          <el-descriptions-item label="设备运维状态">{{ currentOrder.currentStatusText }}</el-descriptions-item>
          <el-descriptions-item label="设备在线状态">{{ currentOrder.onlineStatusText }}</el-descriptions-item>
          <el-descriptions-item label="设备报警状态">{{ currentOrder.alarmStatusText }}</el-descriptions-item>
        </el-descriptions>

        <div class="mt-4">
          <div class="mb-3 mt-5 text-[15px] font-600 text-[#2c3e50]">办理经过</div>
          <el-timeline v-if="currentOrder.workOrderLogList?.length">
            <el-timeline-item
              v-for="log in currentOrder.workOrderLogList"
              :key="log.logId"
              :timestamp="formatDateTime(log.operTime)"
              :type="getLogType(log.operType)"
            >
              {{ log.operDesc }}
              <span v-if="log.operUserName" class="ml-3 text-[12px] text-[#909399]">操作人: {{ log.operUserName }}</span>
            </el-timeline-item>
          </el-timeline>
          <el-empty v-else description="暂无办理日志" :image-size="80" />
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import {computed, onMounted, ref} from 'vue'
import {CircleCheck, Refresh, Search} from '@element-plus/icons-vue'
import {ElMessage} from 'element-plus'
import {getManholeWorkOrderDetail, getManholeWorkOrderFinishedPage} from '@/api/pipeNetwork/basic'

const orders = ref([])
const loading = ref(false)
const detailLoading = ref(false)
const searchOrderNo = ref('')
const searchCaseNo = ref('')
const orderLevelFilter = ref('')
const dateRange = ref([])
const timeFilter = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)
const detailDrawerVisible = ref(false)
const currentOrder = ref(null)

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

function getOrderLevelMeta(level) {
  const map = {
    1: { text: '紧急', tag: 'danger' },
    2: { text: '一般', tag: 'warning' },
    3: { text: '低', tag: 'info' }
  }
  return map[Number(level)] || { text: '—', tag: 'info' }
}

function getOrderTypeText(type) {
  const map = {
    1: '故障维修',
    2: '日常巡检',
    3: '设备保养'
  }
  return map[Number(type)] || '—'
}

function getOrderStatusMeta(status) {
  const map = {
    6: { text: '已结案', tag: 'success' },
    7: { text: '已驳回', tag: 'danger' },
    9: { text: '延期待接单', tag: 'warning' }
  }
  return map[Number(status)] || { text: '—', tag: 'info' }
}

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 normalizeOrder(item) {
  const levelMeta = getOrderLevelMeta(item.orderLevel)
  const statusMeta = getOrderStatusMeta(item.orderStatus)
  return {
    ...item,
    orderLevelText: levelMeta.text,
    orderLevelTag: levelMeta.tag,
    orderTypeText: getOrderTypeText(item.orderType),
    orderStatusText: statusMeta.text,
    orderStatusTag: statusMeta.tag,
    createTimeText: formatDateTime(item.createTime),
    dispatchTimeText: formatDateTime(item.dispatchTime),
    planFinishTimeText: formatDateTime(item.planFinishTime),
    delayedDeadlineText: formatDateTime(item.delayedDeadline),
    verifyTimeText: formatDateTime(item.verifyTime),
    realFinishTimeText: formatDateTime(item.realFinishTime),
    updateTimeText: formatDateTime(item.updateTime),
    currentStatusText: getCurrentStatusText(item.equipmentStatus?.currentStatus),
    onlineStatusText: getOnlineStatusText(item.equipmentStatus?.onlineStatus),
    alarmStatusText: getAlarmStatusText(item.equipmentStatus?.alarmStatus),
    statusUpdateTimeText: formatDateTime(item.equipmentStatus?.statusUpdateTime)
  }
}

function isWithinRecentDays(value, days) {
  if (!value) return false
  const time = new Date(value).getTime()
  if (Number.isNaN(time)) return false
  return Date.now() - time <= days * 24 * 3600000
}

const filteredOrders = computed(() => {
  if (timeFilter.value === 'week') {
    return orders.value.filter(item => isWithinRecentDays(item.realFinishTime, 7))
  }
  if (timeFilter.value === 'month') {
    return orders.value.filter(item => isWithinRecentDays(item.realFinishTime, 30))
  }
  return orders.value
})

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

const completedOrdersCount = computed(() => orders.value.length)
const weeklyCompleted = computed(() => orders.value.filter(item => isWithinRecentDays(item.realFinishTime, 7)).length)
const monthlyCompleted = computed(() => orders.value.filter(item => isWithinRecentDays(item.realFinishTime, 30)).length)

async function loadOrders() {
  loading.value = true
  try {
    const orderNo = searchOrderNo.value.trim()
    const caseNo = searchCaseNo.value.trim()
    const payload = {
      pageNum: 1,
      pageSize: 200,
      orderLevel: orderLevelFilter.value || undefined,
      orderNo: orderNo || undefined,
      caseNo: caseNo || undefined,
      startTime: dateRange.value?.[0] ? `${dateRange.value[0]} 00:00:00` : undefined,
      endTime: dateRange.value?.[1] ? `${dateRange.value[1]} 23:59:59` : undefined
    }
    const res = await getManholeWorkOrderFinishedPage(payload)
    const records = Array.isArray(res?.data?.records) ? res.data.records : []
    orders.value = records
      .filter(item => [6, 7].includes(Number(item.orderStatus)))
      .map(normalizeOrder)
    currentPage.value = 1
    if (currentOrder.value) {
      const matched = orders.value.find(item => item.orderId === currentOrder.value.orderId)
      if (matched) {
        await viewDetail(matched)
      } else {
        currentOrder.value = null
        detailDrawerVisible.value = false
      }
    }
  } catch (error) {
    orders.value = []
    currentOrder.value = null
    ElMessage.error('办结工单加载失败')
  } finally {
    loading.value = false
  }
}

async function viewDetail(order) {
  detailLoading.value = true
  detailDrawerVisible.value = true
  try {
    const res = await getManholeWorkOrderDetail(order.orderId)
    currentOrder.value = normalizeOrder(res?.data || order)
  } catch (error) {
    currentOrder.value = order
    ElMessage.error('工单详情加载失败')
  } finally {
    detailLoading.value = false
  }
}

function handleRowClick(row) {
  viewDetail(row)
}

function setTimeFilter(filter) {
  timeFilter.value = filter
  currentPage.value = 1
}

function getLogType(operType) {
  const map = {
    2: 'primary',
    3: 'warning',
    4: 'primary',
    5: 'warning',
    6: 'success',
    7: 'danger',
    8: 'warning',
    9: 'warning'
  }
  return map[Number(operType)] || 'info'
}

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