<template>
  <div class="smart-host-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">主机定位总览</h2>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <a-button @click="exportData" class="export-button">
        <template #icon>
          <ExportOutlined />
        </template>
        导出数据
      </a-button>
      <div class="search-group">
        <a-input
          :value="searchValue"
          @input="updateSearchValue"
          placeholder="请输入主机编号"
          class="search-input"
          @pressEnter="handleSearch"
        />
        <a-button type="primary" class="search-button" @click="handleSearch">
          <template #icon>
            <SearchOutlined />
          </template>
          搜索
        </a-button>
        <a-button class="search-button" @click="handleClearSearch" v-if="searchValue.trim()">
          清除
        </a-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <a-table
        :columns="columns"
        :data-source="hosts"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @change="handleTableChange"
        class="host-table"
      >
        <template #bodyCell="{ column, record }">
          <!-- 设备编号 -->
          <template v-if="column.dataIndex === 'deviceNumber'">
            <span class="device-number">{{ record.deviceNumber }}</span>
          </template>
          
          <!-- 设备电量% -->
          <template v-else-if="column.dataIndex === 'battery'">
            <div class="battery-cell">
              <span class="battery-value">{{ record.battery }}</span>
            </div>
          </template>
          
          <!-- 设备信号值 -->
          <template v-else-if="column.dataIndex === 'signalValue'">
            <div class="signal-cell">
              <span class="signal-value">{{ record.signalValue }}</span>
            </div>
          </template>
          
          <!-- 设备温度/°C -->
          <template v-else-if="column.dataIndex === 'temperature'">
            <div class="temperature-cell">
              <span class="temperature-value">{{ record.temperature }}</span>
            </div>
          </template>
          
          <!-- 更新时间 -->
          <template v-else-if="column.dataIndex === 'updateTime'">
            <div class="update-time-cell">
              <span class="update-time-value">{{ record.updateTime }}</span>
            </div>
          </template>
          
          <!-- 联网状态 -->
          <template v-else-if="column.dataIndex === 'networkStatus'">
            <div class="network-status-cell">
              <a-tag 
                :color="getNetworkStatusColor(record.networkStatus)"
                class="network-status-tag"
              >
                {{ record.networkStatus }}
              </a-tag>
            </div>
          </template>
          
          <!-- 操作 -->
          <template v-else-if="column.dataIndex === 'action'">
            <div class="action-cell">
              <a-button type="link" class="action-link" @click="viewLocation(record)">
                查看定位
              </a-button>
              <!-- <a-button type="link" class="action-link" @click="viewCollectionInfo(record)">
                查看采集信息
              </a-button> -->
            </div>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 定位信息模态框 -->
    <a-modal
      :open="locationVisible"
      title="查看定位"
      :footer="null"
      width="90%"
      :style="{ top: '20px' }"
      @cancel="handleLocationCancel"
    >
      <div class="location-modal">
        <!-- 地图容器 -->
        <div class="map-container">
          <div id="locationMap" class="baidu-map"></div>
          
          <!-- 地图样式切换按钮 - 严格按照图片样式 -->
          <div class="map-style-controls">
            <div 
              :class="['style-btn', { active: mapStyle === 'normal' }]"
              @click="switchMapStyle('normal')"
            >
              地图
            </div>
            <div 
              :class="['style-btn', { active: mapStyle === 'hybrid' }]"
              @click="switchMapStyle('hybrid')"
            >
              混合
            </div>
          </div>
          

        </div>
        
        <!-- 底部取消按钮 -->
        <div class="location-footer">
          <a-button class="cancel-btn" @click="handleLocationCancel">取消</a-button>
        </div>
      </div>
    </a-modal>

    <!-- 采集信息模态框 -->
    <a-modal
      :open="collectionInfoVisible"
      title="查看采集信息"
      :footer="null"
      width="800px"
      @cancel="handleCollectionInfoCancel"
    >
      <div class="collection-info-modal">
        <div class="info-grid">
          <div class="info-item">
            <span class="label">设备编号:</span>
            <span class="value">{{ currentHost?.deviceNumber }}</span>
          </div>
          <div class="info-item">
            <span class="label">设备电量:</span>
            <span class="value">{{ currentHost?.battery }}%</span>
          </div>
          <div class="info-item">
            <span class="label">信号强度:</span>
            <span class="value">{{ currentHost?.signalValue }}</span>
          </div>
          <div class="info-item">
            <span class="label">设备温度:</span>
            <span class="value">{{ currentHost?.temperature }}°C</span>
          </div>
          <div class="info-item">
            <span class="label">GPS状态:</span>
            <span class="value">{{ currentHost?.gpsStatus }}</span>
          </div>
          <div class="info-item">
            <span class="label">联网状态:</span>
            <span class="value">{{ currentHost?.networkStatus }}</span>
          </div>
          <div class="info-item">
            <span class="label">最后更新:</span>
            <span class="value">{{ currentHost?.updateTime }}</span>
          </div>
          <div class="info-item">
            <span class="label">设备标题:</span>
            <span class="value">{{ currentHost?.title || '未设置' }}</span>
          </div>
        </div>
        
        <!-- 底部按钮 -->
        <div class="modal-footer">
          <a-button @click="handleCollectionInfoCancel">关闭</a-button>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { message } from 'ant-design-vue'
