<template>
  <div>
    <!-- 顶部统计卡片 -->
    <el-row :gutter="16" class="mb-16px">
      <el-col :xl="6" :lg="6" :md="12" :sm="12" :xs="24">
        <el-card shadow="hover" class="stat-card">
          <div class="flex items-center">
            <div class="stat-icon bg-blue-100">
              <Icon icon="mdi:account-group" :size="24" color="#1890ff" />
            </div>
            <div class="ml-16px">
              <div class="text-24px font-bold">{{ statistics.totalPersonnel }}</div>
              <div class="text-14px text-gray-500">总人员数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="12" :xs="24">
        <el-card shadow="hover" class="stat-card">
          <div class="flex items-center">
            <div class="stat-icon bg-green-100">
              <Icon icon="mdi:account-check" :size="24" color="#52c41a" />
            </div>
            <div class="ml-16px">
              <div class="text-24px font-bold">{{ statistics.onlinePersonnel }}</div>
              <div class="text-14px text-gray-500">在线人员</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="12" :xs="24">
        <el-card shadow="hover" class="stat-card">
          <div class="flex items-center">
            <div class="stat-icon bg-orange-100">
              <Icon icon="mdi:alert-circle" :size="24" color="#fa8c16" />
            </div>
            <div class="ml-16px">
              <div class="text-24px font-bold">{{ statistics.alertCount }}</div>
              <div class="text-14px text-gray-500">预警数量</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="12" :xs="24">
        <el-card shadow="hover" class="stat-card">
          <div class="flex items-center">
            <div class="stat-icon bg-purple-100">
              <Icon icon="mdi:map-marker-radius" :size="24" color="#722ed1" />
            </div>
            <div class="ml-16px">
              <div class="text-24px font-bold">{{ statistics.areaCount }}</div>
              <div class="text-14px text-gray-500">监控区域</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 主要内容区域 -->
    <el-row :gutter="16">
      <!-- 左侧地图区域 -->
      <el-col :xl="16" :lg="16" :md="24" :sm="24" :xs="24">
        <el-card shadow="never" class="map-card">
          <template #header>
            <div class="flex justify-between items-center">
              <span class="text-16px font-bold">人员实时定位</span>
              <div class="flex items-center space-x-8px">
                <el-button size="small" @click="refreshMap">
                  <Icon icon="mdi:refresh" class="mr-4px" />
                  刷新
                </el-button>
                <el-button size="small" @click="toggleFullscreen">
                  <Icon icon="mdi:fullscreen" class="mr-4px" />
                  全屏
                </el-button>
              </div>
            </div>
          </template>

          <!-- 地图容器 -->
          <div ref="mapContainer" class="map-container">
            <div id="personnelMap" class="map-content">
              <!-- 地图加载状态 -->
              <div v-if="mapLoading" class="map-loading">
                <div class="loading-content">
                  <Icon icon="mdi:loading" class="loading-icon" />
                  <div class="loading-text">地图加载中...</div>
                </div>
              </div>
            </div>

            <!-- 地图控制面板 -->
            <div class="map-controls">
              <div class="control-panel">
                <div class="control-title">图层控制</div>
                <el-checkbox v-model="mapLayers.showPersonnel" @change="toggleLayer('personnel')">
                  人员位置
                </el-checkbox>
                <el-checkbox v-model="mapLayers.showAreas" @change="toggleLayer('areas')">
                  安全区域
                </el-checkbox>
                <el-checkbox v-model="mapLayers.showAlerts" @change="toggleLayer('alerts')">
                  预警信息
                </el-checkbox>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 实时动态 -->
        <el-card shadow="never" class="mt-16px">
          <template #header>
            <div class="flex justify-between items-center">
              <span class="text-16px font-bold">实时动态</span>
              <el-tag type="success" size="small">
                <Icon icon="mdi:circle" class="mr-4px" />
                实时更新
              </el-tag>
            </div>
          </template>

          <div class="activity-list">
            <div v-for="activity in realTimeActivities" :key="activity.id" class="activity-item">
              <div class="activity-avatar">
                <el-avatar :size="32" :src="activity.avatar">
                  <Icon icon="mdi:account" />
                </el-avatar>
              </div>
              <div class="activity-content">
                <div class="activity-title">
                  <span class="font-medium">{{ activity.personName }}</span>
                  <span class="text-gray-500">{{ activity.action }}</span>
                </div>
                <div class="activity-location">
                  <Icon icon="mdi:map-marker" class="mr-4px" />
                  {{ activity.location }}
                </div>
                <div class="activity-time">{{ formatTime(activity.time, 'yyyy-MM-dd HH:mm:ss') }}</div>
              </div>
              <div class="activity-status">
                <el-tag :type="activity.status === 'normal' ? 'success' : 'warning'" size="small">
                  {{ activity.status === 'normal' ? '正常' : '异常' }}
                </el-tag>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧信息面板 -->
      <el-col :xl="8" :lg="8" :md="24" :sm="24" :xs="24">
        <!-- 人员列表 -->
        <el-card shadow="never">
          <template #header>
            <div class="flex justify-between items-center">
              <span class="text-16px font-bold">人员列表</span>
              <el-input
                v-model="searchKeyword"
                placeholder="搜索人员"
                size="small"
                style="width: 200px"
                clearable
              >
                <template #prefix>
                  <Icon icon="mdi:magnify" />
                </template>
              </el-input>
            </div>
          </template>

          <div class="personnel-list">
            <div
              v-for="person in filteredPersonnel"
              :key="person.id"
              class="personnel-item"
              :class="{ active: selectedPerson?.id === person.id }"
              @click="selectPerson(person)"
            >
              <div class="personnel-avatar">
                <el-avatar :size="40" :src="person.avatar">
                  <Icon icon="mdi:account" />
                </el-avatar>
                <div class="status-indicator" :class="person.status"></div>
              </div>
              <div class="personnel-info">
                <div class="personnel-name">{{ person.name }}</div>
                <div class="personnel-department">{{ person.department }}</div>
                <div class="personnel-location">
                  <Icon icon="mdi:map-marker" class="mr-4px" />
                  {{ person.currentLocation }}
                </div>
              </div>
              <div class="personnel-actions">
                <el-button size="small" @click.stop="trackPerson(person)">
                  <Icon icon="mdi:crosshairs-gps" />
                </el-button>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 预警信息 -->
        <el-card shadow="never" class="mt-16px">
          <template #header>
            <div class="flex justify-between items-center">
              <span class="text-16px font-bold">预警信息</span>
              <el-badge :value="alertList.length" class="item">
                <Icon icon="mdi:bell" />
              </el-badge>
            </div>
          </template>

          <div class="alert-list">
            <div v-for="alert in alertList" :key="alert.id" class="alert-item">
              <div class="alert-icon">
                <Icon
                  :icon="alert.type === 'danger' ? 'mdi:alert-circle' : 'mdi:information'"
                  :color="alert.type === 'danger' ? '#ff4d4f' : '#fa8c16'"
                />
              </div>
              <div class="alert-content">
                <div class="alert-title">{{ alert.title }}</div>
                <div class="alert-description">{{ alert.description }}</div>
                                 <div class="alert-time">{{ formatTime(alert.time, 'yyyy-MM-dd HH:mm:ss') }}</div>
              </div>
              <div class="alert-actions">
                <el-button size="small" @click="handleAlert(alert)">
                  处理
                </el-button>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 区域统计 -->
        <el-card shadow="never" class="mt-16px">
          <template #header>
            <span class="text-16px font-bold">区域统计</span>
          </template>

          <div class="area-stats">
            <div v-for="area in areaStats" :key="area.id" class="area-stat-item">
              <div class="area-info">
                <div class="area-name">{{ area.name }}</div>
                <div class="area-count">{{ area.personCount }}/{{ area.maxCapacity }}</div>
              </div>
              <el-progress
                :percentage="(area.personCount / area.maxCapacity) * 100"
                :color="getProgressColor(area.personCount / area.maxCapacity)"
              />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { formatTime } from '@/utils'
