<!--运维任务管理-->
<template>
  <div class="terminal-dispatch">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-icon><Warning /></el-icon>
        <span class="title">异常终端派发中心</span>
        <el-tag type="danger" effect="dark">未处理异常 {{ abnormalCount }}</el-tag>
      </div>
      <div class="header-right">
        <el-input
            v-model="searchKeyword"
            placeholder="搜索终端编号/名称/地址"
            clearable
            :prefix-icon="Search"
            style="width: 240px"
        />
        <el-select v-model="deviceTypeFilter" placeholder="设备类型" clearable style="width: 120px">
          <el-option label="智能井盖" value="smart" />
          <el-option label="防爆井盖" value="explosion" />
          <el-option label="水位计" value="water" />
        </el-select>
        <el-button type="primary" :icon="Refresh" @click="refreshList">刷新</el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card critical">
        <div class="stat-value">{{ criticalCount }}</div>
        <div class="stat-label">严重异常</div>
      </div>
      <div class="stat-card warning">
        <div class="stat-value">{{ warningCount }}</div>
        <div class="stat-label">一般异常</div>
      </div>
      <div class="stat-card">
        <div class="stat-value">{{ pendingCount }}</div>
        <div class="stat-label">待派发</div>
      </div>
      <div class="stat-card">
        <div class="stat-value">{{ todayDispatched }}</div>
        <div class="stat-label">今日已派发</div>
      </div>
    </div>

    <!-- 批量操作栏 -->
    <div class="batch-bar" v-if="selectedRows.length > 0">
      <span>已选择 <strong>{{ selectedRows.length }}</strong> 个异常终端</span>
      <el-button type="primary" @click="batchDispatch">批量派发</el-button>
      <el-button @click="clearSelection">取消选择</el-button>
    </div>

    <!-- 主内容区：左侧终端列表 + 右侧详情 -->
    <div class="main-layout">
      <!-- 左侧异常终端列表 -->
      <div class="terminal-list-panel">
        <div class="list-header">
          <span>异常终端列表（未处理）</span>
          <el-checkbox v-model="selectAll" @change="handleSelectAll">全选</el-checkbox>
        </div>
        <div class="terminal-list">
          <div
              v-for="terminal in paginatedTerminals"
              :key="terminal.id"
              class="terminal-item"
              :class="{
              selected: selectedRows.includes(terminal.id),
              critical: terminal.abnormalLevel === 'critical',
              warning: terminal.abnormalLevel === 'warning'
            }"
          >
            <el-checkbox
                :model-value="selectedRows.includes(terminal.id)"
                @change="(val) => toggleSelect(terminal.id, val)"
                class="select-checkbox"
            />
            <div class="terminal-content" @click="selectTerminal(terminal)">
              <div class="terminal-header">
                <span class="terminal-code">{{ terminal.code }}</span>
                <el-tag :type="terminal.abnormalLevel === 'critical' ? 'danger' : 'warning'" size="small">
                  {{ terminal.abnormalLevel === 'critical' ? '严重' : '一般' }}
                </el-tag>
              </div>
              <div class="terminal-location">
                <el-icon><Location /></el-icon> {{ terminal.locationShort }}
              </div>
              <div class="terminal-desc">{{ terminal.abnormalDesc }}</div>
              <div class="terminal-time">异常时间: {{ terminal.abnormalTime }}</div>
            </div>
          </div>
        </div>
        <div class="pagination-area">
          <el-pagination
              small
              layout="prev, pager, next"
              :total="filteredTerminals.length"
              :page-size="pageSize"
              v-model:current-page="currentPage"
          />
        </div>
      </div>

      <!-- 右侧详情面板 -->
      <div class="detail-panel" v-if="selectedTerminal">
        <el-tabs v-model="activeTab">
          <!-- 终端基本信息与位置 -->
          <el-tab-pane label="终端信息" name="info">
            <div class="info-section">
              <div class="section-title">
                <span><el-icon><Monitor /></el-icon> 终端基本信息</span>
                <el-button type="primary" size="small" @click="openDispatchDialog(selectedTerminal)">派发任务</el-button>
              </div>
              <el-descriptions :column="2" border>
                <el-descriptions-item label="终端编号">{{ selectedTerminal.code }}</el-descriptions-item>
                <el-descriptions-item label="设备名称">{{ selectedTerminal.name }}</el-descriptions-item>
                <el-descriptions-item label="设备类型">{{ selectedTerminal.deviceTypeName }}</el-descriptions-item>
                <el-descriptions-item label="设备型号">{{ selectedTerminal.model }}</el-descriptions-item>
                <el-descriptions-item label="权属单位">{{ selectedTerminal.ownerUnit }}</el-descriptions-item>
                <el-descriptions-item label="异常级别">
                  <el-tag :type="selectedTerminal.abnormalLevel === 'critical' ? 'danger' : 'warning'">
                    {{ selectedTerminal.abnormalLevel === 'critical' ? '严重异常' : '一般异常' }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="异常描述" :span="2">{{ selectedTerminal.abnormalDesc }}</el-descriptions-item>
                <el-descriptions-item label="异常时间">{{ selectedTerminal.abnormalTime }}</el-descriptions-item>
                <el-descriptions-item label="当前状态">
                  <el-tag :type="selectedTerminal.status === 'pending' ? 'danger' : 'success'">
                    {{ selectedTerminal.status === 'pending' ? '待处理' : '处理中' }}
                  </el-tag>
                </el-descriptions-item>
              </el-descriptions>
            </div>

            <!-- 位置信息 - GIS地图模拟 -->
            <div class="location-section">
              <div class="section-title"><el-icon><MapLocation /></el-icon> 终端位置信息</div>
              <div class="map-container">
                <div class="mock-map">
                  <el-icon :size="40" color="#f56c6c"><Location /></el-icon>
                  <div class="map-coords">
                    <div><strong>{{ selectedTerminal.address }}</strong></div>
                    <div>经度: {{ selectedTerminal.lng }}, 纬度: {{ selectedTerminal.lat }}</div>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>

          <!-- 历次处置记录 -->
          <el-tab-pane label="处置记录" name="history">
            <div class="history-section">
              <div class="section-title"><el-icon><Document /></el-icon> 历次处置信息</div>
              <el-timeline v-if="selectedTerminal.historyRecords?.length">
                <el-timeline-item
                    v-for="record in selectedTerminal.historyRecords"
                    :key="record.id"
                    :timestamp="record.time"
                    :type="record.type"
                >
                  <div class="record-content">
                    <div><strong>派发对象:</strong> {{ record.dispatchedTo }}</div>
                    <div><strong>处置说明:</strong> {{ record.description }}</div>
                    <div v-if="record.feedbackImages?.length" class="record-images">
                      <el-image
                          v-for="(img, idx) in record.feedbackImages"
                          :key="idx"
                          :src="img"
                          fit="cover"
                          class="history-img"
                      />
                    </div>
                  </div>
                </el-timeline-item>
              </el-timeline>
              <el-empty v-else description="暂无历史处置记录" :image-size="80" />
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 未选中状态 -->
      <div v-else class="empty-panel">
        <el-empty description="请从左侧选择异常终端查看详情" :image-size="140" />
      </div>
    </div>

    <!-- 派发对话框 -->
    <el-dialog v-model="dispatchDialogVisible" :title="`派发任务 - ${currentDispatchTerminal?.code}`" width="500px">
      <el-form :model="dispatchForm" label-width="100px">
        <el-form-item label="派发对象" required>
          <el-select v-model="dispatchForm.targetType" placeholder="选择派发类型" style="width: 100%" @change="onTargetTypeChange">
            <el-option label="施工单位" value="construction" />
            <el-option label="维护人员" value="maintainer" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择单位/人员" required>
          <el-select v-model="dispatchForm.targetId" placeholder="请选择" style="width: 100%">
            <el-option
                v-for="item in dispatchTargets"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="派发说明">
          <el-input type="textarea" v-model="dispatchForm.remark" placeholder="填写任务要求、注意事项等" rows="3" />
        </el-form-item>
        <el-form-item label="期望完成时间">
          <el-date-picker v-model="dispatchForm.deadline" type="datetime" placeholder="选择截止时间" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dispatchDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmDispatch">确认派发</el-button>
      </template>
    </el-dialog>

    <!-- 批量派发确认对话框 -->
    <el-dialog v-model="batchDispatchDialogVisible" title="批量派发确认" width="450px">
      <p>将向以下 {{ batchDispatchIds.length }} 个异常终端派发任务：</p>
      <div class="batch-list">
        <el-tag v-for="id in batchDispatchIds.slice(0, 5)" :key="id" size="small" style="margin: 4px">
          {{ getTerminalCode(id) }}
        </el-tag>
        <span v-if="batchDispatchIds.length > 5">等{{ batchDispatchIds.length }}个终端</span>
      </div>
      <el-form style="margin-top: 16px">
        <el-form-item label="派发对象">
          <el-select v-model="batchDispatchForm.targetType" placeholder="选择派发类型" style="width: 100%">
            <el-option label="施工单位" value="construction" />
            <el-option label="维护人员" value="maintainer" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择单位/人员">
          <el-select v-model="batchDispatchForm.targetId" placeholder="请选择" style="width: 100%">
            <el-option v-for="item in batchDispatchTargets" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="batchDispatchDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmBatchDispatch">确认批量派发</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Warning, Search, Refresh, Location, Monitor, MapLocation, Document } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 模拟异常终端数据
