<!--可视化调度-->
<template>
  <div class="app-container">
    <div class="dispatch-layout">
      <!-- 左列 -->
      <div class="left-col">
        <!-- 应急事件列表 -->
        <el-card shadow="never" class="panel-card">
          <template #header>
            <div class="card-title">
              <el-icon><Warning /></el-icon>
              <span>应急事件列表</span>
              <el-button type="primary" size="small" style="margin-left:auto" @click="refreshEvents">
                <el-icon><Refresh /></el-icon> 刷新事件列表
              </el-button>
            </div>
          </template>
          <div class="event-list">
            <div
              v-for="event in events"
              :key="event.id"
              class="event-item"
              :class="{ selected: selectedEventId === event.id }"
              @click="selectEvent(event.id)"
            >
              <div class="event-head">
                <span class="event-name">{{ event.name }}</span>
                <el-tag :type="levelTagType(event.level)" size="small">{{ event.level }}</el-tag>
              </div>
              <div class="event-info">
                <span>{{ event.location }}</span>
                <el-tag :type="event.status === '处置中' ? 'warning' : event.status === '紧急响应' ? 'danger' : 'info'" size="small" effect="plain">
                  {{ event.status }}
                </el-tag>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 手动发送调度信息 -->
        <el-card shadow="never" class="panel-card">
          <template #header>
            <div class="card-title">
              <el-icon><Promotion /></el-icon>
              <span>手动发送调度信息</span>
            </div>
          </template>
          <div v-if="selectedEvent" class="selected-event-box">
            <el-descriptions :column="1" border size="small">
              <el-descriptions-item label="事件名称">{{ selectedEvent.name }}</el-descriptions-item>
              <el-descriptions-item label="事件等级">{{ selectedEvent.level }}</el-descriptions-item>
              <el-descriptions-item label="当前状态">{{ selectedEvent.status }}</el-descriptions-item>
            </el-descriptions>
          </div>
          <div v-else class="no-event-tip">请先从上方列表选择一个应急事件</div>
          <div style="margin-top:12px">
            <el-form label-position="top" size="default">
              <el-form-item label="调度半径（km）">
                <el-input-number v-model="dispatchRadius" :min="1" :max="50" :step="1" style="width:100%" @change="updateStatistics" />
              </el-form-item>
            </el-form>
            <div class="stat-section">
              <div class="stat-label">统计范围内在线资源</div>
              <div class="stat-row">
                <div class="stat-item">
                  <div class="stat-value">{{ stats.vehicleCount }}</div>
                  <div class="stat-name">应急车辆</div>
                </div>
                <div class="stat-item">
                  <div class="stat-value">{{ stats.personnelCount }}</div>
                  <div class="stat-name">应急人员</div>
                </div>
              </div>
            </div>
            <el-button type="danger" style="width:100%;margin-top:12px" @click="sendDispatch">
              <el-icon><Position /></el-icon> 发送调度指令
            </el-button>
            <div class="dispatch-tip">推送至手机APP及车载终端</div>
          </div>
        </el-card>
      </div>

      <!-- 中列 -->
      <div class="middle-col">
        <!-- 在线应急资源 -->
        <el-card shadow="never" class="panel-card">
          <template #header>
            <div class="card-title">
              <el-icon><Monitor /></el-icon>
              <span>在线应急资源</span>
              <el-tag type="info" size="small" style="margin-left:8px">半径 {{ dispatchRadius }}km</el-tag>
            </div>
          </template>
          <div class="resource-list">
            <div v-for="res in resourcesInRange" :key="res.id" class="resource-item">
              <div class="res-info">
                <span class="online-indicator"></span>
                <span class="res-name">{{ res.name }}</span>
              </div>
              <el-tag size="small" :type="res.category === '车辆' ? 'primary' : res.category === '值守人员' ? '' : 'warning'">
                {{ res.category }}
              </el-tag>
            </div>
            <div v-if="resourcesInRange.length === 0" class="empty-tip">半径内暂无在线资源</div>
          </div>
        </el-card>

        <!-- 应急处置临时群组 -->
        <el-card shadow="never" class="panel-card">
          <template #header>
            <div class="card-title">
              <el-icon><UserFilled /></el-icon>
              <span>应急处置临时群组</span>
              <el-button type="primary" size="small" style="margin-left:auto" @click="showCreateGroupDialog">新建群组</el-button>
            </div>
          </template>
          <div class="group-list">
            <div
              v-for="group in tempGroups"
              :key="group.id"
              class="group-item"
              :class="{ active: currentGroupId === group.id }"
              @click="selectGroup(group.id)"
            >
              <div class="group-head">
                <span class="group-name">{{ group.name }}</span>
                <el-button type="danger" size="small" text @click.stop="deleteGroup(group.id)">删除</el-button>
              </div>
              <div class="member-tags">
                <el-tag
                  v-for="memberId in group.members"
                  :key="memberId"
                  closable
                  size="small"
                  style="margin:2px"
                  @close="removeMember(group.id, memberId)"
                >
                  {{ getMemberName(memberId) }}
                </el-tag>
                <el-button size="small" text type="primary" @click.stop="openAddMemberDialog(group.id)">+ 添加</el-button>
              </div>
            </div>
            <div v-if="tempGroups.length === 0" class="empty-tip">暂无临时群组，点击新建</div>
          </div>
          <el-button style="width:100%;margin-top:12px" @click="addDeviceToCurrentGroup">
            添加设备到当前群组
          </el-button>
        </el-card>
      </div>

      <!-- 右列 -->
      <div class="right-col">
        <!-- 监控画面 -->
        <div class="monitor-grid">
          <div v-for="(cam, idx) in cameras" :key="idx" class="monitor-screen" @click="viewCamera(cam)">
            <div class="monitor-placeholder">
              <el-icon :size="32" color="#909399"><VideoCamera /></el-icon>
              <span class="monitor-label">{{ cam.name }}</span>
            </div>
          </div>
        </div>

        <!-- 音频对讲 -->
        <el-card shadow="never" class="panel-card" style="background:#1a2a3a;border-color:#2a3a4a">
          <template #header>
            <div class="card-title" style="color:#fff">
              <el-icon style="color:#67C23A"><Microphone /></el-icon>
              <span style="color:#fff">音频对讲</span>
            </div>
          </template>
          <div class="call-buttons">
            <el-button type="success" @click="callSingle">
              <el-icon><Phone /></el-icon> 一对一呼叫
            </el-button>
            <el-button type="warning" @click="callGroup">
              <el-icon><ChatDotRound /></el-icon> 群组对讲(一对多)
            </el-button>
            <el-button type="danger" @click="endCall">
              <el-icon><SwitchButton /></el-icon> 挂断
            </el-button>
          </div>
          <div class="call-status">
            {{ callStatusText }}
          </div>
          <div class="call-tip">
            当前选中群组: {{ currentGroupName }}，可发起群组对讲
          </div>
        </el-card>
      </div>
    </div>

    <!-- 新建群组弹窗 -->
    <el-dialog v-model="createGroupDialogVisible" title="新建临时群组" width="520px" append-to-body>
      <el-form label-position="top">
        <el-form-item label="群组名称">
          <el-input v-model="newGroupName" placeholder="请输入群组名称" />
        </el-form-item>
        <el-form-item label="选择成员">
          <el-checkbox-group v-model="newGroupMembers">
            <el-checkbox v-for="res in allResources" :key="res.id" :label="res.id" :value="res.id">
              {{ res.name }}（{{ res.category }}）
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createGroupDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCreateGroup">确定</el-button>
      </template>
    </el-dialog>

    <!-- 一对一呼叫弹窗 -->
    <el-dialog v-model="callSingleDialogVisible" title="一对一呼叫" width="480px" append-to-body>
      <p style="margin-bottom:12px;color:#606266;font-size:13px">请选择要呼叫的人员：</p>
      <el-checkbox-group v-model="callTargets">
        <div v-for="res in personResources" :key="res.id" style="margin-bottom:8px">
          <el-checkbox :label="res.id" :value="res.id">
            {{ res.name }}（{{ res.category }}）
          </el-checkbox>
        </div>
      </el-checkbox-group>
      <template #footer>
        <el-button @click="callSingleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCallSingle">呼叫</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Warning, Refresh, Promotion, Position, Monitor, UserFilled,
  Phone, ChatDotRound, SwitchButton, Microphone, VideoCamera
} from '@element-plus/icons-vue'