import type { Personnel, RealTimeActivity, Alert, AreaStat, Statistics, MapLayers } from './types'

defineOptions({ name: 'SafeHome' })

const { t } = useI18n()

// 统计数据
const statistics = reactive<Statistics>({
  totalPersonnel: 156,
  onlinePersonnel: 142,
  alertCount: 3,
  areaCount: 8
})

// 地图相关
const mapContainer = ref()
const mapLoading = ref(true)
const mapLayers = reactive<MapLayers>({
  showPersonnel: true,
  showAreas: true,
  showAlerts: true
})

// 搜索关键词
const searchKeyword = ref('')

// 选中的人员
const selectedPerson = ref<Personnel | null>(null)

// 人员列表数据
const personnelList = reactive<Personnel[]>([
  {
    id: 1,
    name: '成经理',
    department: '技术部',
    avatar: '',
    status: 'online',
    currentLocation: 'A区-3楼-会议室',
    lastUpdate: new Date()
  },
  {
    id: 2,
    name: '齐总',
    department: '销售部',
    avatar: '',
    status: 'offline',
    currentLocation: 'B区-2楼-办公区',
    lastUpdate: new Date()
  },
  {
    id: 3,
    name: '凡心仪',
    department: '人事部',
    avatar: '',
    status: 'warning',
    currentLocation: 'C区-1楼-大厅',
    lastUpdate: new Date()
  },
  {
    id: 4,
    name: '张总',
    department: '财务部',
    avatar: '',
    status: 'online',
    currentLocation: 'A区-4楼-财务室',
    lastUpdate: new Date()
  }
])