const mockTerminals = ref([
  {
    id: 1, code: 'TM-1001', name: '人民路智能井盖', deviceType: 'smart', deviceTypeName: '智能井盖',
    model: 'WATCHMAN-S2', ownerUnit: '市政工程管理处', abnormalLevel: 'critical',
    abnormalDesc: '倾斜角度14.2°，超过阈值8°，有跌落风险', abnormalTime: '2025-04-02 14:23:15',
    status: 'pending', lng: 121.487, lat: 31.249, address: '人民路与解放路口东50m', locationShort: '人民路口',
    historyRecords: []
  },
  {
    id: 2, code: 'TM-1002', name: '滨江路防爆井盖', deviceType: 'explosion', deviceTypeName: '防爆井盖',
    model: 'WATCHMAN-EX', ownerUnit: '水务集团', abnormalLevel: 'critical',
    abnormalDesc: '水位62cm，超过阈值40cm，溢水风险', abnormalTime: '2025-04-02 13:55:02',
    status: 'pending', lng: 121.502, lat: 31.235, address: '滨江路化工园区南门', locationShort: '滨江园区',
    historyRecords: []
  },
  {
    id: 3, code: 'TM-1003', name: '古城街井盖', deviceType: 'smart', deviceTypeName: '智能井盖',
    model: 'WATCHMAN-S1', ownerUnit: '市政设施管理处', abnormalLevel: 'warning',
    abnormalDesc: '异常震动112mg，超过阈值80mg', abnormalTime: '2025-04-02 12:10:33',
    status: 'pending', lng: 121.478, lat: 31.258, address: '古城街北段树下', locationShort: '古城街',
    historyRecords: [
      { id: 1, time: '2025-03-28 10:30:00', type: 'primary', dispatchedTo: '维修一组-张建国', description: '现场检查为车辆碾压导致，已加固' }
    ]
  },
  {
    id: 4, code: 'TM-1004', name: '南港路井盖', deviceType: 'smart', deviceTypeName: '智能井盖',
    model: 'WATCHMAN-S2', ownerUnit: '市政工程管理处', abnormalLevel: 'warning',
    abnormalDesc: '井盖异常开启', abnormalTime: '2025-04-02 11:45:20',
    status: 'pending', lng: 121.495, lat: 31.228, address: '南港路旧车站段', locationShort: '南港路',
    historyRecords: []
  },
  {
    id: 5, code: 'TM-1005', name: '石化区防爆井盖', deviceType: 'explosion', deviceTypeName: '防爆井盖',
    model: 'WATCHMAN-EX', ownerUnit: '生态环境局', abnormalLevel: 'critical',
    abnormalDesc: 'H₂S浓度28ppm，超过阈值15ppm', abnormalTime: '2025-04-02 10:30:45',
    status: 'pending', lng: 121.524, lat: 31.239, address: '石化大道南侧', locationShort: '石化大道',
    historyRecords: [
      { id: 1, time: '2025-03-30 09:00:00', type: 'success', dispatchedTo: '应急抢修队-赵志远', description: '已通风处理，浓度降至安全范围' }
    ]
  },
  {
    id: 6, code: 'TM-1006', name: '高新区智能井盖', deviceType: 'smart', deviceTypeName: '智能井盖',
    model: 'WATCHMAN-S2', ownerUnit: '市政设施管理处', abnormalLevel: 'warning',
    abnormalDesc: '电池电量仅剩12%，需及时更换', abnormalTime: '2025-04-02 08:45:00',
    status: 'pending', lng: 121.512, lat: 31.242, address: '高新大道云计算中心旁', locationShort: '高新区',
    historyRecords: []
  }
])

