<!--经办工单-->
<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><List /></el-icon>
        <span class="text-[20px] font-600 text-[#1f2d3d]">经办工单</span>
        <el-tag type="danger" effect="dark" v-if="pendingOrdersCount > 0">待处理 {{ pendingOrdersCount }}</el-tag>
      </div>
      <div class="flex flex-wrap items-center gap-3">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索工单编号/案件编号"
          clearable
          :prefix-icon="Search"
          class="w-[260px]"
          @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-button type="primary" :icon="Refresh" @click="loadOrders">刷新</el-button>
      </div>
    </div>

    <div class="mb-5 flex flex-wrap gap-4">
      <div
        class="min-w-[100px] 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="statusFilter === '' ? 'border-2 border-[#409eff] bg-[#ecf5ff]' : 'border-2 border-transparent'"
        @click="setStatusFilter('')"
      >
        <div class="text-[28px] font-bold">{{ totalOrders }}</div>
        <div class="mt-1 text-[13px] text-[#606266]">全部工单</div>
      </div>
      <div
        class="min-w-[100px] 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="statusFilter === 'pending' ? 'border-2 border-[#409eff] bg-[#ecf5ff]' : 'border-2 border-transparent'"
        @click="setStatusFilter('pending')"
      >
        <div class="text-[28px] font-bold text-[#f56c6c]">{{ pendingOrdersCount }}</div>
        <div class="mt-1 text-[13px] text-[#606266]">待处理</div>
      </div>
      <div
        class="min-w-[100px] 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="statusFilter === 'processing' ? 'border-2 border-[#409eff] bg-[#ecf5ff]' : 'border-2 border-transparent'"
        @click="setStatusFilter('processing')"
      >
        <div class="text-[28px] font-bold text-[#e6a23c]">{{ processingOrdersCount }}</div>
        <div class="mt-1 text-[13px] text-[#606266]">处理中</div>
      </div>
      <div
        class="min-w-[100px] 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="statusFilter === 'overdue' ? 'border-2 border-[#409eff] bg-[#ecf5ff]' : 'border-2 border-transparent'"
        @click="setStatusFilter('overdue')"
      >
        <div class="text-[28px] font-bold text-[#f56c6c]">{{ overdueCount }}</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="orderStatusText" label="工单状态" width="110" align="center">
          <template #default="{ row }">
            <el-tag :type="row.orderStatusTag" size="small">{{ row.orderStatusText }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTimeText" label="创建时间" width="170" />
        <el-table-column prop="planFinishTimeText" label="计划完成时间" width="170" />
        <el-table-column label="操作" width="150" fixed="right" align="center">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click.stop="viewDetail(row)">查看详情</el-button>
            <el-button v-if="canAcceptOrder(row)" link type="warning" size="small" @click.stop="acceptOrder(row)">接单</el-button>
            <el-button v-else-if="canStartRepair(row)" link type="success" size="small" @click.stop="startRepair(row)">开始维修</el-button>
            <el-button v-else-if="canSubmitVerify(row)" link type="warning" size="small" @click.stop="submitVerify(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="540px" 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-4 text-[14px] 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 class="mt-6 flex justify-end gap-3">
          <el-button v-if="canAcceptOrder(currentOrder)" type="warning" @click="acceptOrder(currentOrder)">接单</el-button>
          <el-button v-if="canStartRepair(currentOrder)" type="primary" @click="startRepair(currentOrder)">开始维修</el-button>
          <el-button v-if="canSubmitVerify(currentOrder)" type="success" @click="submitVerify(currentOrder)">提交验收</el-button>
          <el-button
            v-if="canDelay(currentOrder)"
            type="warning"
            plain
            @click="openDelayDialog(currentOrder)"
          >
            申请延期
          </el-button>
        </div>
        <el-alert
          v-if="!hasOperationButtons(currentOrder)"
          class="mt-4"
          title="当前状态暂无可操作项"
          type="info"
          :closable="false"
          show-icon
        />
      </div>
    </el-drawer>

    <el-dialog v-model="delayDialogVisible" title="申请延期" width="420px">
      <el-form label-width="88px">
        <el-form-item label="截止时间">
          <el-date-picker
            v-model="delayDeadline"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择延期截止时间"
            class="w-full"
          />
        </el-form-item>
        <el-form-item label="延期原因">
          <el-input v-model="delayReason" type="textarea" rows="3" placeholder="请输入延期原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="delayDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitDelay">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

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

const DEFAULT_OPER_USER_ID = 1

const orders = ref([])
const loading = ref(false)
const detailLoading = ref(false)
const detailDrawerVisible = ref(false)
const delayDialogVisible = ref(false)
const currentOrder = ref(null)
const searchKeyword = ref('')
const orderLevelFilter = ref('')
const statusFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const delayDeadline = ref('')
const delayReason = ref('')

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 = {
    1: { key: 'pending', text: '待派单', tag: 'danger' },
    2: { key: 'pending', text: '待接单', tag: 'danger' },
    3: { key: 'processing', text: '已接单', tag: 'warning' },
    4: { key: 'processing', text: '处理中', tag: 'warning' },
    5: { key: 'verify', text: '待验收', tag: 'primary' },
    6: { key: 'completed', text: '已结案', tag: 'success' },
    7: { key: 'completed', text: '已驳回', tag: 'danger' },
    8: { key: 'verify', text: '延期审核', tag: 'warning' },
    9: { key: 'pending', text: '延期待接单', tag: 'warning' }
  }
  return map[Number(status)] || { key: '', 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),
    orderStatusKey: statusMeta.key,
    orderStatusText: statusMeta.text,
    orderStatusTag: statusMeta.tag,
    createTimeText: formatDateTime(item.createTime),
    dispatchTimeText: formatDateTime(item.dispatchTime),
    planFinishTimeText: formatDateTime(item.planFinishTime),
    delayedDeadlineText: formatDateTime(item.delayedDeadline),
    realFinishTimeText: formatDateTime(item.realFinishTime),
    verifyTimeText: formatDateTime(item.verifyTime),
    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 isOverdue(item) {
  if (!item.planFinishTime) return false
  return new Date(item.planFinishTime).getTime() < Date.now() && ![6, 7].includes(Number(item.orderStatus))
}

const filteredOrders = computed(() => {
  let list = orders.value
  if (statusFilter.value === 'pending') {
    list = list.filter(item => item.orderStatusKey === 'pending')
  } else if (statusFilter.value === 'processing') {
    list = list.filter(item => item.orderStatusKey === 'processing' && !isOverdue(item))
  } else if (statusFilter.value === 'overdue') {
    list = list.filter(item => isOverdue(item))
  }
  return list
})

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

const totalOrders = computed(() => orders.value.length)
const pendingOrdersCount = computed(() => orders.value.filter(item => item.orderStatusKey === 'pending').length)
const processingOrdersCount = computed(() => orders.value.filter(item => item.orderStatusKey === 'processing' && !isOverdue(item)).length)
const overdueCount = computed(() => orders.value.filter(item => isOverdue(item)).length)

async function loadOrders() {
  loading.value = true
  try {
    const keyword = searchKeyword.value.trim()
    const payload = {
      pageNum: 1,
      pageSize: 200,
      orderLevel: orderLevelFilter.value || undefined,
      orderNo: keyword || undefined,
      caseNo: keyword || undefined
    }
    const res = await getManholeWorkOrderPage(payload)
    const records = Array.isArray(res?.data?.records) ? res.data.records : []
    orders.value = records
      .filter(item => [2, 3, 4, 5, 8, 9].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 setStatusFilter(status) {
  statusFilter.value = status
  currentPage.value = 1
  if (detailDrawerVisible.value && currentOrder.value) {
    const first = filteredOrders.value[0]
    if (first) {
      viewDetail(first)
    } else {
      currentOrder.value = null
      detailDrawerVisible.value = false
    }
  }
}

function canStartRepair(order) {
  return Number(order.orderStatus) === 3
}

function canAcceptOrder(order) {
  return [2, 9].includes(Number(order.orderStatus))
}

function canSubmitVerify(order) {
  return Number(order.orderStatus) === 4
}

function canDelay(order) {
  return [3, 4].includes(Number(order.orderStatus))
}

function hasOperationButtons(order) {
  if (!order) return false
  return canAcceptOrder(order) || canStartRepair(order) || canSubmitVerify(order) || canDelay(order)
}

async function operateOrder(orderId, operType, operDesc, extra = {}) {
  await operManholeWorkOrder({
    orderId,
    operType,
    operDesc,
    operUserId: DEFAULT_OPER_USER_ID,
    ...extra
  })
  await loadOrders()
  if (currentOrder.value?.orderId === orderId) {
    const matched = orders.value.find(item => item.orderId === orderId)
    if (matched) {
      await viewDetail(matched)
    }
  }
}

async function startRepair(order) {
  try {
    await operateOrder(order.orderId, 4, '开始维修')
    ElMessage.success('已开始维修')
  } catch (error) {
    ElMessage.error(error?.message || '开始维修失败')
  }
}

async function acceptOrder(order) {
  try {
    await operateOrder(order.orderId, 3, '接单')
    ElMessage.success('已接单')
  } catch (error) {
    ElMessage.error(error?.message || '接单失败')
  }
}

async function submitVerify(order) {
  try {
    await operateOrder(order.orderId, 5, '提交验收')
    ElMessage.success('已提交验收')
  } catch (error) {
    ElMessage.error(error?.message || '提交验收失败')
  }
}

function openDelayDialog(order) {
  currentOrder.value = order
  delayDeadline.value = ''
  delayReason.value = ''
  delayDialogVisible.value = true
}

async function submitDelay() {
  if (!currentOrder.value?.orderId) return
  if (!delayDeadline.value) {
    ElMessage.warning('请选择延期截止时间')
    return
  }
  if (!delayReason.value.trim()) {
    ElMessage.warning('请输入延期原因')
    return
  }
  try {
    await operateOrder(currentOrder.value.orderId, 8, '申请延期', {
      delayedReason: delayReason.value.trim(),
      delayedDeadline: delayDeadline.value
    })
    delayDialogVisible.value = false
    ElMessage.success('延期申请已提交')
  } catch (error) {
    ElMessage.error(error?.message || '延期申请失败')
  }
}

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>