// 实时动态数据
const realTimeActivities = reactive<RealTimeActivity[]>([
  {
    id: 1,
    personName: '成经理',
    action: '进入A区',
    location: 'A区-3楼-会议室',
    time: new Date(),
    status: 'normal',
    avatar: ''
  },
  {
    id: 2,
    personName: '齐总',
    action: '离开B区',
    location: 'B区-2楼-办公区',
    time: new Date(Date.now() - 5 * 60 * 1000),
    status: 'normal',
    avatar: ''
  },
  {
    id: 3,
    personName: '凡心仪',
    action: '异常停留',
    location: 'C区-1楼-大厅',
    time: new Date(Date.now() - 10 * 60 * 1000),
    status: 'warning',
    avatar: ''
  }
])

// 预警信息
const alertList = reactive<Alert[]>([
  {
    id: 1,
    title: '人员异常停留',
    description: '凡心仪在C区大厅停留超过30分钟',
    type: 'warning',
    time: new Date(Date.now() - 15 * 60 * 1000)
  },
  {
    id: 2,
    title: '区域人数超限',
    description: 'A区会议室人数已达到上限',
    type: 'danger',
    time: new Date(Date.now() - 20 * 60 * 1000)
  },
  {
    id: 3,
    title: '设备离线',
    description: 'B区定位设备离线',
    type: 'warning',
    time: new Date(Date.now() - 25 * 60 * 1000)
  }
])

// 区域统计
const areaStats = reactive<AreaStat[]>([
  {
    id: 1,
    name: 'A区',
    personCount: 45,
    maxCapacity: 50
  },
  {
    id: 2,
    name: 'B区',
    personCount: 38,
    maxCapacity: 40
  },
  {
    id: 3,
    name: 'C区',
    personCount: 25,
    maxCapacity: 30
  },
  {
    id: 4,
    name: 'D区',
    personCount: 34,
    maxCapacity: 35
  }
])

// 计算属性
const filteredPersonnel = computed(() => {
  if (!searchKeyword.value) return personnelList
  return personnelList.filter(person =>
    person.name.includes(searchKeyword.value) ||
    person.department.includes(searchKeyword.value)
  )
})

// 方法
const refreshMap = () => {
  // 刷新地图数据
  if (map) {
    initPersonnelMarkers()
    console.log('地图数据已刷新')
  }
}

const toggleFullscreen = () => {
  // 切换全屏
  const mapElement = document.getElementById('personnelMap')
  if (mapElement) {
    if (!document.fullscreenElement) {
      mapElement.requestFullscreen()
    } else {
      document.exitFullscreen()
    }
  }
}

const toggleLayer = (layer: string) => {
  // 切换图层显示
  if (!map) return

  switch (layer) {
    case 'personnel':
      markers.forEach(marker => {
        marker.setVisible(mapLayers.showPersonnel)
      })
      break
    case 'areas':
      areas.forEach(area => {
        if (area instanceof BMapGL.Circle || area instanceof BMapGL.Label) {
          area.setVisible(mapLayers.showAreas)
        }
      })
      break
    case 'alerts':
      // 处理预警图层显示
      console.log('切换预警图层:', mapLayers.showAlerts)
      break
  }
}

const selectPerson = (person: Personnel) => {
  selectedPerson.value = person
  // 在地图上高亮显示选中人员
  console.log('选中人员:', person)
}

const trackPerson = (person: Personnel) => {
  // 追踪人员位置
  console.log('追踪人员:', person)
}

const handleAlert = (alert: Alert) => {
  // 处理预警信息
  console.log('处理预警:', alert)
}

const getProgressColor = (percentage: number) => {
  if (percentage < 0.7) return '#52c41a'
  if (percentage < 0.9) return '#fa8c16'
  return '#ff4d4f'
}

// 生命周期
onMounted(() => {
  // 初始化地图
  initMap()

  // 启动实时更新
  startRealTimeUpdate()
})

onUnmounted(() => {
  // 清理定时器
  stopRealTimeUpdate()
})