// ============ 应急事件 ============
const events = ref([
  { id: 1, name: '化工园区氯气泄漏', level: '重大', location: '化工园区', lat: 31.2, lng: 118.5, status: '处置中' },
  { id: 2, name: '城南枢纽交通事故', level: '较大', location: '城南枢纽', lat: 31.15, lng: 118.45, status: '待调度' },
  { id: 3, name: '城西隧道火灾', level: '特别重大', location: '城西隧道', lat: 31.22, lng: 118.38, status: '紧急响应' }
])

const selectedEventId = ref(1)
const selectedEvent = computed(() => events.value.find(e => e.id === selectedEventId.value))

const levelTagType = (level) => {
  const map = { '特别重大': 'danger', '重大': 'warning', '较大': '', '一般': 'info' }
  return map[level] || 'info'
}

const selectEvent = (id) => {
  selectedEventId.value = id
  updateStatistics()
}

const refreshEvents = () => {
  ElMessage.success('事件列表已刷新')
}

// ============ 调度参数 ============
const dispatchRadius = ref(5)
const stats = ref({ vehicleCount: 0, personnelCount: 0 })

// ============ 应急资源 ============
const vehicles = ref([
  { id: 'v1', name: '消防车-01', lat: 31.19, lng: 118.48, online: true, category: '车辆' },
  { id: 'v2', name: '救护车-03', lat: 31.21, lng: 118.52, online: true, category: '车辆' },
  { id: 'v3', name: '抢险车-05', lat: 31.17, lng: 118.44, online: true, category: '车辆' }
])

