/**
 * 修复版百度地图服务工具
 * 专门解决 coordType 错误问题
 */

// 百度地图API加载状态
let BMapLoaded = false;
let loadingPromise = null;

/**
 * 加载百度地图API
 */
export const loadBMapScript = async (retryCount = 0) => {
  if (BMapLoaded) {
    console.log('百度地图API已加载');
    return Promise.resolve();
  }
  
  if (loadingPromise) {
    console.log('百度地图API正在加载中...');
    return loadingPromise;
  }
  
  console.log(`开始加载百度地图API... (重试次数: ${retryCount})`);
  
  loadingPromise = new Promise(async (resolve, reject) => {
    try {
      const { BAIDU_MAP_CONFIG } = await import('../config/env');
      
      console.log('使用API密钥:', BAIDU_MAP_CONFIG.apiKey);
      
      if (!BAIDU_MAP_CONFIG.apiKey || BAIDU_MAP_CONFIG.apiKey === 'YOUR_VALID_BAIDU_MAP_API_KEY') {
        const error = new Error('百度地图API密钥未配置或无效');
        console.error('API密钥错误:', error);
        reject(error);
        return;
      }
      
      if (typeof window.BMap !== 'undefined') {
        console.log('BMap已存在，直接使用');
        BMapLoaded = true;
        resolve();
        return;
      }
      
      // 创建全局回调函数
      window.initBMap = () => {
        console.log('百度地图API加载成功');
        clearTimeout(timeoutId);
        
        setTimeout(() => {
          if (window.BMap && typeof window.BMap.Map === 'function') {
            BMapLoaded = true;
            resolve();
          } else {
            console.error('BMap对象未正确初始化');
            reject(new Error('BMap对象未正确初始化'));
          }
          delete window.initBMap;
        }, 100);
      };
      
      // 创建script标签
      const script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = `https://api.map.baidu.com/api?v=3.0&ak=${BAIDU_MAP_CONFIG.apiKey}&callback=initBMap`;
      
      console.log('百度地图API URL:', script.src);
      
      script.onerror = async (error) => {
        console.error('百度地图脚本加载失败:', error);
        clearTimeout(timeoutId);
        if (script.parentNode) {
          script.parentNode.removeChild(script);
        }
        if (window.initBMap) {
          delete window.initBMap;
        }
        
        if (retryCount < BAIDU_MAP_CONFIG.maxRetries) {
          console.log(`重试加载百度地图API (${retryCount + 1}/${BAIDU_MAP_CONFIG.maxRetries})`);
          setTimeout(() => {
            loadBMapScript(retryCount + 1).then(resolve).catch(reject);
          }, BAIDU_MAP_CONFIG.retryDelay);
        } else {
          reject(new Error('百度地图API加载失败，已达到最大重试次数'));
        }
      };
      
      // 设置超时
      const timeoutId = setTimeout(() => {
        console.error('百度地图API加载超时');
        if (script.parentNode) {
          script.parentNode.removeChild(script);
        }
        if (window.initBMap) {
          delete window.initBMap;
        }
        reject(new Error('百度地图API加载超时'));
      }, 10000);
      
      document.head.appendChild(script);
      
    } catch (error) {
      console.error('加载百度地图API时发生错误:', error);
      reject(error);
    }
  });
  
  return loadingPromise;
};

/**
 * 修复版创建地图函数
 * 专门解决 coordType 错误
 */
