import React, { useState, useEffect, useRef } from 'react';
import { message } from 'antd';
import { getPreviewUrl } from '@/services/VideoAPI';
import services from '@/services';

const isDebug = false;

const debugLog = (type: string, ...args: any[]) => {
  if (isDebug) {
    if(type === 'log' || type === undefined || type === null || type === '') {
      console.log(...args);
    } else if(type === 'error') {
      console.error(...args);
    }
  }
};

// Define types
interface VideoPlayerProps {
  deviceId: string;
  playerId?: string;
  visible: boolean;
  hide?: boolean;
  width?: number;
  height?: number;
  onInitialized?: (success: boolean) => void;
  onError?: (error: any) => void;
}

declare global {
  interface Window {
    WebControl: any;
    JSEncrypt: any;
    // 添加一个全局函数，可以在控制台手动清理播放器
    cleanupHikPlayer?: (playerId: string) => void;
    // 全局播放器实例缓存，避免重复创建
    hikPlayerInstances?: Record<string, any>;
  }
}

// 初始化全局播放器实例缓存
if (typeof window !== 'undefined' && !window.hikPlayerInstances) {
  window.hikPlayerInstances = {};
}

// 为全局添加一个手动清理函数，开发人员可以在控制台调用
if (typeof window !== 'undefined') {
  window.cleanupHikPlayer = (playerId: string) => {
    try {
      debugLog('log', `手动清理播放器: ${playerId}`);
      
      // 检查是否有缓存的实例
      const cachedInstance = window.hikPlayerInstances?.[playerId];
      if (cachedInstance) {
        try {
          cachedInstance.JS_HideWnd();
          debugLog('log', `已手动隐藏播放器: ${playerId}`);
        } catch (err) {
          debugLog('error', `手动隐藏播放器出错: ${err}`);
        }
      }
      
      // 尝试移除DOM元素内容
      const container = document.getElementById(playerId);
      if (container) {
        // 设置为隐藏状态
        container.style.visibility = 'hidden';
        debugLog('log', `已手动设置播放器容器为隐藏: ${playerId}`);
      } else {
        debugLog('error', `找不到播放器容器: ${playerId}`);
      }
      
      return true;
    } catch (error) {
      debugLog('error', `手动清理播放器出错: ${error}`);
      return false;
    }
  };
}

// Add the Hikvision script to the document
const loadScript = (src: string): Promise<void> => {
  return new Promise((resolve, reject) => {
    debugLog('log', `Loading script: ${src}`);
    
    // Check if script is already loaded
    const existingScript = document.querySelector(`script[src="${src}"]`);
    if (existingScript) {
      debugLog('log', `Script already loaded: ${src}`);
      resolve();
      return;
    }
    
    const script = document.createElement('script');
    script.src = src;
    script.async = true;
    
    script.onload = () => {
      debugLog('log', `Script loaded successfully: ${src}`);
      resolve();
    };
    
    script.onerror = (error) => {
      debugLog('error', `Failed to load script: ${src}`, error);
      reject(error);
    };
    
    document.head.appendChild(script);
  });
};