import { SearchOutlined, ExportOutlined } from '@ant-design/icons-vue'
import { ExportUtils } from '../utils/exportUtils'
import { loadBMapScript, createMap } from '@/utils/mapService'
import { API_CONFIG } from '@/config/env.js'

// 响应式数据
const hosts = ref([])
const loading = ref(false)
const searchValue = ref('')
const autoRefresh = ref(true)
const refreshInterval = ref(null)

// 模态框相关数据
const locationVisible = ref(false)
const collectionInfoVisible = ref(false)
const mapStyle = ref('normal')
const currentLocation = ref(null)
const currentHost = ref(null)
const baiduMap = ref(null)
const locationMarker = ref(null)

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
})

// 表格列配置 - 严格按照图片样式
const columns = [
  {
    title: '设备编号',
    dataIndex: 'deviceNumber',
    key: 'deviceNumber',
    width: 120,
    align: 'center',
  },
  {
    title: '设备电量/%',
    dataIndex: 'battery',
    key: 'battery',
    width: 100,
    align: 'center',
  },
  {
    title: '设备信号值',
    dataIndex: 'signalValue',
    key: 'signalValue',
    width: 100,
    align: 'center',
  },
  {
    title: '设备温度/°C',
    dataIndex: 'temperature',
    key: 'temperature',
    width: 120,
    align: 'center',
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
    width: 180,
    align: 'center',
  },
  {
    title: '联网状态',
    dataIndex: 'networkStatus',
    key: 'networkStatus',
    width: 100,
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 200,
    align: 'center',
  }
]

// 获取联网状态颜色
const getNetworkStatusColor = (status) => {
  const colorMap = {
    '已联网': 'green',
    '未联网': 'red'
  }
  return colorMap[status] || 'default'
}