const persons = ref([
  { id: 'p1', name: '王敏', lat: 31.2, lng: 118.5, online: true, category: '值守人员' },
  { id: 'p2', name: '陈方', lat: 31.19, lng: 118.49, online: true, category: '指挥人员' },
  { id: 'p3', name: '刘洋', lat: 31.23, lng: 118.47, online: true, category: '值守人员' },
  { id: 'p4', name: '赵磊', lat: 31.18, lng: 118.46, online: true, category: '指挥人员' }
])

const allResources = computed(() => [...vehicles.value, ...persons.value])
const personResources = computed(() => persons.value)

// 计算距离
const getDistance = (lat1, lng1, lat2, lng2) => {
  const R = 6371
  const dLat = (lat2 - lat1) * Math.PI / 180
  const dLng = (lng2 - lng1) * Math.PI / 180
  const a = Math.sin(dLat / 2) ** 2 + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * Math.sin(dLng / 2) ** 2
  return R * 2 * Math.asin(Math.sqrt(a))
}

// 半径内资源
const resourcesInRange = computed(() => {
  if (!selectedEvent.value) return []
  const event = selectedEvent.value
  const radius = dispatchRadius.value
  const vInRange = vehicles.value.filter(v => v.online && getDistance(event.lat, event.lng, v.lat, v.lng) <= radius)
  const pInRange = persons.value.filter(p => p.online && getDistance(event.lat, event.lng, p.lat, p.lng) <= radius)
  return [...vInRange, ...pInRange]
})

// 更新统计
const updateStatistics = () => {
  if (!selectedEvent.value) return
  const event = selectedEvent.value
  const radius = dispatchRadius.value
  stats.value.vehicleCount = vehicles.value.filter(v => v.online && getDistance(event.lat, event.lng, v.lat, v.lng) <= radius).length
  stats.value.personnelCount = persons.value.filter(p => p.online && getDistance(event.lat, event.lng, p.lat, p.lng) <= radius).length
}

// 发送调度
const sendDispatch = () => {
  if (!selectedEvent.value) {
    ElMessage.warning('请先选择应急事件')
    return
  }
  ElMessageBox.confirm(
    `事件: ${selectedEvent.value.name}\n调度半径: ${dispatchRadius.value}km\n覆盖车辆: ${stats.value.vehicleCount}辆, 人员: ${stats.value.personnelCount}人\n\n确认发送调度指令？`,
    '调度指令确认',
    { confirmButtonText: '确认发送', cancelButtonText: '取消', type: 'warning' }
  ).then(() => {
    ElMessage.success('调度指令已发送！推送至手机APP、车载终端及应急指挥箱。')
  }).catch(() => {})
}