const VideoPlayer: React.FC<VideoPlayerProps> = ({ 
  deviceId, 
  playerId, 
  visible, 
  hide = false, 
  width,
  height,
  onInitialized, 
  onError 
}) => {
  const [oWebControl, setOWebControl] = useState<any>(null);
  const [initCount, setInitCount] = useState<number>(0);
  const [pubKey, setPubKey] = useState<string>('');
  const [streamUrl, setStreamUrl] = useState<string>('');
  const [isPlaying, setIsPlaying] = useState<boolean>(false);
  const [isInitialized, setIsInitialized] = useState<boolean>(false);
  const [isHidden, setIsHidden] = useState<boolean>(false);
  
  // const playWndRef = useRef<HTMLDivElement>(null);
  const playWndId = playerId || `playWnd_${deviceId}`;
  
  // 使用ref存储webControl实例，避免依赖于state引起的重渲染问题
  const webControlRef = useRef<any>(null);
  const resizeHandlerRef = useRef<() => void>(() => {});
  
  // 视频播放器容器宽高常量
  const ratio = 0.61;
  // 使用传入的宽高，如果没有传入则使用默认值
  const PLAYER_WIDTH = width || 357 * ratio;
  const PLAYER_HEIGHT = height || 206 * ratio;

  // 初始化插件及依赖
  const initDependencies = async () => {
    debugLog('log', 'initDependencies');
    try {
      // 尝试加载依赖脚本，先尝试使用已经在index.html中引入的脚本
      if (!window.JSEncrypt) {
        try {
          await loadScript('/cd-comprehensive/js/hikvision/jsencrypt.min.js');
        } catch (err) {
          debugLog('error', 'Failed to load jsencrypt.min.js', err);
        }
      }
      
      // 尝试加载 WebControl
      if (!window.WebControl) {
        try {
          await loadScript('/cd-comprehensive/js/hikvision/web-control_1.2.7.min.js');
        } catch (err) {
          debugLog('error', 'Failed to load web-control_1.2.7.min.js', err);
        }
      }
      
      // 等待一段时间，让脚本完全加载
      await new Promise(resolve => setTimeout(resolve, 500));
      
      if (!window.WebControl) {
        message.error('WebControl 初始化失败，请确保插件库正确安装');
        throw new Error('WebControl not initialized');
      }
      
      debugLog('log', 'Dependencies loaded successfully!');
      return true;
    } catch (error) {
      debugLog('error', 'Failed to load dependencies:', error);
      onError?.(error);
      return false;
    }
  };

  // 处理窗口大小变化
  const handleResize = () => {
    // 安全检查：确保webControlRef.current存在
    const webControl = webControlRef.current;
    if (!webControl) {
      debugLog('log', `${playWndId}：无法执行resize - webControlRef为空，稍后会重试`);
      return;
    }
    
    try {
      debugLog('log', `${playWndId}：执行resize操作:`, PLAYER_WIDTH, PLAYER_HEIGHT);
      webControl.JS_Resize(PLAYER_WIDTH, PLAYER_HEIGHT);
      setWndCover();
    } catch (err) {
      debugLog('error', `${playWndId}：resize操作失败:`, err);
    }
  };

  // 设置窗口裁剪
  const setWndCover = () => {
    const webControl = webControlRef.current;
    if (!webControl) {
      debugLog('log', `${playWndId}：setWndCover - webControlRef为空`);
      return;
    }

    try {
      const iWidth = window.innerWidth;
      const iHeight = window.innerHeight;
      const playWndElement = document.getElementById(playWndId);
      if (!playWndElement) {
        debugLog('log', `${playWndId}：setWndCover - 播放器DOM元素不存在`);
        return;
      }
      
      const oDivRect = playWndElement.getBoundingClientRect();
      // console.log(`${playWndId}：窗口位置信息:`, oDivRect);

      let iCoverLeft = oDivRect.left < 0 ? Math.abs(oDivRect.left) : 0;
      let iCoverTop = oDivRect.top < 0 ? Math.abs(oDivRect.top) : 0;
      let iCoverRight = oDivRect.right - iWidth > 0 ? Math.round(oDivRect.right - iWidth) : 0;
      let iCoverBottom = oDivRect.bottom - iHeight > 0 ? Math.round(oDivRect.bottom - iHeight) : 0;

      iCoverLeft = Math.min(iCoverLeft, PLAYER_WIDTH);
      iCoverTop = Math.min(iCoverTop, PLAYER_HEIGHT);
      iCoverRight = Math.min(iCoverRight, PLAYER_WIDTH);
      iCoverBottom = Math.min(iCoverBottom, PLAYER_HEIGHT);

      // console.log(`${playWndId}：执行窗口裁剪:`, PLAYER_WIDTH, PLAYER_HEIGHT);
      webControl.JS_RepairPartWindow(0, 0, PLAYER_WIDTH + 1, PLAYER_HEIGHT); // 多1个像素点防止还原后边界缺失一个像素条
      
      if (iCoverLeft !== 0) {
        webControl.JS_CuttingPartWindow(0, 0, iCoverLeft, PLAYER_HEIGHT);
      }
      if (iCoverTop !== 0) {
        webControl.JS_CuttingPartWindow(0, 0, PLAYER_WIDTH + 1, iCoverTop); // 多剪掉一个像素条，防止出现剪掉一部分窗口后出现一个像素条
      }
      if (iCoverRight !== 0) {
        webControl.JS_CuttingPartWindow(PLAYER_WIDTH - iCoverRight, 0, iCoverRight, PLAYER_HEIGHT);
      }
      if (iCoverBottom !== 0) {
        webControl.JS_CuttingPartWindow(0, PLAYER_HEIGHT - iCoverBottom, PLAYER_WIDTH, iCoverBottom);
      }
    } catch (err) {
      debugLog('error', `${playWndId}：执行窗口裁剪出错:`, err);
    }
  };

  // 获取视频URL并播放
  const fetchVideoUrl = async (webControl: any) => {
    // 防止重复获取视频
    if (isPlaying) {
      debugLog('log', `${playWndId}：视频已在播放中，跳过获取视频流`);
      return;
    }
    
    // 正在获取视频URL时避免重复调用
    const fetchingKey = `${playWndId}_fetching`;
    if ((window as any)[fetchingKey]) {
      debugLog('log', `${playWndId}：正在获取视频流，跳过重复请求`);
      return;
    }
    
    try {
      debugLog('log', `${playWndId}：开始获取视频流`);
      // (window as any)[fetchingKey] = true;      
      (window as any)[fetchingKey] = false;
      playVideo(webControl, '');
    } catch (error) {
      (window as any)[fetchingKey] = false;
      debugLog('error', `${playWndId}：获取视频流错误`, error);
      // message.error('获取视频流出错');
      onError?.(error);
    }
  };

  const fetchVideoUrlOld = async (webControl: any) => {
    // 防止重复获取视频
    if (isPlaying) {
      debugLog('log', `${playWndId}：视频已在播放中，跳过获取视频流`);
      return;
    }
    
    // 正在获取视频URL时避免重复调用
    const fetchingKey = `${playWndId}_fetching`;
    if ((window as any)[fetchingKey]) {
      debugLog('log', `${playWndId}：正在获取视频流，跳过重复请求`);
      return;
    }
    
    try {
      debugLog('log', `${playWndId}：开始获取视频流`);
      (window as any)[fetchingKey] = true;
      
      services.DataBase.getGzInfoData({
        typeCode: 'gz-zm-sblx',
      }).then((res) => {
        (window as any)[fetchingKey] = false;
        
        if (res.code === 200) {
          debugLog('log', `${playWndId}：获取视频流成功`);
          setStreamUrl(res.data);
          playVideo(webControl, res.data);
        } else {
          debugLog('error', `${playWndId}：获取视频流失败`, res);
          // message.error('获取视频流失败');
          onError?.(new Error('获取视频流失败'));
        }
      }).catch(error => {
        (window as any)[fetchingKey] = false;
        debugLog('error', `${playWndId}：获取视频流异常`, error);
        onError?.(error);
      });
    } catch (error) {
      (window as any)[fetchingKey] = false;
      debugLog('error', `${playWndId}：获取视频流错误`, error);
      message.error('获取视频流出错');
      onError?.(error);
    }
  };
  
  // 获取视频URL并播放
  const fetchVideoUrlFromDemo = async (webControl: any) => {
    try {
      const response = await getPreviewUrl({ indexCode: deviceId });
      if (response.code === '0' && response.data) {
        setStreamUrl(response.data);
        playVideo(webControl, response.data);
      } else {
        message.error('获取视频流失败');
        onError?.(new Error('获取视频流失败'));
      }
    } catch (error) {
      debugLog('error', '获取视频流错误', error);
      message.error('获取视频流出错');
      onError?.(error);
    }
  };

  // 播放视频
  const playVideo = (webControl: any, url: string) => {
    if (!webControl) {
      debugLog('error', `${playWndId}：无法播放视频 - WebControl实例不可用`);
      return;
    }
    
    // 防止重复播放
    if (isPlaying) {
      debugLog('log', `${playWndId}：视频已经在播放中，跳过播放`);
      return;
    }
    
    // 正在播放视频时避免重复调用
    const playingKey = `${playWndId}_playing`;
    if ((window as any)[playingKey]) {
      debugLog('log', `${playWndId}：视频正在启动播放过程中，跳过重复调用`);
      return;
    }
    
    try {
      debugLog('log', `${playWndId}：开始播放视频...`);
      (window as any)[playingKey] = true;
      
      // 显示视频窗口
      webControl.JS_ShowWnd();
      
      // 播放前确保窗口大小正确
      webControl.JS_Resize(PLAYER_WIDTH, PLAYER_HEIGHT);
      setWndCover();
      
      debugLog('log', `${playWndId}：开始预览, 相机码:`, deviceId);
      
      const params = {
        argument: {
          cameraIndexCode: deviceId,
          streamMode: 0,
          transMode: 1,
          gpuMode: 0,
          wndId: -1,
        },
        funcName: 'startPreview',
      };
      
      const param = JSON.stringify(params).replace(/(\s*)/g, '');
      
      webControl.JS_RequestInterface(JSON.parse(param))
        .then(function(oData: any) {
          debugLog('log', `${playWndId}：视频预览启动成功:`, oData);
          setIsPlaying(true);
          (window as any)[playingKey] = false;
          
          // 视频开始播放后再次确保窗口大小正确
          setTimeout(() => {
            if (webControl) {
              webControl.JS_Resize(PLAYER_WIDTH, PLAYER_HEIGHT);
              setWndCover();
            }
          }, 1000);
        })
        .catch(function(error: any) {
          debugLog('error', `${playWndId}：视频预览启动失败:`, error);
          (window as any)[playingKey] = false;
          setIsPlaying(false);
          onError?.(error);
        });
    } catch (error) {
      debugLog('error', `${playWndId}：播放视频出错:`, error);
      (window as any)[playingKey] = false;
      setIsPlaying(false);
      onError?.(error);
    }
  };
  
  // 隐藏视频窗口
  const hideWnd = () => {
    const webControl = webControlRef.current;
    if (webControl) {
      debugLog('log', '===执行隐藏播放器:', playWndId);
      try {
        // 先停止预览
        try {
          webControl.JS_RequestInterface({
            funcName: 'stopAllPreview',
          });
          debugLog('log', '已停止所有预览:', playWndId);
          setIsPlaying(false);
        } catch (err) {
          debugLog('error', '停止预览失败:', err);
        }
        
        // 隐藏窗口
        try {
          webControl.JS_HideWnd();
          debugLog('log', '已隐藏窗口:', playWndId);
        } catch (err) {
          debugLog('error', '隐藏窗口失败:', err);
        }
        
        // 隐藏容器
        const container = document.getElementById(playWndId);
        if (container) {
          container.style.visibility = 'hidden';
        }
        
        setIsHidden(true);
        return true;
      } catch (error) {
        debugLog('error', '隐藏播放器出错:', error);
        
        // 即使出错，也尝试设置隐藏状态
        setIsHidden(true);
        return false;
      }
    }
    return false;
  };

  // 销毁视频窗口
  const destroyWnd = () => {
    const webControl = webControlRef.current;
    if (webControl) {
      debugLog('log', '===执行销毁播放器:', playWndId);
      try {
        // 先隐藏DOM容器 - 防止销毁过程中仍然可见
        const container = document.getElementById(playWndId);
        if (container) {
          container.style.visibility = 'hidden';
        }
        
        // 停止所有预览 - 先执行这一步
        try {
        webControl.JS_RequestInterface({
          funcName: 'stopAllPreview',
        });
          debugLog('log', '已停止所有预览:', playWndId);
        } catch (err) {
          debugLog('error', '停止预览失败:', err);
        }
        
        // 隐藏窗口 (页面切换时使用)
        try {
          webControl.JS_HideWnd();
          debugLog('log', '已隐藏窗口:', playWndId);
        } catch (err) {
          debugLog('error', '隐藏窗口失败:', err);
        }
        
        // 实际销毁 (只有在组件卸载时才调用)
        if (false) { // 页面切换时不调用断开连接
          try {
        webControl.JS_Disconnect();
            debugLog('log', '已断开连接:', playWndId);
            
            // 清除缓存
            // if (window.hikPlayerInstances && window.hikPlayerInstances[playWndId]) {
            //   delete window.hikPlayerInstances[playWndId];
            // }
          } catch (err) {
            debugLog('error', '断开连接失败:', err);
          }
          
        webControlRef.current = null;
        setOWebControl(null);
        }
        
        setIsPlaying(false);
        setIsHidden(true);
        
        return true;
      } catch (error) {
        debugLog('error', '销毁播放器出错:', error);
        
        // 即使出错，也标记为隐藏状态
        setIsPlaying(false);
        setIsHidden(true);
        
        return false;
      }
    }
    return false;
  };

  // 手动触发一次resize事件
  const triggerManualResize = () => {
    if (!webControlRef.current) {
      debugLog('log', `${playWndId}：手动resize失败 - webControlRef为空`);
      return;
    }
    debugLog('log', `${playWndId}：触发手动resize`);
    handleResize();
  };

  // 组件挂载时初始化插件和事件监听
  useEffect(() => {
    if (visible) {
      debugLog('log', `${playWndId}：开始初始化播放器`);
      initPlugin();
    }
    
    // 创建一个稳定的resize处理函数
    const stableResizeHandler = () => {
      if (webControlRef.current) {
        handleResize();
      }
    };
    
    // 保存到ref中，确保移除时使用同一个函数引用
    resizeHandlerRef.current = stableResizeHandler;
    
    // 添加resize事件监听
    window.addEventListener('resize', stableResizeHandler);
    
    // 组件挂载后主动触发resize (只有在实例存在时才触发)
    let resizeTimers: number[] = [];
    
    // 使用递增延迟，确保在实例创建后能够触发resize
    const scheduleResize = (delay: number, maxAttempts: number, currentAttempt = 0) => {
      if (currentAttempt >= maxAttempts) return;
      
      const timerId = window.setTimeout(() => {
        if (webControlRef.current) {
          debugLog('log', `${playWndId}：尝试resize - 第${currentAttempt + 1}次, delay=${delay}ms`);
          handleResize();
        } else if (currentAttempt < maxAttempts - 1) {
          // 如果还没有实例且没达到最大尝试次数，递归调用
          scheduleResize(delay + 500, maxAttempts, currentAttempt + 1);
        }
      }, delay);
      
      resizeTimers.push(timerId);
    };
    
    // 尝试5次resize，间隔递增
    scheduleResize(1000, 5);
    
    // DOM变化监听，用于检测容器变化
    let observer: MutationObserver | null = null;
    if (visible) {
      // 等待容器元素创建
      const checkContainerAndObserve = () => {
        const container = document.getElementById(playWndId);
        if (container) {
          observer = new MutationObserver(() => {
            if (webControlRef.current) {
              // console.log(`${playWndId}：MutationObserver - DOM变化，触发resize`);
              handleResize();
            }
          });
          
          observer.observe(container, {
            childList: true,
            subtree: true,
            attributes: true
          });
        } else {
          // 如果容器不存在，稍后再试
          setTimeout(checkContainerAndObserve, 500);
        }
      };
      
      checkContainerAndObserve();
    }
    
    // 组件卸载时清理
    return () => {
      debugLog('log', `${playWndId}：组件卸载，执行销毁播放器`);
      hideWnd();
      window.removeEventListener('resize', stableResizeHandler);
      
      // 清除所有timer
      resizeTimers.forEach(id => window.clearTimeout(id));
      
      if (observer) {
        observer.disconnect();
      }
    };
  }, [visible, playWndId, PLAYER_WIDTH, PLAYER_HEIGHT]); // 当尺寸变化时重新执行

  // 当设备ID变化时获取新的视频流
  useEffect(() => {
    const webControl = webControlRef.current;
    if (webControl && isInitialized && !isPlaying && !isHidden) {
      fetchVideoUrl(webControl);
    }
  }, [deviceId, isInitialized, isPlaying, isHidden]);

  // 监听hide prop的变化
  useEffect(() => {
    if (hide && webControlRef.current && !isHidden) {
      debugLog('log', '接收到隐藏信号，正在隐藏播放器:', playWndId);
      hideWnd();
    } else if (!hide && webControlRef.current && isHidden && visible) {
      debugLog('log', '接收到显示信号，正在显示播放器:', playWndId);
      
      // 显示播放器
      try {
        webControlRef.current.JS_ShowWnd();
        
        // 重新调整大小
        webControlRef.current.JS_Resize(PLAYER_WIDTH, PLAYER_HEIGHT);
        setWndCover();
        
        // 设置容器可见
        const container = document.getElementById(playWndId);
        if (container) {
          container.style.visibility = 'visible';
        }
        
        setIsHidden(false);
        
        // 重新播放视频
        if (!isPlaying) {
          fetchVideoUrl(webControlRef.current);
        }
      } catch (err) {
        debugLog('error', '显示播放器窗口失败:', err);
      }
    }
  }, [hide, playWndId, isHidden, visible, isPlaying]);

  // 监听尺寸变化重新调整大小
  useEffect(() => {
    if (webControlRef.current && isInitialized && !isHidden) {
      debugLog('log', '播放器尺寸变化，重新调整大小:', PLAYER_WIDTH, PLAYER_HEIGHT);
      handleResize();
    }
  }, [PLAYER_WIDTH, PLAYER_HEIGHT, isInitialized, isHidden]);

  // 专门监听deviceId变化，强制切换视频
  useEffect(() => {
    const webControl = webControlRef.current;
    // 只在初始化完成且非隐藏状态时处理
    if (webControl && isInitialized && !isHidden) {
      // 如果正在播放，需要先停止当前视频，然后播放新视频
      if (isPlaying) {
        debugLog('log', `${playWndId}：设备ID变化，停止当前视频并切换到新视频:`, deviceId);
        try {
          // 停止当前预览
          webControl.JS_RequestInterface({
            funcName: 'stopAllPreview',
          }).then(() => {
            debugLog('log', `${playWndId}：成功停止当前视频，准备播放新视频`);
            setIsPlaying(false);
            // 延迟一点时间后获取新视频
            setTimeout(() => {
              fetchVideoUrl(webControl);
            }, 300);
          }).catch((err: any) => {
            debugLog('error', `${playWndId}：停止当前视频失败:`, err);
            // 即使停止失败，也尝试重置状态并播放新视频
            setIsPlaying(false);
            fetchVideoUrl(webControl);
          });
        } catch (err: any) {
          debugLog('error', `${playWndId}：停止视频时发生异常:`, err);
          // 出现异常时也重置播放状态并尝试播放新视频
          setIsPlaying(false);
          fetchVideoUrl(webControl);
        }
      } else {
        // 如果未播放，直接获取并播放新视频
        fetchVideoUrl(webControl);
      }
    }
  }, [deviceId]); // 仅依赖deviceId变化

  // 集成回调函数
  const cbIntegrationCallBack = (oData: any) => {
    debugLog('log', '集成回调函数', oData);
    if (oData.responseMsg?.msg?.result === 816) {
      setIsPlaying(false);
    }
  };

  // 初始化按钮点击
  const initBtnClicked = (webControl: any) => {
    if (!webControl) return;
    
    const objData = {
      appkey: '25896797',
      ip: '10.1.191.118',
      port: 443,
      secret: 'OomCCAPKTUSOFLXexiHV',
      // appkey: '27247271',
      // ip: '10.1.213.18',
      // secret: '65cuqMKiHZJhHLVyjq8g',
    };
    
    const params = {
      argument: {
        appkey: objData.appkey,
        secret: objData.secret,
        ip: objData.ip,
        playMode: 0,
        port: objData.port,
        snapDir: '',
        videoDir: '',
        layout: '1x1',
        enableHTTPS: 1,
        showToolbar: 0,
        showSmart: 0,
        buttonIDs: '0,16,256,257,258,259,260,512,513,514,515,516,517,768,769',
        reconnectTimes: 3
      },
      funcName: 'init',
    };
    
    const param = JSON.stringify(params).replace(/(\s*)/g, '');
    
    // 修改初始化流程，确保初始化完成后再获取并播放视频
    webControl.JS_RequestInterface(JSON.parse(param))
      .then(function(oData: any) {
        debugLog('log', '初始化成功', oData);
        // 初始化成功后再次调整窗口大小
        webControl.JS_Resize(PLAYER_WIDTH, PLAYER_HEIGHT);
        setWndCover();
        
        // 等待一秒再获取并播放视频
        setTimeout(() => {
          fetchVideoUrl(webControl);
        }, 1000);
      })
      .catch(function(error: any) {
        debugLog('error', '初始化失败', error);
        message.error('视频插件初始化失败');
        onError?.(error);
      });
  };

  // 请求接口
  const requestInterface = (webControl: any, value: string) => {
    if (!webControl) return;
    
    return webControl.JS_RequestInterface(JSON.parse(value)).then(function(oData: any) {
      debugLog('log', 'requestInterface', oData);
      return oData;
    });
  };

  // 下载插件
  const frontDownload = () => {
    const a = document.createElement('a');
    a.href = 'https://10.1.214.101:21000/download/VideoWebPlugin.exe';
    a.download = 'VideoWebPlugin.exe';
    a.style.display = 'none';
    document.body.appendChild(a);
    a.click();
    a.remove();
  };

  // 初始化插件
  const initPlugin = async () => {
    debugLog('log', `${playWndId}：开始初始化视频插件...`);
    
    // 防止重复初始化
    const initializingKey = `${playWndId}_initializing`;
    if ((window as any)[initializingKey]) {
      debugLog('log', `${playWndId}：插件正在初始化中，跳过重复初始化`);
      return;
    }
    
    try {
      (window as any)[initializingKey] = true;
      
      // 检查是否有全局缓存的实例
      if (window.hikPlayerInstances?.[playWndId]) {
        debugLog('log', `${playWndId}：使用全局缓存的播放器实例`);
        webControlRef.current = window.hikPlayerInstances[playWndId];
        setOWebControl(window.hikPlayerInstances[playWndId]);
        setIsInitialized(true);
        
        // 如果之前是隐藏状态，则显示播放器
        if (isHidden) {
          try {
            // 显示播放器窗口
            webControlRef.current.JS_ShowWnd();
            
            // 重新调整大小
            webControlRef.current.JS_Resize(PLAYER_WIDTH, PLAYER_HEIGHT);
            setWndCover();
            
            // 设置容器可见
            const container = document.getElementById(playWndId);
            if (container) {
              container.style.visibility = 'visible';
            }
            
            setIsHidden(false);
            onInitialized?.(true);
            
            // 如果之前没有播放状态，则重新播放
            if (!isPlaying) {
              // 延迟获取视频流，确保UI已渲染
              setTimeout(() => {
                fetchVideoUrl(webControlRef.current);
              }, 500);
            }
          } catch (err) {
            debugLog('error', `${playWndId}：显示播放器窗口失败:`, err);
            
            // 如果显示失败，需要重新初始化
            webControlRef.current = null;
            setOWebControl(null);
            if (window.hikPlayerInstances) {
              delete window.hikPlayerInstances[playWndId];
            }
            
            // 继续执行初始化流程
          }
        } else {
          // 重新调整大小
          webControlRef.current.JS_Resize(PLAYER_WIDTH, PLAYER_HEIGHT);
          setWndCover();
          onInitialized?.(true);
          
          // 如果之前没有播放状态，则重新播放
          if (!isPlaying) {
            // 延迟获取视频流，确保UI已渲染
            setTimeout(() => {
              fetchVideoUrl(webControlRef.current);
            }, 500);
          }
        }
        
        // 如果已经有播放器实例且显示成功，则返回
        if (webControlRef.current) {
          (window as any)[initializingKey] = false;
          return;
        }
      }
      
      // 从这里开始是创建新实例的逻辑
      const dependenciesLoaded = await initDependencies();
      if (!dependenciesLoaded) {
        debugLog('error', `${playWndId}：依赖加载失败，无法初始化插件`);
        message.error('依赖加载失败，无法初始化插件');
        onInitialized?.(false);
        (window as any)[initializingKey] = false;
        return;
      }

      // 检查播放器容器是否存在
      const container = document.getElementById(playWndId);
      if (!container) {
        debugLog('error', `${playWndId}：播放器容器不存在`);
        message.error('播放器容器不存在，请检查页面结构');
        onInitialized?.(false);
        (window as any)[initializingKey] = false;
        return;
      }
      
      // 确保容器可见
      container.style.visibility = 'visible';

      // 使用 WebControl 构造函数创建实例
      const { WebControl } = window;
      debugLog('log', `${playWndId}：创建WebControl实例`);
      
      const webControl = new WebControl({
        szPluginContainer: playWndId,
        iServicePortStart: 15900,
        iServicePortEnd: 15900,
        szClassId: '23BF3B0A-2C56-4D97-9C03-0CB103AA8F11',
        cbConnectSuccess: function() {
          debugLog('log', `${playWndId}：创建WebControl实例成功`);
          // VideoPluginConnect.dll 是从 VideoWebPlugin.exe 安装后的程序文件夹获取的
          // 这里的路径是相对于插件运行目录的路径，不是网站的相对路径
          webControl
            .JS_StartService('window', {
              dllPath: './VideoPluginConnect.dll',
            })
            .then(
              () => {
                debugLog('log', `${playWndId}：启动插件服务成功`);
                webControl.JS_SetWindowControlCallback({
                  cbIntegrationCallBack: cbIntegrationCallBack,
                });
                webControl
                  .JS_CreateWnd(playWndId, PLAYER_WIDTH, PLAYER_HEIGHT)
                  .then(() => {
                    debugLog('log', `${playWndId}：创建播放窗口成功`);
                    // 立即调整大小和位置
                    webControl.JS_Resize(PLAYER_WIDTH, PLAYER_HEIGHT);
                    
                    // 将实例保存到ref中，避免状态更新导致的重渲染
                    webControlRef.current = webControl;
                    
                    // 保存到全局缓存
                    if (window.hikPlayerInstances) {
                      window.hikPlayerInstances[playWndId] = webControl;
                    }
                    
                    // 也保存到状态中，但主要是为了组件更新
                    setOWebControl(webControl);
                    setIsInitialized(true);
                    setIsHidden(false);
                    onInitialized?.(true);
                    (window as any)[initializingKey] = false;
                    
                    // 窗口创建后调整大小和位置
                    setTimeout(() => {
                      if (webControlRef.current) {
                        webControlRef.current.JS_Resize(PLAYER_WIDTH, PLAYER_HEIGHT);
                        setWndCover();
                        initBtnClicked(webControlRef.current);
                        debugLog('log', `${playWndId}：初始化完成，尺寸已调整为:`, PLAYER_WIDTH, PLAYER_HEIGHT);
                      }
                    }, 500);
                  })
                  .catch((error: any) => {
                    debugLog('error', `${playWndId}：创建播放窗口失败`, error);
                    onInitialized?.(false);
                    (window as any)[initializingKey] = false;
                  });
              },
              (error: any) => {
                debugLog('error', `${playWndId}：启动插件服务失败`, error);
                onInitialized?.(false);
                (window as any)[initializingKey] = false;
              }
            )
            .catch((error: any) => {
              debugLog('error', `${playWndId}：JS_StartService 出错:`, error);
              onInitialized?.(false);
              (window as any)[initializingKey] = false;
            });
        },
        cbConnectError: function(error: any) {
          debugLog('error', `${playWndId}：创建WebControl实例失败`, error);
          webControlRef.current = null;
          setOWebControl(null);
          message.warning('插件未启动，正在尝试启动，请稍候...');
          (window as any)[initializingKey] = false;
          window.WebControl.JS_WakeUp('VideoWebPlugin://');
          setInitCount(prev => {
            const newCount = prev + 1;
            if (newCount < 3) {
              setTimeout(() => {
                initPlugin();
              }, 3000);
            } else {
              message.warning('插件启动失败，请检查插件是否安装！');
              onInitialized?.(false);
              if (newCount === 3) {
                frontDownload();
              }
            }
            return newCount;
          });
        },
        cbConnectClose: function(isNormalClose: boolean) {
          debugLog('log', `${playWndId}：WebControl连接关闭，正常关闭：`, isNormalClose);
          webControlRef.current = null;
          setOWebControl(null);
          (window as any)[initializingKey] = false;
          // message.warning('插件连接已关闭');
          onInitialized?.(false);
        }
      });
    } catch (error) {
      debugLog('error', `${playWndId}：初始化插件失败:`, error);
      // message.error('初始化插件失败，请刷新页面重试');
      onInitialized?.(false);
      (window as any)[initializingKey] = false;
    }
  };

  /* 视频播放组件不再需要返回DOM，因为我们使用外部传入的ID */
  return null;
};

export default VideoPlayer; 