// 派发目标选项
const constructionUnits = [
  { id: 'c1', name: '市政一建施工队', type: 'construction' },
  { id: 'c2', name: '水务工程公司', type: 'construction' },
  { id: 'c3', name: '管道抢修中心', type: 'construction' }
]
const maintainers = [
  { id: 'm1', name: '张建国 - 维修一组', type: 'maintainer' },
  { id: 'm2', name: '李志强 - 维修二组', type: 'maintainer' },
  { id: 'm3', name: '王大明 - 应急抢修队', type: 'maintainer' },
  { id: 'm4', name: '陈辉 - 巡检专员', type: 'maintainer' }
]

// 筛选条件
const searchKeyword = ref('')
const deviceTypeFilter = ref('')
const currentPage = ref(1)
const pageSize = 6

// 选择相关
const selectedRows = ref([])
const selectAll = ref(false)
const selectedTerminal = ref(mockTerminals.value[0])
const activeTab = ref('info')

// 派发相关
const dispatchDialogVisible = ref(false)
const currentDispatchTerminal = ref(null)
const dispatchForm = ref({
  targetType: 'construction',
  targetId: '',
  remark: '',
  deadline: ''
})
const batchDispatchDialogVisible = ref(false)
const batchDispatchIds = ref([])
const batchDispatchForm = ref({
  targetType: 'construction',
  targetId: ''
})

