// 百度地图瓦片加载诊断工具

/**
 * 检查百度地图API是否正确加载
 */
export const checkBMapAPI = () => {
  const checks = {
    bMapLoaded: typeof window.BMap !== 'undefined',
    bMapVersion: window.BMap ? window.BMap.version : null,
    apiScript: !!document.querySelector('script[src*="api.map.baidu.com"]'),
    mapTypes: window.BMAP_NORMAL_MAP ? true : false
  }
  
  console.log('百度地图API检查结果:', checks)
  return checks
}

/**
 * 诊断地图瓦片加载问题
 */
export const diagnoseMapTiles = (map) => {
  if (!map) {
    console.warn('地图实例不存在')
    return
  }
  
  const diagnostics = {
    center: map.getCenter(),
    zoom: map.getZoom(),
    bounds: map.getBounds(),
    mapType: map.getMapType(),
    size: map.getSize(),
    viewport: map.getViewport()
  }
  
  console.log('地图瓦片诊断信息:', diagnostics)
  
  // 检查瓦片加载状态
  const tileLayer = map.getTileLayer()
  if (tileLayer) {
    console.log('瓦片图层信息:', tileLayer)
  }
  
  return diagnostics
}

/**
 * 强制重新加载地图瓦片
 */
export const forceReloadTiles = (map) => {
  if (!map) return
  
  console.log('强制重新加载地图瓦片')
  
  // 方法1：临时改变地图类型
  const currentType = map.getMapType()
  map.setMapType(window.BMAP_SATELLITE_MAP)
  setTimeout(() => {
    map.setMapType(currentType)
  }, 100)
}

/**
 * 监控地图瓦片加载性能
 */
export const monitorTileLoading = (map) => {
  if (!map) return
  
  let tileLoadStart = Date.now()
  
  map.addEventListener('tilesloaded', () => {
    const loadTime = Date.now() - tileLoadStart
    console.log(`地图瓦片加载完成，耗时: ${loadTime}ms`)
  })
  
  map.addEventListener('dragstart', () => {
    tileLoadStart = Date.now()
    console.log('开始拖动，准备加载新瓦片')
  })
  
  map.addEventListener('zoomstart', () => {
    tileLoadStart = Date.now()
    console.log('开始缩放，准备加载新瓦片')
  })
}

/**
 * 检查网络连接状态
 */
export const checkNetworkStatus = () => {
  const status = {
    online: navigator.onLine,
    connection: navigator.connection ? {
      effectiveType: navigator.connection.effectiveType,
      downlink: navigator.connection.downlink,
      rtt: navigator.connection.rtt
    } : null
  }
  
  console.log('网络状态:', status)
  return status
}
