<!--经办工单-->
<template>
  <div class="pending-orders">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-icon><List /></el-icon>
        <span class="title">待处理工单</span>
        <el-tag type="danger" effect="dark" v-if="pendingOrdersCount > 0">待处理 {{ pendingOrdersCount }}</el-tag>
      </div>
      <div class="header-right">
        <el-input
            v-model="searchKeyword"
            placeholder="搜索工单编号/案件编号/地址"
            clearable
            :prefix-icon="Search"
            style="width: 260px"
            size="default"
        />
        <el-select v-model="alertLevelFilter" placeholder="报警级别" clearable style="width: 120px" size="default">
          <el-option label="严重" value="critical" />
          <el-option label="一般" value="warning" />
        </el-select>
        <el-button type="primary" :icon="Refresh" @click="refreshList">刷新</el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card" :class="{ active: statusFilter === '' }" @click="setStatusFilter('')">
        <div class="stat-value">{{ totalOrders }}</div>
        <div class="stat-label">全部工单</div>
      </div>
      <div class="stat-card pending" :class="{ active: statusFilter === 'pending' }" @click="setStatusFilter('pending')">
        <div class="stat-value">{{ pendingOrdersCount }}</div>
        <div class="stat-label">待处理</div>
      </div>
      <div class="stat-card processing" :class="{ active: statusFilter === 'processing' }" @click="setStatusFilter('processing')">
        <div class="stat-value">{{ processingOrdersCount }}</div>
        <div class="stat-label">处理中</div>
      </div>
      <div class="stat-card overdue" :class="{ active: statusFilter === 'overdue' }" @click="setStatusFilter('overdue')">
        <div class="stat-value">{{ overdueCount }}</div>
        <div class="stat-label">已逾期</div>
      </div>
    </div>

    <!-- 工单列表 -->
    <div class="order-table-container">
      <el-table
          :data="paginatedOrders"
          stripe
          border
          style="width: 100%"
          v-loading="loading"
          @row-click="handleRowClick"
      >
        <el-table-column type="index" label="序号" width="55" align="center" />
        <el-table-column prop="code" label="工单编号" width="160" sortable />
        <el-table-column prop="caseCode" label="关联案件编号" width="160" />
        <el-table-column prop="alertLevel" label="报警级别" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.alertLevel === 'critical' ? 'danger' : 'warning'" size="small">
              {{ row.alertLevel === 'critical' ? '严重' : '一般' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="alertType" label="报警类型" width="120" />
        <el-table-column prop="alertDesc" label="报警描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="ownerUnit" label="权属单位" width="140" />
        <el-table-column prop="address" label="详细地址" min-width="180" show-overflow-tooltip />
        <el-table-column prop="status" label="工单状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" sortable />
        <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>
            <el-button
                v-if="row.status === 'pending'"
                link type="success"
                size="small"
                @click.stop="handleOrder(row)"
            >处理</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <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, 100]"
        />
      </div>
    </div>

    <!-- 工单详情抽屉 -->
    <el-drawer v-model="detailDrawerVisible" :title="`工单详情 - ${currentOrder?.code}`" size="500px" direction="rtl">
      <div v-if="currentOrder" class="order-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="工单编号">{{ currentOrder.code }}</el-descriptions-item>
          <el-descriptions-item label="关联案件">
            <el-link type="primary" @click="viewCaseDetail">{{ currentOrder.caseCode }}</el-link>
          </el-descriptions-item>
          <el-descriptions-item label="报警级别">
            <el-tag :type="currentOrder.alertLevel === 'critical' ? 'danger' : 'warning'">
              {{ currentOrder.alertLevel === 'critical' ? '严重' : '一般' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="报警类型">{{ currentOrder.alertType }}</el-descriptions-item>
          <el-descriptions-item label="报警描述">{{ currentOrder.alertDesc }}</el-descriptions-item>
          <el-descriptions-item label="权属单位">{{ currentOrder.ownerUnit }}</el-descriptions-item>
          <el-descriptions-item label="详细地址">{{ currentOrder.address }}</el-descriptions-item>
          <el-descriptions-item label="用途">{{ currentOrder.purpose || '市政排水' }}</el-descriptions-item>
          <el-descriptions-item label="工单状态">
            <el-tag :type="getStatusType(currentOrder.status)">{{ getStatusText(currentOrder.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentOrder.createTime }}</el-descriptions-item>
          <el-descriptions-item label="指派人">{{ currentOrder.assignee || '未指派' }}</el-descriptions-item>
          <el-descriptions-item label="计划完成时间">{{ currentOrder.deadline || '—' }}</el-descriptions-item>
        </el-descriptions>

        <!-- 处理记录 -->
        <div class="process-logs" v-if="currentOrder.processLogs?.length">
          <div class="sub-title">处理记录</div>
          <el-timeline>
            <el-timeline-item v-for="log in currentOrder.processLogs" :key="log.id" :timestamp="log.time" :type="log.type">
              {{ log.content }}
            </el-timeline-item>
          </el-timeline>
        </div>

        <!-- 操作按钮 -->
        <div class="detail-actions" v-if="currentOrder.status === 'pending'">
          <el-button type="primary" @click="handleOrder(currentOrder)">开始处理</el-button>
          <el-button type="warning" @click="openAssignDialog">指派人员</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 指派人员对话框 -->
    <el-dialog v-model="assignDialogVisible" title="指派维护人员" width="400px">
      <el-form>
        <el-form-item label="选择维护人员">
          <el-select v-model="selectedWorkerId" placeholder="请选择" style="width: 100%">
            <el-option v-for="worker in workers" :key="worker.id" :label="worker.name" :value="worker.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="assignRemark" placeholder="可选，填写派单说明" rows="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="assignDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAssign">确认指派</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { List, Search, Refresh } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 模拟工单数据
const mockOrders = ref([
  {
    id: 1, code: 'WO-20250402-001', caseCode: 'CASE-20250402-001', alertLevel: 'critical',
    alertType: '倾斜超标', alertDesc: '井盖倾斜角度14.2°，超过阈值8°，有跌落风险',
    ownerUnit: '市政工程管理处', address: '人民路与解放路口东50m', purpose: '主干道排水',
    status: 'pending', createTime: '2025-04-02 14:25:00', assignee: null, deadline: '2025-04-03 14:25:00',
    processLogs: [{ id: 1, time: '2025-04-02 14:25:00', content: '工单自动创建', type: 'info' }]
  },
  {
    id: 2, code: 'WO-20250402-002', caseCode: 'CASE-20250402-002', alertLevel: 'critical',
    alertType: '水位超限', alertDesc: '井下水位62cm，超过阈值40cm，溢水风险',
    ownerUnit: '水务集团', address: '滨江路化工园区南门', purpose: '化工区雨水排放',
    status: 'processing', createTime: '2025-04-02 14:00:00', assignee: '张建国', deadline: '2025-04-03 10:00:00',
    processLogs: [
      { id: 1, time: '2025-04-02 14:00:00', content: '工单自动创建', type: 'info' },
      { id: 2, time: '2025-04-02 14:30:00', content: '已指派张建国前往处置', type: 'primary' }
    ]
  },
  {
    id: 3, code: 'WO-20250402-003', caseCode: 'CASE-20250402-003', alertLevel: 'warning',
    alertType: '异常震动', alertDesc: '异常震动112mg，超过阈值80mg，疑似外力冲击',
    ownerUnit: '市政设施管理处', address: '古城街北段树下', purpose: '老城区排水',
    status: 'pending', createTime: '2025-04-02 12:15:00', assignee: null, deadline: '2025-04-03 12:15:00',
    processLogs: [{ id: 1, time: '2025-04-02 12:15:00', content: '工单自动创建', type: 'info' }]
  },
  {
    id: 4, code: 'WO-20250402-004', caseCode: 'CASE-20250402-004', alertLevel: 'warning',
    alertType: '井盖开启异常', alertDesc: '井盖非正常开启',
    ownerUnit: '市政工程管理处', address: '南港路旧车站段', purpose: '市政井盖',
    status: 'overdue', createTime: '2025-04-01 10:30:00', assignee: '王大明', deadline: '2025-04-02 10:30:00',
    processLogs: [
      { id: 1, time: '2025-04-01 10:30:00', content: '工单创建', type: 'info' },
      { id: 2, time: '2025-04-01 11:00:00', content: '指派王大明处置', type: 'primary' },
      { id: 3, time: '2025-04-02 10:30:00', content: '工单已逾期，待处理', type: 'danger' }
    ]
  },
  {
    id: 5, code: 'WO-20250402-005', caseCode: 'CASE-20250402-005', alertLevel: 'critical',
    alertType: '气体超标', alertDesc: '井下H₂S浓度28ppm，超过阈值15ppm',
    ownerUnit: '生态环境局', address: '石化大道南侧', purpose: '化工区排污',
    status: 'pending', createTime: '2025-04-02 09:20:00', assignee: null, deadline: '2025-04-03 09:20:00',
    processLogs: [{ id: 1, time: '2025-04-02 09:20:00', content: '工单自动创建', type: 'info' }]
  },
  {
    id: 6, code: 'WO-20250402-006', caseCode: 'CASE-20250402-006', alertLevel: 'warning',
    alertType: '电池低电量', alertDesc: '设备电池电量仅剩12%，需及时更换',
    ownerUnit: '市政设施管理处', address: '中央公园北门', purpose: '公园排水',
    status: 'processing', createTime: '2025-04-02 08:45:00', assignee: '陈辉', deadline: '2025-04-03 08:45:00',
    processLogs: [
      { id: 1, time: '2025-04-02 08:45:00', content: '工单创建', type: 'info' },
      { id: 2, time: '2025-04-02 09:30:00', content: '指派陈辉前往更换电池', type: 'primary' }
    ]
  }
])

// 维护人员列表
const workers = ref([
  { id: 'w1', name: '张建国 - 维修一组' },
  { id: 'w2', name: '李志强 - 维修二组' },
  { id: 'w3', name: '王大明 - 应急抢修队' },
  { id: 'w4', name: '陈辉 - 巡检专员' },
  { id: 'w5', name: '赵志远 - 抢修班' }
])

// 筛选状态
const searchKeyword = ref('')
const alertLevelFilter = ref('')
const statusFilter = ref('pending')  // 默认显示待处理
const currentPage = ref(1)
const pageSize = ref(10)
const loading = ref(false)

// 弹窗/抽屉状态
const detailDrawerVisible = ref(false)
const assignDialogVisible = ref(false)
const currentOrder = ref(null)
const selectedWorkerId = ref('')
const assignRemark = ref('')

// 计算属性
const filteredOrders = computed(() => {
  let list = mockOrders.value

  // 状态筛选
  if (statusFilter.value) {
    list = list.filter(o => o.status === statusFilter.value)
  }

  // 报警级别筛选
  if (alertLevelFilter.value) {
    list = list.filter(o => o.alertLevel === alertLevelFilter.value)
  }

  // 关键词搜索
  if (searchKeyword.value) {
    const kw = searchKeyword.value.toLowerCase()
    list = list.filter(o =>
        o.code.toLowerCase().includes(kw) ||
        o.caseCode.toLowerCase().includes(kw) ||
        o.address.toLowerCase().includes(kw)
    )
  }

  return list
})

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

const totalOrders = computed(() => mockOrders.value.length)
const pendingOrdersCount = computed(() => mockOrders.value.filter(o => o.status === 'pending').length)
const processingOrdersCount = computed(() => mockOrders.value.filter(o => o.status === 'processing').length)
const overdueCount = computed(() => mockOrders.value.filter(o => o.status === 'overdue').length)

// 方法
const setStatusFilter = (status) => {
  statusFilter.value = status
  currentPage.value = 1
}

const getStatusType = (status) => {
  const map = { pending: 'danger', processing: 'warning', overdue: 'danger', completed: 'success' }
  return map[status] || 'info'
}

const getStatusText = (status) => {
  const map = { pending: '待处理', processing: '处理中', overdue: '已逾期', completed: '已完成' }
  return map[status] || status
}

const refreshList = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    ElMessage.success('列表已刷新')
  }, 500)
}

const handleRowClick = (row) => {
  viewDetail(row)
}

const viewDetail = (order) => {
  currentOrder.value = order
  detailDrawerVisible.value = true
}

const viewCaseDetail = () => {
  ElMessage.info(`查看案件 ${currentOrder.value?.caseCode} 详情（演示）`)
}

const handleOrder = (order) => {
  if (order.status === 'pending') {
    // 如果未指派人员，先弹出指派对话框
    if (!order.assignee) {
      currentOrder.value = order
      assignDialogVisible.value = true
    } else {
      // 已有指派人，直接更新状态
      order.status = 'processing'
      order.processLogs.push({
        id: Date.now(),
        time: new Date().toLocaleString(),
        content: `开始处理工单，负责人：${order.assignee}`,
        type: 'primary'
      })
      ElMessage.success(`工单 ${order.code} 已开始处理`)
      detailDrawerVisible.value = false
    }
  }
}

const openAssignDialog = () => {
  assignDialogVisible.value = true
}

const confirmAssign = () => {
  if (!selectedWorkerId.value) {
    ElMessage.warning('请选择维护人员')
    return
  }
  const worker = workers.value.find(w => w.id === selectedWorkerId.value)
  if (currentOrder.value) {
    currentOrder.value.assignee = worker.name
    currentOrder.value.status = 'processing'
    currentOrder.value.processLogs.push({
      id: Date.now(),
      time: new Date().toLocaleString(),
      content: `已指派 ${worker.name} 处理工单，备注：${assignRemark.value || '无'}`,
      type: 'primary'
    })
    ElMessage.success(`工单已指派给 ${worker.name}`)
  }
  assignDialogVisible.value = false
  selectedWorkerId.value = ''
  assignRemark.value = ''
  detailDrawerVisible.value = false
}
</script>

<style scoped>
.pending-orders {
  background: #f0f2f6;
  min-height: 100vh;
  padding: 20px;
}

.page-header {
  background: white;
  border-radius: 16px;
  padding: 16px 24px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-left .title {
  font-size: 20px;
  font-weight: 600;
  color: #1f2d3d;
}

.header-right {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.stats-cards {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 12px 24px;
  text-align: center;
  cursor: pointer;
  transition: all 0.2s;
  min-width: 100px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.05);
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.stat-card.active {
  border: 2px solid #409eff;
  background: #ecf5ff;
}

.stat-card.pending .stat-value { color: #f56c6c; }
.stat-card.processing .stat-value { color: #e6a23c; }
.stat-card.overdue .stat-value { color: #f56c6c; }

.stat-value {
  font-size: 28px;
  font-weight: bold;
}

.stat-label {
  font-size: 13px;
  color: #606266;
  margin-top: 4px;
}

.order-table-container {
  background: white;
  border-radius: 16px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
  padding-top: 12px;
  border-top: 1px solid #e9ecef;
}

.order-detail {
  padding: 8px;
}

.sub-title {
  font-weight: 600;
  margin: 16px 0 12px 0;
  font-size: 14px;
  color: #2c3e50;
}

.process-logs {
  margin-top: 16px;
}

.detail-actions {
  margin-top: 24px;
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}
</style>