// 地图实例
let map: any = null
let markers: any[] = []
let areas: any[] = []

// 地图初始化
const initMap = () => {
  // 检查百度地图API是否已加载
  if (typeof BMapGL === 'undefined') {
    console.error('百度地图API未加载')
    return
  }

  const mapElement = document.getElementById('personnelMap')
  if (!mapElement) return

  try {
    // 创建地图实例，设置中心点和缩放级别
    map = new BMapGL.Map('personnelMap')
    const point = new BMapGL.Point(116.404, 39.915) // 北京天安门坐标
    map.centerAndZoom(point, 15)

    // 启用滚轮缩放
    map.enableScrollWheelZoom(true)

    // 添加地图控件
    map.addControl(new BMapGL.ScaleControl())
    map.addControl(new BMapGL.ZoomControl())
    map.addControl(new BMapGL.LocationControl())

    // 初始化人员标记点
    initPersonnelMarkers()

    // 初始化安全区域
    initSafetyAreas()

    console.log('百度地图初始化成功')
    mapLoading.value = false
  } catch (error) {
    console.error('地图初始化失败:', error)
    mapLoading.value = false
    mapElement.innerHTML = `
      <div style="width: 100%; height: 100%; background: #f0f2f5; display: flex; align-items: center; justify-content: center;">
        <div style="text-align: center; color: #666;">
          <Icon icon="mdi:alert-circle" style="font-size: 48px; margin-bottom: 16px; color: #ff4d4f;" />
          <div>地图加载失败</div>
          <div style="font-size: 12px; margin-top: 8px;">请检查网络连接和API密钥</div>
        </div>
      </div>
    `
  }
}

// 初始化人员标记点
const initPersonnelMarkers = () => {
  if (!map) return

  // 清除现有标记
  markers.forEach(marker => map.removeOverlay(marker))
  markers = []

  // 为每个人员创建标记点
  personnelList.forEach(person => {
    const point = getRandomPoint() // 模拟位置，实际应该从API获取
    const marker = new BMapGL.Marker(point, {
      icon: createPersonnelIcon(person.status),
      title: person.name
    })

    // 添加信息窗口
    const infoWindow = new BMapGL.InfoWindow(`
      <div style="padding: 10px;">
        <h4 style="margin: 0 0 8px 0;">${person.name}</h4>
        <p style="margin: 0 0 4px 0;">部门: ${person.department}</p>
        <p style="margin: 0 0 4px 0;">位置: ${person.currentLocation}</p>
        <p style="margin: 0;">状态: ${getStatusText(person.status)}</p>
      </div>
    `)

    marker.addEventListener('click', () => {
      map.openInfoWindow(infoWindow, point)
      selectPerson(person)
    })

    map.addOverlay(marker)
    markers.push(marker)
  })
}

// 初始化安全区域
const initSafetyAreas = () => {
  if (!map) return

  // 清除现有区域
  areas.forEach(area => map.removeOverlay(area))
  areas = []

  // 定义安全区域（模拟数据）
  const safetyAreas = [
    {
      name: 'A区',
      center: new BMapGL.Point(116.404, 39.915),
      radius: 200,
      color: '#52c41a'
    },
    {
      name: 'B区',
      center: new BMapGL.Point(116.414, 39.905),
      radius: 150,
      color: '#1890ff'
    },
    {
      name: 'C区',
      center: new BMapGL.Point(116.394, 39.925),
      radius: 180,
      color: '#fa8c16'
    }
  ]

  safetyAreas.forEach(area => {
    const circle = new BMapGL.Circle(area.center, area.radius, {
      fillColor: area.color,
      fillOpacity: 0.1,
      strokeColor: area.color,
      strokeOpacity: 0.8,
      strokeWeight: 2
    })

    // 添加区域标签
    const label = new BMapGL.Label(area.name, {
      position: area.center,
      offset: new BMapGL.Size(20, -10)
    })
    label.setStyle({
      color: area.color,
      fontSize: '14px',
      fontWeight: 'bold',
      backgroundColor: 'white',
      padding: '4px 8px',
      borderRadius: '4px',
      border: `1px solid ${area.color}`
    })

    map.addOverlay(circle)
    map.addOverlay(label)
    areas.push(circle, label)
  })
}

// 创建人员图标
const createPersonnelIcon = (status: string) => {
  const colors = {
    online: '#52c41a',
    offline: '#d9d9d9',
    warning: '#fa8c16'
  }

  const color = colors[status as keyof typeof colors] || '#d9d9d9'

  return new BMapGL.Icon(`
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
      <circle cx="12" cy="12" r="10" fill="${color}" stroke="white" stroke-width="2"/>
      <circle cx="12" cy="8" r="3" fill="white"/>
      <path d="M5 20c0-3.87 3.13-7 7-7s7 3.13 7 7" fill="white"/>
    </svg>
  `, new BMapGL.Size(24, 24))
}