// 计算属性
const abnormalTerminals = computed(() => {
  return mockTerminals.value.filter(t => t.status === 'pending')
})

const filteredTerminals = computed(() => {
  let list = abnormalTerminals.value
  if (searchKeyword.value) {
    const kw = searchKeyword.value.toLowerCase()
    list = list.filter(t =>
        t.code.toLowerCase().includes(kw) ||
        t.name.toLowerCase().includes(kw) ||
        t.address.toLowerCase().includes(kw)
    )
  }
  if (deviceTypeFilter.value) {
    list = list.filter(t => t.deviceType === deviceTypeFilter.value)
  }
  return list
})

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

const abnormalCount = computed(() => abnormalTerminals.value.length)
const criticalCount = computed(() => abnormalTerminals.value.filter(t => t.abnormalLevel === 'critical').length)
const warningCount = computed(() => abnormalTerminals.value.filter(t => t.abnormalLevel === 'warning').length)
const pendingCount = computed(() => abnormalTerminals.value.filter(t => t.status === 'pending').length)
const todayDispatched = computed(() => {
  // 模拟今日派发数量
  return 3
})

// 派发目标动态计算
const dispatchTargets = computed(() => {
  if (dispatchForm.value.targetType === 'construction') {
    return constructionUnits
  } else {
    return maintainers
  }
})

const batchDispatchTargets = computed(() => {
  if (batchDispatchForm.value.targetType === 'construction') {
    return constructionUnits
  } else {
    return maintainers
  }
})

// 方法
const refreshList = () => {
  ElMessage.success('列表已刷新')
}

const handleSelectAll = (val) => {
  if (val) {
    selectedRows.value = paginatedTerminals.value.map(t => t.id)
  } else {
    selectedRows.value = []
  }
}

const toggleSelect = (id, val) => {
  if (val) {
    selectedRows.value.push(id)
  } else {
    selectedRows.value = selectedRows.value.filter(i => i !== id)
  }
  // 更新全选状态
  selectAll.value = paginatedTerminals.value.length > 0 &&
      paginatedTerminals.value.every(t => selectedRows.value.includes(t.id))
}

const clearSelection = () => {
  selectedRows.value = []
  selectAll.value = false
}

const selectTerminal = (terminal) => {
  selectedTerminal.value = terminal
}

const getTerminalCode = (id) => {
  const terminal = mockTerminals.value.find(t => t.id === id)
  return terminal?.code || id
}

// 单个派发
const openDispatchDialog = (terminal) => {
  currentDispatchTerminal.value = terminal
  dispatchForm.value = {
    targetType: 'construction',
    targetId: '',
    remark: '',
    deadline: ''
  }
  dispatchDialogVisible.value = true
}

const confirmDispatch = () => {
  if (!dispatchForm.value.targetId) {
    ElMessage.warning('请选择派发对象')
    return
  }
  const target = dispatchTargets.value.find(t => t.id === dispatchForm.value.targetId)
  if (currentDispatchTerminal.value) {
    // 更新终端状态
    currentDispatchTerminal.value.status = 'processing'
    // 添加处置记录
    const newRecord = {
      id: Date.now(),
      time: new Date().toLocaleString(),
      type: 'primary',
      dispatchedTo: target.name,
      description: dispatchForm.value.remark || '派发任务，请及时处理',
      deadline: dispatchForm.value.deadline ? new Date(dispatchForm.value.deadline).toLocaleString() : null
    }
    if (!currentDispatchTerminal.value.historyRecords) {
      currentDispatchTerminal.value.historyRecords = []
    }
    currentDispatchTerminal.value.historyRecords.unshift(newRecord)

    ElMessage.success(`已派发任务至 ${target.name}`)
  }
  dispatchDialogVisible.value = false
}