// ============ 临时群组 ============
const tempGroups = ref([
  { id: 'g1', name: '化工园区应急组', members: ['v1', 'p1'] },
  { id: 'g2', name: '医疗救护组', members: ['v2', 'p4'] }
])

const currentGroupId = ref(null)
const currentGroupName = computed(() => {
  const g = tempGroups.value.find(g => g.id === currentGroupId.value)
  return g ? g.name : '未选择'
})

const createGroupDialogVisible = ref(false)
const newGroupName = ref('')
const newGroupMembers = ref([])

const selectGroup = (groupId) => {
  currentGroupId.value = groupId
}

const getMemberName = (memberId) => {
  const res = allResources.value.find(r => r.id === memberId)
  return res ? res.name : memberId
}

const showCreateGroupDialog = () => {
  newGroupName.value = ''
  newGroupMembers.value = []
  createGroupDialogVisible.value = true
}

const confirmCreateGroup = () => {
  if (!newGroupName.value.trim()) {
    ElMessage.warning('请输入群组名称')
    return
  }
  const newId = 'g' + Date.now()
  tempGroups.value.push({ id: newId, name: newGroupName.value, members: [...newGroupMembers.value] })
  createGroupDialogVisible.value = false
  ElMessage.success(`群组「${newGroupName.value}」创建成功`)
}

const deleteGroup = (groupId) => {
  ElMessageBox.confirm('确定删除该临时群组？', '提示', { type: 'warning' }).then(() => {
    tempGroups.value = tempGroups.value.filter(g => g.id !== groupId)
    if (currentGroupId.value === groupId) currentGroupId.value = null
    ElMessage.success('群组已删除')
  }).catch(() => {})
}

const removeMember = (groupId, memberId) => {
  const group = tempGroups.value.find(g => g.id === groupId)
  if (group) {
    group.members = group.members.filter(m => m !== memberId)
  }
}

const addMemberTargetGroupId = ref(null)

const openAddMemberDialog = (groupId) => {
  addMemberTargetGroupId.value = groupId
  newGroupMembers.value = []
  // 复用新建群组弹窗的部分逻辑，但这里简化处理
  // 找到群组已有成员，排除后可选
  newGroupName.value = '' // 不使用名称
  createGroupDialogVisible.value = true
}

const addDeviceToCurrentGroup = () => {
  if (!currentGroupId.value) {
    ElMessage.warning('请先点击选中一个临时群组')
    return
  }
  openAddMemberDialog(currentGroupId.value)
}

// 重写confirmCreateGroup以支持添加成员模式
const confirmCreateGroupOriginal = confirmCreateGroup

// ============ 监控画面 ============
const cameras = ref([
  { name: '监控一', location: '化工园区' },
  { name: '监控二', location: '城南救援点' },
  { name: '监控三', location: '消防1组' },
  { name: '监控四', location: '城东路口' }
])

const viewCamera = (cam) => {
  ElMessage.info(`调取 ${cam.name}（${cam.location}）实时监控画面`)
}

// ============ 音频对讲 ============
const callStatusText = ref('未建立对讲 | 选择设备或群组')
const callSingleDialogVisible = ref(false)
const callTargets = ref([])

const callSingle = () => {
  callTargets.value = []
  callSingleDialogVisible.value = true
}

const confirmCallSingle = () => {
  if (callTargets.value.length === 0) {
    ElMessage.warning('请选择要呼叫的人员')
    return
  }
  const names = callTargets.value.map(id => getMemberName(id)).join('、')
  callStatusText.value = `正在呼叫 ${names}...`
  callSingleDialogVisible.value = false
  setTimeout(() => {
    callStatusText.value = `已与 ${names} 建立音频对讲`
    ElMessage.success(`已与 ${names} 建立音频对讲`)
  }, 1000)
}

