/**
 * 百度地图加载器
 * 提供更健壮的百度地图API加载和初始化功能
 */

// 百度地图API加载状态
let BMapLoaded = false;
let loadingPromise = null;
let retryCount = 0;
const MAX_RETRY = 3;

/**
 * 加载百度地图API
 * @param {string} apiKey - 百度地图API密钥
 * @returns {Promise} 加载完成的Promise
 */
export const loadBaiduMapAPI = async (apiKey = 'fLz8UwJSM3ayYl6dtsWYp7TQ8993R6kC') => {
  // 如果已经加载过，直接返回
  if (BMapLoaded && window.BMap) {
    console.log('百度地图API已加载');
    return Promise.resolve();
  }
  
  // 如果正在加载中，返回加载Promise
  if (loadingPromise) {
    console.log('百度地图API正在加载中...');
    return loadingPromise;
  }
  
  console.log('开始加载百度地图API...');
  
  // 创建加载Promise
  loadingPromise = new Promise(async (resolve, reject) => {
    try {
      // 检查API密钥
      if (!apiKey || apiKey === 'YOUR_VALID_BAIDU_MAP_API_KEY') {
        const error = new Error('百度地图API密钥未配置或无效');
        console.error('API密钥错误:', error);
        reject(error);
        return;
      }
      
      // 检查是否已经存在BMap
      if (typeof window.BMap !== 'undefined' && window.BMap.Map) {
        console.log('BMap已存在，直接使用');
        BMapLoaded = true;
        resolve();
        return;
      }
      
      // 创建全局回调函数
      window.initBaiduMapCallback = () => {
        console.log('百度地图API脚本加载完成');
        
        // 等待BMap对象完全初始化
        const checkBMap = () => {
          if (window.BMap && typeof window.BMap.Map === 'function') {
            console.log('BMap对象初始化完成');
            BMapLoaded = true;
            resolve();
            // 清理全局回调
            delete window.initBaiduMapCallback;
          } else {
            console.log('等待BMap对象初始化...');
            setTimeout(checkBMap, 100);
          }
        };
        
        // 开始检查BMap对象
        setTimeout(checkBMap, 50);
      };
      
      // 创建script标签
      const script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = `https://api.map.baidu.com/api?v=3.0&ak=${apiKey}&callback=initBaiduMapCallback`;
      
      console.log('百度地图API URL:', script.src);
      
      script.onerror = (error) => {
        console.error('百度地图脚本加载失败:', error);
        reject(new Error('百度地图脚本加载失败'));
      };
      
      script.onload = () => {
        console.log('百度地图脚本加载成功');
      };
      
      // 设置超时
      const timeout = setTimeout(() => {
        if (!BMapLoaded) {
          console.error('百度地图API加载超时');
          reject(new Error('百度地图API加载超时'));
        }
      }, 20000);
      
      // 成功加载后清除超时
      const originalResolve = resolve;
      resolve = () => {
        clearTimeout(timeout);
        originalResolve();
      };
      
      // 添加到文档中
      document.head.appendChild(script);
      
    } catch (error) {
      console.error('加载百度地图API时出错:', error);
      reject(error);
    }
  });
  
  return loadingPromise;
};

/**
 * 重试加载百度地图API
 * @param {string} apiKey - 百度地图API密钥
 * @returns {Promise} 加载完成的Promise
 */
export const retryLoadBaiduMapAPI = async (apiKey = 'fLz8UwJSM3ayYl6dtsWYp7TQ8993R6kC') => {
  if (retryCount >= MAX_RETRY) {
    throw new Error('百度地图API加载重试次数已达上限');
  }
  
  retryCount++;
  console.log(`第 ${retryCount} 次尝试加载百度地图API...`);
  
  // 重置状态
  BMapLoaded = false;
  loadingPromise = null;
  
  // 清理可能存在的旧脚本
  const existingScript = document.querySelector('script[src*="api.map.baidu.com"]');
  if (existingScript) {
    existingScript.remove();
  }
  
  // 清理全局回调
  if (window.initBaiduMapCallback) {
    delete window.initBaiduMapCallback;
  }
  
  return loadBaiduMapAPI(apiKey);
};