// 批量派发
const batchDispatch = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择异常终端')
    return
  }
  batchDispatchIds.value = [...selectedRows.value]
  batchDispatchForm.value = {
    targetType: 'construction',
    targetId: ''
  }
  batchDispatchDialogVisible.value = true
}

const confirmBatchDispatch = () => {
  if (!batchDispatchForm.value.targetId) {
    ElMessage.warning('请选择派发对象')
    return
  }
  const target = batchDispatchTargets.value.find(t => t.id === batchDispatchForm.value.targetId)

  // 批量更新所有选中的终端
  batchDispatchIds.value.forEach(id => {
    const terminal = mockTerminals.value.find(t => t.id === id)
    if (terminal && terminal.status === 'pending') {
      terminal.status = 'processing'
      const newRecord = {
        id: Date.now() + Math.random(),
        time: new Date().toLocaleString(),
        type: 'primary',
        dispatchedTo: target.name,
        description: `批量派发任务，${batchDispatchForm.value.targetType === 'construction' ? '请施工单位' : '请维护人员'}及时处理`
      }
      if (!terminal.historyRecords) terminal.historyRecords = []
      terminal.historyRecords.unshift(newRecord)
    }
  })

  ElMessage.success(`已批量派发 ${batchDispatchIds.value.length} 个任务至 ${target.name}`)
  batchDispatchDialogVisible.value = false
  clearSelection()
}

const onTargetTypeChange = () => {
  dispatchForm.value.targetId = ''
}
</script>

<style scoped>
.terminal-dispatch {
  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;
  min-width: 110px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.05);
}

.stat-card.critical .stat-value { color: #f56c6c; }
.stat-card.warning .stat-value { color: #e6a23c; }
.stat-value { font-size: 28px; font-weight: bold; }
.stat-label { font-size: 13px; color: #606266; margin-top: 4px; }

.batch-bar {
  background: #ecf5ff;
  border-radius: 12px;
  padding: 12px 20px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
}

.main-layout {
  display: flex;
  gap: 20px;
}

.terminal-list-panel {
  width: 420px;
  background: white;
  border-radius: 16px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.list-header {
  padding: 16px;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  justify-content: space-between;
  font-weight: 600;
}

.terminal-list {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
  max-height: calc(100vh - 280px);
}

.terminal-item {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  padding: 12px;
  margin-bottom: 10px;
  border-radius: 12px;
  background: #fafbfc;
  border: 1px solid #e9ecef;
  cursor: pointer;
  transition: all 0.2s;
}

.terminal-item.selected {
  background: #ecf5ff;
  border-color: #409eff;
}

.terminal-item.critical { border-left: 3px solid #f56c6c; }
.terminal-item.warning { border-left: 3px solid #e6a23c; }

.select-checkbox { margin-top: 2px; }
.terminal-content { flex: 1; }

.terminal-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 6px;
}

.terminal-code { font-weight: 600; font-size: 14px; }
.terminal-location { font-size: 12px; color: #6c757d; display: flex; align-items: center; gap: 4px; margin-bottom: 4px; }
.terminal-desc { font-size: 12px; color: #f56c6c; margin-bottom: 4px; }
.terminal-time { font-size: 11px; color: #aaa; }

.detail-panel {
  flex: 1;
  background: white;
  border-radius: 16px;
  padding: 20px;
  overflow-y: auto;
}

.empty-panel {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  border-radius: 16px;
}

.section-title {
  font-weight: 600;
  font-size: 16px;
  margin: 16px 0 12px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.map-container { margin-bottom: 20px; }
.mock-map {
  background: #e9f5e9;
  border-radius: 12px;
  height: 140px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
}

.record-content { font-size: 13px; }
.record-images { display: flex; gap: 8px; margin-top: 8px; }
.history-img { width: 60px; height: 50px; border-radius: 6px; object-fit: cover; }

.pagination-area { padding: 12px; text-align: center; border-top: 1px solid #eee; }

.batch-list { max-height: 150px; overflow-y: auto; }
</style>