const callGroup = () => {
  if (!currentGroupId.value) {
    ElMessage.warning('请先选中一个临时群组')
    return
  }
  const group = tempGroups.value.find(g => g.id === currentGroupId.value)
  if (!group || group.members.length === 0) {
    ElMessage.warning('群组无成员')
    return
  }
  callStatusText.value = `发起群组对讲 → ${group.name}，设备数: ${group.members.length}`
  setTimeout(() => {
    callStatusText.value = `群组对讲进行中: ${group.name} 已接通`
    ElMessage.success(`群组「${group.name}」对讲已接通`)
  }, 800)
}

const endCall = () => {
  callStatusText.value = '对讲已挂断 | 选择设备或群组'
  ElMessage.info('对讲已挂断')
}

// ============ 监听 ============
watch(dispatchRadius, () => { updateStatistics() })

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

<style scoped>
.app-container {
  padding: 16px;
  background: #f0f2f5;
  min-height: calc(100vh - 84px);
}

.dispatch-layout {
  display: flex;
  gap: 12px;
  height: calc(100vh - 120px);
}

.left-col {
  width: 25%;
  min-width: 280px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  overflow-y: auto;
}

.middle-col {
  width: 35%;
  min-width: 300px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  overflow-y: auto;
}

.right-col {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
  min-width: 0;
}

.panel-card {
  border-radius: 8px;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 600;
  font-size: 14px;
  color: #303133;
}

.card-title .el-icon {
  color: #409EFF;
  font-size: 16px;
}

/* 事件列表 */
.event-list {
  max-height: 260px;
  overflow-y: auto;
}

.event-item {
  padding: 10px 12px;
  margin-bottom: 8px;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
}

.event-item:hover {
  border-color: #409EFF;
}

.event-item.selected {
  border-color: #409EFF;
  background: #ecf5ff;
  border-left: 3px solid #409EFF;
}

.event-head {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.event-name {
  font-weight: 600;
  font-size: 13px;
  color: #303133;
}

.event-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #909399;
}

/* 调度面板 */
.selected-event-box {
  margin-bottom: 8px;
}

.no-event-tip {
  font-size: 13px;
  color: #909399;
  text-align: center;
  padding: 12px 0;
}

.stat-section {
  margin-top: 8px;
}

.stat-label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-row {
  display: flex;
  gap: 16px;
}

.stat-item {
  flex: 1;
  text-align: center;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 6px;
}

.stat-value {
  font-size: 24px;
  font-weight: 700;
  color: #409EFF;
}

.stat-name {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.dispatch-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
  text-align: center;
}

/* 资源列表 */
.resource-list {
  max-height: 200px;
  overflow-y: auto;
}

.resource-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
  font-size: 13px;
}

.resource-item:last-child {
  border-bottom: none;
}

.res-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.online-indicator {
  width: 8px;
  height: 8px;
  background: #67C23A;
  border-radius: 50%;
  flex-shrink: 0;
}

.res-name {
  color: #303133;
}

.empty-tip {
  text-align: center;
  padding: 16px;
  color: #909399;
  font-size: 13px;
}

/* 群组列表 */
.group-list {
  max-height: 260px;
  overflow-y: auto;
}

.group-item {
  padding: 10px;
  margin-bottom: 8px;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
}

.group-item:hover {
  border-color: #E6A23C;
}

.group-item.active {
  border-color: #E6A23C;
  background: #fdf6ec;
  border-left: 3px solid #E6A23C;
}

.group-head {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
}

.group-name {
  font-weight: 600;
  font-size: 13px;
  color: #303133;
}

.member-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  align-items: center;
}

/* 监控画面 */
.monitor-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  flex: 1;
  min-height: 280px;
}

.monitor-screen {
  background: #1a2a3a;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  border: 1px solid #2a3a4a;
  transition: border-color 0.2s;
}

.monitor-screen:hover {
  border-color: #409EFF;
}

.monitor-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  min-height: 120px;
  gap: 8px;
}

.monitor-label {
  font-size: 12px;
  color: #909399;
}

/* 音频对讲 */
.call-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.call-status {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 6px;
  padding: 8px 12px;
  margin-top: 12px;
  font-size: 13px;
  color: #fff;
}

.call-tip {
  margin-top: 8px;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
}
</style>