// 获取随机坐标点（模拟数据）
const getRandomPoint = () => {
  const basePoint = new BMapGL.Point(116.404, 39.915)
  const latOffset = (Math.random() - 0.5) * 0.01
  const lngOffset = (Math.random() - 0.5) * 0.01
  return new BMapGL.Point(basePoint.lng + lngOffset, basePoint.lat + latOffset)
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap = {
    online: '在线',
    offline: '离线',
    warning: '异常'
  }
  return statusMap[status as keyof typeof statusMap] || '未知'
}

// 实时更新
let updateTimer: NodeJS.Timeout | null = null

const startRealTimeUpdate = () => {
  updateTimer = setInterval(() => {
    // 模拟实时数据更新
    console.log('实时数据更新')

    // 更新人员位置（模拟）
    if (map && markers.length > 0) {
      markers.forEach((marker, index) => {
        const newPoint = getRandomPoint()
        marker.setPosition(newPoint)
      })
    }

    // 更新统计数据
    statistics.onlinePersonnel = Math.floor(Math.random() * 20) + 140
    statistics.alertCount = Math.floor(Math.random() * 5) + 1
  }, 5000) // 每5秒更新一次
}

const stopRealTimeUpdate = () => {
  if (updateTimer) {
    clearInterval(updateTimer)
    updateTimer = null
  }
}
</script>

<style scoped>
.stat-card {
  transition: all 0.3s;
}

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

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.map-card {
  height: 600px;
}

.map-container {
  position: relative;
  height: 500px;
}

.map-content {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
}

.map-loading {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(240, 242, 245, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.loading-content {
  text-align: center;
  color: #666;
}

.loading-icon {
  font-size: 48px;
  margin-bottom: 16px;
  animation: spin 1s linear infinite;
}

.loading-text {
  font-size: 14px;
  color: #666;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.map-controls {
  position: absolute;
  top: 16px;
  right: 16px;
  z-index: 1000;
}

.control-panel {
  background: white;
  border-radius: 8px;
  padding: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.control-title {
  font-weight: 500;
  margin-bottom: 8px;
  font-size: 14px;
}

.activity-list {
  max-height: 300px;
  overflow-y: auto;
}

.activity-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

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

.activity-avatar {
  margin-right: 12px;
}

.activity-content {
  flex: 1;
}

.activity-title {
  font-size: 14px;
  margin-bottom: 4px;
}

.activity-location {
  font-size: 12px;
  color: #666;
  margin-bottom: 2px;
}

.activity-time {
  font-size: 12px;
  color: #999;
}

.activity-status {
  margin-left: 12px;
}

.personnel-list {
  max-height: 400px;
  overflow-y: auto;
}

.personnel-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border-radius: 8px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid transparent;
}

.personnel-item:hover {
  background: #f5f5f5;
}

.personnel-item.active {
  background: #e6f7ff;
  border-color: #1890ff;
}

.personnel-avatar {
  position: relative;
  margin-right: 12px;
}

.status-indicator {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  border: 2px solid white;
}

.status-indicator.online {
  background: #52c41a;
}

.status-indicator.offline {
  background: #d9d9d9;
}

.status-indicator.warning {
  background: #fa8c16;
}

.personnel-info {
  flex: 1;
}

.personnel-name {
  font-weight: 500;
  margin-bottom: 2px;
}

.personnel-department {
  font-size: 12px;
  color: #666;
  margin-bottom: 2px;
}

.personnel-location {
  font-size: 12px;
  color: #999;
}

.personnel-actions {
  margin-left: 8px;
}

.alert-list {
  max-height: 300px;
  overflow-y: auto;
}

.alert-item {
  display: flex;
  align-items: flex-start;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

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

.alert-icon {
  margin-right: 12px;
  margin-top: 2px;
}

.alert-content {
  flex: 1;
}

.alert-title {
  font-weight: 500;
  margin-bottom: 4px;
}

.alert-description {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.alert-time {
  font-size: 12px;
  color: #999;
}

.alert-actions {
  margin-left: 12px;
}

.area-stats {
  max-height: 200px;
  overflow-y: auto;
}

.area-stat-item {
  margin-bottom: 16px;
}

.area-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.area-name {
  font-weight: 500;
}

.area-count {
  font-size: 12px;
  color: #666;
}
</style>