/**
 * 检查百度地图API是否可用
 * @returns {boolean} 是否可用
 */
export const isBaiduMapAvailable = () => {
  return BMapLoaded && window.BMap && typeof window.BMap.Map === 'function';
};

/**
 * 等待百度地图API加载完成
 * @param {number} timeout - 超时时间（毫秒）
 * @returns {Promise} 加载完成的Promise
 */
export const waitForBaiduMap = (timeout = 10000) => {
  return new Promise((resolve, reject) => {
    if (isBaiduMapAvailable()) {
      resolve();
      return;
    }
    
    const startTime = Date.now();
    const checkInterval = setInterval(() => {
      if (isBaiduMapAvailable()) {
        clearInterval(checkInterval);
        resolve();
      } else if (Date.now() - startTime > timeout) {
        clearInterval(checkInterval);
        reject(new Error('等待百度地图API加载超时'));
      }
    }, 100);
  });
};

/**
 * 创建百度地图实例
 * @param {string|HTMLElement} container - 地图容器ID或元素
 * @param {Object} options - 地图配置选项
 * @returns {Promise<BMap.Map>} 地图实例
 */
export const createBaiduMap = async (container, options = {}) => {
  try {
    // 确保百度地图API已加载
    await loadBaiduMapAPI();
    
    // 等待BMap完全可用
    await waitForBaiduMap();
    
    // 获取容器元素
    let mapContainer = typeof container === 'string' 
      ? document.getElementById(container) 
      : container;
    
    // 如果容器不存在，等待一段时间后重试
    if (!mapContainer) {
      console.log('地图容器不存在，等待DOM渲染...');
      await new Promise(resolve => setTimeout(resolve, 200));
      mapContainer = typeof container === 'string' 
        ? document.getElementById(container) 
        : container;
    }
    
    if (!mapContainer) {
      throw new Error('地图容器不存在，请确保DOM已正确渲染');
    }
    
    // 检查容器是否有尺寸
    if (mapContainer.offsetWidth === 0 || mapContainer.offsetHeight === 0) {
      console.warn('地图容器尺寸为0，等待尺寸计算...');
      await new Promise(resolve => setTimeout(resolve, 100));
    }
    
    // 默认配置
    const defaultOptions = {
      center: new window.BMap.Point(106.27, 38.47), // 宁夏中心点
      zoom: 8,
      enableMapClick: true,
      enableScrollWheelZoom: true,
      enableDragging: true,
      enableDoubleClickZoom: true,
      enableKeyboard: true
    };
    
    // 合并配置
    const mergedOptions = { ...defaultOptions, ...options };
    
    // 创建地图实例
    const map = new window.BMap.Map(mapContainer);
    
    // 设置中心点和缩放级别
    map.centerAndZoom(mergedOptions.center, mergedOptions.zoom);
    
    // 配置地图功能
    if (mergedOptions.enableScrollWheelZoom) {
      map.enableScrollWheelZoom();
    }
    
    if (mergedOptions.enableDragging) {
      map.enableDragging();
    } else {
      map.disableDragging();
    }
    
    if (mergedOptions.enableDoubleClickZoom) {
      map.enableDoubleClickZoom();
    } else {
      map.disableDoubleClickZoom();
    }
    
    if (mergedOptions.enableKeyboard) {
      map.enableKeyboard();
    } else {
      map.disableKeyboard();
    }
    
    // 添加地图控件
    map.addControl(new window.BMap.NavigationControl());
    map.addControl(new window.BMap.ScaleControl());
    map.addControl(new window.BMap.OverviewMapControl());
    
    console.log('百度地图创建成功');
    return map;
    
  } catch (error) {
    console.error('创建百度地图失败:', error);
    throw error;
  }
};