export const createMap = async (container, options = {}) => {
  console.log('修复版createMap函数开始执行');
  
  // 确保API已加载
  await loadBMapScript();
  
  // 验证容器
  if (!container) {
    throw new Error('地图容器不能为空');
  }
  
  // 检查容器是否在DOM中
  if (!document.contains(container)) {
    throw new Error('地图容器不在DOM中');
  }
  
  // 强制设置容器样式，确保地图能正确初始化
  const originalStyles = {
    position: container.style.position,
    display: container.style.display,
    visibility: container.style.visibility,
    width: container.style.width,
    height: container.style.height,
    minHeight: container.style.minHeight
  };
  
  // 设置临时样式
  container.style.position = 'relative';
  container.style.display = 'block';
  container.style.visibility = 'visible';
  container.style.width = container.style.width || '100%';
  container.style.height = container.style.height || '400px';
  container.style.minHeight = container.style.minHeight || '400px';
  
  // 等待样式生效
  await new Promise(resolve => setTimeout(resolve, 50));
  
  // 检查容器尺寸
  if (container.offsetWidth === 0 || container.offsetHeight === 0) {
    console.warn('容器尺寸为0，强制设置尺寸');
    container.style.width = '100%';
    container.style.height = '400px';
    await new Promise(resolve => setTimeout(resolve, 50));
  }
  
  console.log('容器最终状态:', {
    offsetWidth: container.offsetWidth,
    offsetHeight: container.offsetHeight,
    clientWidth: container.clientWidth,
    clientHeight: container.clientHeight,
    computedStyle: {
      position: window.getComputedStyle(container).position,
      display: window.getComputedStyle(container).display,
      visibility: window.getComputedStyle(container).visibility
    }
  });
  
  // 检查父级元素样式
  let parent = container.parentElement;
  while (parent && parent !== document.body) {
    const parentStyle = window.getComputedStyle(parent);
    if (parentStyle.position === 'fixed' || parentStyle.display === 'none') {
      console.warn('发现可能有问题的父级样式:', {
        tagName: parent.tagName,
        position: parentStyle.position,
        display: parentStyle.display
      });
    }
    parent = parent.parentElement;
  }
  
  // 默认配置
  const defaultOptions = {
    center: { lng: 106.27, lat: 38.47 },
    zoom: 8,
    enableMapClick: true,
    enableScrollWheelZoom: true,
    enableDragging: true,
    enableDoubleClickZoom: true,
    enableKeyboard: true
  };
  
  const mergedOptions = { ...defaultOptions, ...options };
  
  console.log('地图配置选项:', mergedOptions);
  
  // 创建地图实例
  let map;
  try {
    console.log('开始创建BMap.Map实例...');
    
    // 确保BMap对象存在
    if (!window.BMap || typeof window.BMap.Map !== 'function') {
      throw new Error('BMap对象未正确加载');
    }
    
    // 创建地图实例
    map = new window.BMap.Map(container);
    console.log('地图实例创建成功:', map);
    
    // 验证地图实例
    if (!map || typeof map.centerAndZoom !== 'function') {
      throw new Error('地图实例创建失败');
    }
    
  } catch (error) {
    console.error('创建地图实例失败:', error);
    // 恢复原始样式
    Object.keys(originalStyles).forEach(key => {
      container.style[key] = originalStyles[key];
    });
    throw error;
  }
  
  // 恢复原始样式
  Object.keys(originalStyles).forEach(key => {
    container.style[key] = originalStyles[key];
  });
  
  // 设置中心点和缩放级别
  console.log('设置地图中心点和缩放级别:', mergedOptions.center, mergedOptions.zoom);
  map.centerAndZoom(mergedOptions.center, mergedOptions.zoom);
  
  // 添加地图控件
  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.addEventListener('tilesloaded', function() {
    console.log('百度地图瓦片加载完成');
  });
  
  map.addEventListener('load', function() {
    console.log('百度地图完全加载完成');
  });
  
  // 设置地图功能
  if (mergedOptions.enableMapClick) {
    map.enableMapClick();
  }
  if (mergedOptions.enableScrollWheelZoom) {
    map.enableScrollWheelZoom();
  }
  if (mergedOptions.enableDragging) {
    map.enableDragging();
  }
  if (mergedOptions.enableDoubleClickZoom) {
    map.enableDoubleClickZoom();
  }
  if (mergedOptions.enableKeyboard) {
    map.enableKeyboard();
  }
  
  console.log('修复版地图创建完成');
  return map;
};

/**
 * 添加标记点
 */
export const addMarkers = (map, markers) => {
  if (!map || !markers || !Array.isArray(markers)) {
    console.warn('addMarkers: 参数无效');
    return;
  }
  
  console.log('添加标记点:', markers.length);
  
  markers.forEach((markerData, index) => {
    try {
      const point = new window.BMap.Point(markerData.lng, markerData.lat);
      const marker = new window.BMap.Marker(point);
      
      if (markerData.title) {
        const infoWindow = new window.BMap.InfoWindow(markerData.title);
        marker.addEventListener('click', function() {
          map.openInfoWindow(infoWindow, point);
        });
      }
      
      map.addOverlay(marker);
      console.log(`标记点 ${index + 1} 添加成功`);
    } catch (error) {
      console.error(`添加标记点 ${index + 1} 失败:`, error);
    }
  });
};

/**
 * 清除所有覆盖物
 */
export const clearOverlays = (map) => {
  if (!map) {
    console.warn('clearOverlays: 地图实例无效');
    return;
  }
  
  map.clearOverlays();
  console.log('已清除所有覆盖物');
};

/**
 * 调整视图以适应所有标记
 */
export const setViewToFitMarkers = (map, markers) => {
  if (!map || !markers || !Array.isArray(markers) || markers.length === 0) {
    console.warn('setViewToFitMarkers: 参数无效');
    return;
  }
  
  const points = markers.map(marker => new window.BMap.Point(marker.lng, marker.lat));
  map.setViewport(points);
  console.log('已调整视图以适应标记点');
};