// 获取数据
const fetchData = async (showMessage = false) => {
  try {
    loading.value = true
    
    // 构建查询参数
    const params = new URLSearchParams({
      page: pagination.current.toString(),
      limit: pagination.pageSize.toString(),
      _t: Date.now().toString(), // 防止缓存
      refresh: 'true'
    })
    
    // 如果有搜索条件，添加到参数中
    if (searchValue.value.trim()) {
      params.append('search', searchValue.value.trim())
      console.log('搜索条件:', searchValue.value.trim())
    }
    
    // 调用API获取智能主机数据（使用环境配置的基础URL，兼容生产 /farm/api 前缀）
    const apiUrl = `${API_CONFIG.baseUrl}/smart-devices/hosts?${params}`
    console.log('API请求URL:', apiUrl)
    
    const response = await fetch(apiUrl, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    console.log('API响应结果:', result)
    
    if (result.success) {
      // 更新设备列表数据（后端已计算联网状态）
      hosts.value = result.data || []
      pagination.total = result.total || 0
      
      console.log('更新后的设备列表:', hosts.value)
      console.log('总数:', pagination.total)
      
      if (showMessage) {
        const searchText = searchValue.value.trim() ? `搜索"${searchValue.value.trim()}"` : '加载'
        message.success(`${searchText}完成，共找到 ${pagination.total} 条主机数据`)
      }
      
    } else {
      throw new Error(result.message || '获取数据失败')
    }
    
  } catch (error) {
    console.error('获取数据失败:', error)
    if (showMessage) {
      message.error('获取数据失败: ' + error.message)
    }
    
    // 如果API失败，显示空数据
    hosts.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 更新搜索值
const updateSearchValue = (e) => {
  const newValue = e.target.value
  console.log('输入框值变化:', newValue)
  console.log('更新前searchValue:', searchValue.value)
  searchValue.value = newValue
  console.log('更新后searchValue:', searchValue.value)
}

// 搜索处理
const handleSearch = () => {
  console.log('执行搜索，当前搜索值:', searchValue.value)
  pagination.current = 1
  fetchData(true)
}

// 清除搜索
const handleClearSearch = () => {
  searchValue.value = ''
  pagination.current = 1
  fetchData(true)
}



// 自动刷新功能
const startAutoRefresh = () => {
  if (refreshInterval.value) {
    clearInterval(refreshInterval.value)
  }
  
  if (autoRefresh.value) {
    refreshInterval.value = setInterval(() => {
      fetchData(false) // 自动刷新时不显示成功消息
    }, 30000) // 每30秒自动刷新一次
    console.log('自动刷新已启动，每30秒更新一次数据')
  }
}

// 停止自动刷新
const stopAutoRefresh = () => {
  if (refreshInterval.value) {
    clearInterval(refreshInterval.value)
    refreshInterval.value = null
    console.log('自动刷新已停止')
  }
}

// 查看定位
const viewLocation = (record) => {
  if (record.longitude && record.latitude && record.longitude !== '0' && record.latitude !== '90') {
    currentLocation.value = {
      longitude: parseFloat(record.longitude),
      latitude: parseFloat(record.latitude),
      deviceNumber: record.deviceNumber,
      updateTime: record.updateTime
    }
    locationVisible.value = true
    
    // 延迟初始化地图，确保DOM已渲染
    setTimeout(() => {
      initBaiduMap()
    }, 100)
  } else {
    message.warning('该设备暂无有效定位信息')
  }
}

// 查看采集信息
const viewCollectionInfo = (record) => {
  currentHost.value = record
  collectionInfoVisible.value = true
}

// 取消定位信息
const handleLocationCancel = () => {
  locationVisible.value = false
  currentLocation.value = null
  if (baiduMap.value) {
    baiduMap.value = null
  }
  if (locationMarker.value) {
    locationMarker.value = null
  }
}

// 取消采集信息
const handleCollectionInfoCancel = () => {
  collectionInfoVisible.value = false
  currentHost.value = null
}

// 初始化百度地图
const initBaiduMap = async () => {
  if (!currentLocation.value) return
  
  try {
    // 确保百度地图API已加载
    await loadBMapScript()
    
    // 获取地图容器
    const mapContainer = document.getElementById('locationMap')
    if (!mapContainer) {
      message.error('地图容器不存在')
      return
    }
    
    // 创建地图实例
    const map = await createMap(mapContainer, {
      center: new window.BMap.Point(currentLocation.value.longitude, currentLocation.value.latitude),
      zoom: 15
    })
    
    baiduMap.value = map
    
    // 添加设备位置标记 - 使用红色大头针样式
    const point = new window.BMap.Point(currentLocation.value.longitude, currentLocation.value.latitude)
    
    // 创建自定义标记图标
    const icon = new window.BMap.Icon(
      'data:image/svg+xml;base64,' + btoa(`
        <svg width="32" height="48" viewBox="0 0 32 48" xmlns="http://www.w3.org/2000/svg">
          <path d="M16 0C7.163 0 0 7.163 0 16c0 16 16 32 16 32s16-16 16-32C32 7.163 24.837 0 16 0z" fill="#ff0000"/>
          <circle cx="16" cy="16" r="8" fill="#ffffff"/>
        </svg>
      `),
      new window.BMap.Size(32, 48),
      {
        anchor: new window.BMap.Size(16, 48)
      }
    )
    
    const marker = new window.BMap.Marker(point, { icon: icon })
    map.addOverlay(marker)
    locationMarker.value = marker
    
    // 创建时间戳标签，固定在红色大头针下方中间
    const label = new window.BMap.Label(currentLocation.value.updateTime, {
      position: point,
      offset: new window.BMap.Size(-50, 30) // 水平居中偏移-50像素，向下偏移30像素
    })
    
    // 设置标签样式
    label.setStyle({
      backgroundColor: 'rgba(0, 0, 0, 0.7)',
      color: 'white',
      border: 'none',
      borderRadius: '4px',
      padding: '4px 8px',
      fontSize: '12px',
      fontWeight: 'normal',
      whiteSpace: 'nowrap',
      boxShadow: '0 2px 4px rgba(0, 0, 0, 0.3)',
      zIndex: 999,
      textAlign: 'center',
      width: 'auto',
      minWidth: '120px'
    })
    
    map.addOverlay(label)
    
    // 创建信息窗口
    const infoWindow = new window.BMap.InfoWindow(`
      <div style="padding: 10px; font-size: 14px;">
        <div style="font-weight: bold; margin-bottom: 5px;">主机位置</div>
        <div>设备编号: ${currentLocation.value.deviceNumber}</div>
        <div>经度: ${currentLocation.value.longitude}</div>
        <div>纬度: ${currentLocation.value.latitude}</div>
        <div style="margin-top: 5px; color: #666;">
          最后定位时间: ${currentLocation.value.updateTime}
        </div>
      </div>
    `, {
      width: 200,
      height: 120
    })
    
    // 点击标记显示信息窗口
    marker.addEventListener('click', () => {
      map.openInfoWindow(infoWindow, point)
    })
    
    // 启用地图控件
    map.addControl(new window.BMap.NavigationControl())
    map.addControl(new window.BMap.ScaleControl())
    map.addControl(new window.BMap.OverviewMapControl())
    map.addControl(new window.BMap.MapTypeControl())
    
    // 启用滚轮缩放
    map.enableScrollWheelZoom(true)
    
    // 设置地图样式
    switchMapStyle(mapStyle.value)
    
    console.log('定位地图初始化成功')
    
  } catch (error) {
    console.error('初始化百度地图失败:', error)
    message.error('地图初始化失败: ' + error.message)
  }
}

// 切换地图样式
const switchMapStyle = (style) => {
  mapStyle.value = style
  
  if (!baiduMap.value) return
  
  try {
    if (style === 'normal') {
      // 普通地图
      baiduMap.value.setMapType(window.BMAP_NORMAL_MAP)
    } else if (style === 'hybrid') {
      // 混合地图（卫星图+路网）
      baiduMap.value.setMapType(window.BMAP_HYBRID_MAP)
    }
  } catch (error) {
    console.error('切换地图样式失败:', error)
  }
}

// 表格变化处理
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchData()
}

// 导出数据
const exportData = async () => {
  try {
    console.log('=== 开始导出智能主机数据 ===')
    
    message.loading('正在获取所有设备数据...', 0)
    
    // 构建查询参数，获取所有数据
    const params = new URLSearchParams({
      page: '1',
      limit: '10000', // 设置一个很大的限制值来获取所有数据
      _t: Date.now().toString()
    })
    
    // 如果有搜索条件，添加到参数中
    if (searchValue.value.trim()) {
      params.append('search', searchValue.value.trim())
      console.log('导出搜索条件:', searchValue.value.trim())
    }
    
    // 调用API获取所有智能主机数据（使用环境配置的基础URL，兼容生产 /farm/api 前缀）
    const apiUrl = `${API_CONFIG.baseUrl}/smart-devices/hosts?${params}`
    console.log('导出API请求URL:', apiUrl)
    
    const response = await fetch(apiUrl, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    console.log('API响应结果:', result)
    
    if (!result.success || !result.data || result.data.length === 0) {
      message.destroy()
      message.warning('没有数据可导出')
      return
    }
    
    const allHosts = result.data || []
    console.log('获取到所有设备数据:', allHosts.length, '条记录')
    console.log('原始数据示例:', allHosts[0])
    
    // 后端已经处理了大部分格式化，直接使用
    const exportData = allHosts
    
    console.log('导出设备数据示例:', exportData[0])
    console.log('导出设备数据总数:', exportData.length)
    
    message.destroy()
    message.loading('正在导出数据...', 0)
    
    const result_export = ExportUtils.exportDeviceData(exportData, 'host')
    
    if (result_export.success) {
      message.destroy()
      message.success(`导出成功！文件：${result_export.filename}`)
    } else {
      message.destroy()
      message.error(result_export.message)
    }
  } catch (error) {
    message.destroy()
    console.error('导出失败:', error)
    message.error('导出失败，请重试')
  }
}

// 组件挂载时获取数据并启动自动刷新
onMounted(() => {
  fetchData(true)
  startAutoRefresh()
})

// 组件卸载时清理定时器
onUnmounted(() => {
  stopAutoRefresh()
})
</script>

<style scoped>
.smart-host-container {
  padding: 24px;
  background: #fff;
  min-height: 100vh;
}

/* 页面标题样式 */
.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #52c41a;
  margin: 0;
  padding: 12px 20px;
  background: #f6ffed;
  border: 1px solid #b7eb8f;
  border-radius: 6px;
  display: inline-block;
}

/* 搜索栏样式 */
.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  gap: 16px;
}

.search-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-input {
  width: 200px;
  border-radius: 4px;
}

.search-button {
  border-radius: 4px;
}

.export-button {
  margin-right: 8px;
}

/* 表格容器样式 */
.table-container {
  background: #fff;
  border-radius: 6px;
  overflow: hidden;
}

.host-table {
  font-size: 12px;
}

/* 表格单元格样式 */
.device-number {
  color: #1890ff;
  font-weight: 500;
}

.battery-cell,
.signal-cell,
.temperature-cell,
.update-time-cell,
.network-status-cell {
  text-align: center;
}

.battery-value,
.signal-value,
.temperature-value,
.update-time-value {
  font-weight: bold;
  font-size: 14px;
}

.network-status-tag {
  border-radius: 4px;
  font-size: 12px;
  padding: 2px 8px;
}

.action-cell {
  display: flex;
  flex-direction: column;
  gap: 2px;
  align-items: center;
}

.action-link {
  color: #1890ff;
  font-size: 12px;
  padding: 0;
  height: auto;
  line-height: 1.2;
  text-decoration: underline;
}

.action-link:hover {
  color: #40a9ff;
}

/* 定位信息模态框样式 */
.location-modal {
  height: 80vh;
  display: flex;
  flex-direction: column;
}

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

.baidu-map {
  width: 100%;
  height: 100%;
  border-radius: 8px;
}

.map-style-controls {
  position: absolute;
  top: 20px;
  right: 20px;
  display: flex;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  overflow: hidden;
  z-index: 1000;
}

.style-btn {
  padding: 8px 16px;
  cursor: pointer;
  font-size: 14px;
  color: #666;
  border: 1px solid #d9d9d9;
  background: white;
  transition: all 0.3s;
  user-select: none;
}

.style-btn:first-child {
  border-right: none;
}

.style-btn:hover {
  color: #1890ff;
  border-color: #1890ff;
}

.style-btn.active {
  color: #fff;
  background-color: #1890ff;
  border-color: #1890ff;
}



.location-footer {
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
  margin-top: 16px;
}

.cancel-btn {
  background-color: #f5f5f5;
  border-color: #d9d9d9;
  color: #666;
}

.cancel-btn:hover {
  background-color: #e6e6e6;
  border-color: #bfbfbf;
  color: #333;
}

/* 采集信息模态框样式 */
.collection-info-modal {
  padding: 20px 0;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px 24px;
  margin-bottom: 24px;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-item .label {
  min-width: 100px;
  color: #666;
  font-size: 14px;
  margin-right: 12px;
}

.info-item .value {
  color: #333;
  font-size: 14px;
  font-weight: 500;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
  margin-top: 20px;
}

/* 表格样式优化 */
.host-table :deep(.ant-table) {
  font-size: 12px;
}

.host-table :deep(.ant-table-thead > tr > th) {
  padding: 8px 4px;
  font-size: 12px;
  font-weight: 600;
  text-align: center;
  white-space: nowrap;
  background: #fafafa;
}

.host-table :deep(.ant-table-tbody > tr > td) {
  padding: 6px 4px;
  font-size: 12px;
}

.host-table :deep(.ant-table-tbody > tr:hover > td) {
  background: #f5f5f5;
}

/* 确保表格不会超出容器 */
.host-table :deep(.ant-table-wrapper) {
  overflow: hidden;
}

.host-table :deep(.ant-table-container) {
  overflow-x: hidden;
}
</style>
