import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import classNames from 'classnames';
import { message } from 'antd';
import VideoPlayer from '../VideoPlayer';
import styles from './index.less';
import services from '@/services';
import { useDashboard } from '../context';
import { useGlobalModalServices } from '@/pages/GlobalModalServices/provider';

// 视频分类类型定义
type VideoType = '1' | '2' | '3' | '4'; // 分类(1-农贸市场，2-背街小巷，3-重点区域，4-地铁口)
type VideoTypeMap = Record<VideoType, string>;

// 视频分类名称映射
const videoTypeNames: VideoTypeMap = {
  '1': '农贸市场',
  '2': '背街小巷',
  '3': '重点区域',
  '4': '地铁口'
};

// 视频分类对应页面ID映射
const videoTypePageMap: Record<VideoType, string> = {
  '1': 'videoFarmersMarket',
  '2': 'videoBackStreets',
  '3': 'videoKeyAreas',
  '4': 'videoSubwayEntrances'
};

// 定义固定的播放窗口ID
const PLAYER_IDS: Record<VideoType, string> = {
  '1': 'playWnd_nongmao',
  '2': 'playWnd_beijie',
  '3': 'playWnd_zhongdian',
  '4': 'playWnd_ditie'
};

// 定义视频项接口
interface VideoItem {
  id: string;
  title: string;
  deviceId: string; // cameraIndexCode
  type: VideoType;
}

// 后端返回的视频数据接口
interface CameraClassificationVO {
  cameraIndexCode: string;
  cameraName: string;
  cameraPinyin: string;
  directoryName: string;
  directoryPath: string;
  type: string;
}

// 分类后的视频列表类型
type CategoryVideos = Record<VideoType, VideoItem[]>;

const VideoCarousel: React.FC = () => {
  // 所有视频数据（分类后）
  const [categoryVideos, setCategoryVideos] = useState<CategoryVideos>({
    '1': [],
    '2': [],
    '3': [],
    '4': []
  });
  const showVideo = true;
  
  // 当前活动的设备ID
  const [activeDeviceId, setActiveDeviceId] = useState<string>('');
  
  // 记录需要销毁的播放器ID
  const [destroyPlayerType, setDestroyPlayerType] = useState<VideoType | null>(null);
  const [triggerDestroy, setTriggerDestroy] = useState<boolean>(false);
  
  // 当前类型下的活动视频索引
  const [activeVideoIndices, setActiveVideoIndices] = useState<Record<VideoType, number>>({
    '1': 0,
    '2': 0,
    '3': 0,
    '4': 0
  });
  
  const [playerInitialized, setPlayerInitialized] = useState<boolean>(false);
  const [autoRotate, setAutoRotate] = useState<boolean>(true);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  
  // 跟踪播放器实例是否已经初始化
  const [playersReady, setPlayersReady] = useState<Record<VideoType, boolean>>({
    '1': false,
    '2': false,
    '3': false,
    '4': false
  });
  
  // 获取页面切换状态
  const { activePage, isTransitioning, transitionDirection, navigateTo } = useDashboard();
  const isHomePage = activePage === 'home';
  const prevIsHomePageRef = useRef<boolean>(true);
  
  // 是否正在销毁播放器
  const [isDestroying, setIsDestroying] = useState<boolean>(false);
  
  // 跟踪播放器实例的引用
  const playerInstancesRef = useRef<Record<VideoType, boolean>>({
    '1': false,
    '2': false,
    '3': false, 
    '4': false
  });
  
  // 跟踪正在销毁的播放器
  const destroyingPlayersRef = useRef<Set<VideoType>>(new Set());
  
  // 获取弹窗服务
  const { dispatch } = useGlobalModalServices();
  
  // 获取指定类型的视频列表数据
  const getVideoData = useCallback(async (type: VideoType) => {
    try {
      setIsLoading(true);
      console.log(`获取类型 ${type} 的视频数据`);
      
      const res = await services.DataBase.getGzInfoData({
        typeCode: 'gz-spsbxx',
        "data": {
          "current": 1,
          "size": 100,
          "type": type // 使用传入的type参数
        }
      });
      
      if (res && res.records) {
        // console.log(`获取类型 ${type} 的视频数据成功:`, res.records);
        
        // 处理该类型的视频数据
        const typedVideos: VideoItem[] = [];
        
        if (Array.isArray(res.records)) {
          res.records.forEach((item: CameraClassificationVO, index: number) => {
            typedVideos.push({
              id: `${type}-${index}`,
              title: item.cameraName || videoTypeNames[type],
              deviceId: item.cameraIndexCode,
              type: type
            });
          });
        }
        
        // console.log(`类型 ${type} 处理后的视频数据:`, typedVideos);
        
        // 更新该类型的视频列表
        setCategoryVideos(prev => ({
          ...prev,
          [type]: typedVideos
        }));
        
        // 如果没有设置过活动设备ID且当前类型有视频，则设置第一个视频为活动视频
        if (!activeDeviceId && typedVideos.length > 0) {
          setActiveDeviceId(typedVideos[0].deviceId);
        }
        
        return typedVideos;
      } else {
        console.error(`获取类型 ${type} 的视频数据失败:`, res);
        message.error(`获取类型 ${type} 的视频数据失败`);
        return [];
      }
    } catch (error) {
      console.error(`获取类型 ${type} 的视频数据异常:`, error);
      message.error(`获取类型 ${type} 的视频数据发生异常`);
      return [];
    } finally {
      setIsLoading(false);
    }
  }, [activeDeviceId]);
  
  // 初始化时获取所有类型的视频数据
  useEffect(() => {
    const fetchAllTypeVideos = async () => {
      setIsLoading(true);
      
      // 并行获取所有类型的视频数据
      const types: VideoType[] = ['1', '2', '3', '4'];
      await Promise.all(types.map(type => getVideoData(type)));
      
      setIsLoading(false);
    };
    
    // 只在组件挂载时执行一次
    fetchAllTypeVideos();
  }, []); // 空依赖数组确保只执行一次
  
  // 强制手动隐藏所有播放器
  const hideAllPlayers = useCallback(() => {
    console.log('隐藏所有播放器');
    setIsDestroying(true);
    
    // 先隐藏所有播放器容器
    const types: VideoType[] = ['1', '2', '3', '4'];
    types.forEach(type => {
      const playerId = PLAYER_IDS[type];
      const container = document.getElementById(playerId);
      if (container) {
        container.style.visibility = 'hidden';
      }
    });
    
    // 全部标记为隐藏
    setTriggerDestroy(true);
    
    // 设置所有类型为正在隐藏状态
    types.forEach(type => {
      destroyingPlayersRef.current.add(type);
    });
    
    // 500ms后重置隐藏状态标志（但播放器仍然保持隐藏）
    setTimeout(() => {
      setIsDestroying(false);
      destroyingPlayersRef.current.clear();
    }, 500);
  }, []);
  
  // 显示所有播放器
  const showAllPlayers = useCallback(() => {
    // 如果当前不是首页，不执行操作
    if (!isHomePage) return;
    
    console.log('显示所有播放器');
    
    // 重置隐藏状态
    setTriggerDestroy(false);
    
    // 显示所有播放器容器
    const types: VideoType[] = ['1', '2', '3', '4'];
    types.forEach(type => {
      const playerId = PLAYER_IDS[type];
      const container = document.getElementById(playerId);
      if (container) {
        container.style.visibility = 'visible';
      }
    });
    
    // 标记所有播放器为未初始化状态，以便重新初始化
    setPlayersReady({
      '1': false,
      '2': false,
      '3': false,
      '4': false
    });
    
    setPlayerInitialized(false);
  }, [isHomePage]);
  
  // 监听页面切换，非首页时隐藏播放器
  useEffect(() => {
    // 检测是否正在从首页切换到其他页面
    const isLeavingHome = prevIsHomePageRef.current && !isHomePage;
    
    if (isLeavingHome && !isDestroying) {
      console.log('正在离开首页，提前隐藏所有播放器');
      hideAllPlayers();
    } else if (isHomePage && !prevIsHomePageRef.current && !isDestroying) {
      // 如果是从其他页面返回首页
      console.log('返回首页，准备显示播放器');
      showAllPlayers();
      
      // 从餐饮油烟页面返回时，重新获取视频列表数据
      console.log('返回首页，重新获取视频列表数据');
      const types: VideoType[] = ['1', '2', '3', '4'];
      types.forEach(type => getVideoData(type));
    }
    
    // 更新上一次的状态
    prevIsHomePageRef.current = isHomePage;
  }, [isHomePage, isDestroying, hideAllPlayers, showAllPlayers, getVideoData]);
  
  // 监听过渡动画开始，提前隐藏播放器
  useEffect(() => {
    if (isTransitioning && transitionDirection === 'out' && !isDestroying) {
      console.log('检测到页面过渡动画开始，立即隐藏所有播放器');
      hideAllPlayers();
    }
  }, [isTransitioning, transitionDirection, isDestroying, hideAllPlayers]);
  
  // 组件卸载时清理
  useEffect(() => {
    return () => {
      console.log('VideoCarousel组件卸载，隐藏所有播放器');
      hideAllPlayers();
    };
  }, [hideAllPlayers]);
  
  // 计算当前窗口比例，用于调整播放器大小
  const calculateRatio = useCallback(() => {
    // 默认设计尺寸
    const designWidth = 3840;
    const designHeight = 1080;
    
    // 获取当前窗口尺寸
    const currentWidth = window.innerWidth;
    const currentHeight = window.innerHeight;
    
    // 计算缩放比例
    const widthRatio = currentWidth / designWidth;
    const heightRatio = currentHeight / designHeight;
    const scaleRatio = Math.min(widthRatio, heightRatio);
    
    // 返回最小的比例值，确保不超出视口
    return scaleRatio;
  }, []);
  
  // 当窗口大小变化时更新ratio
  const [ratio, setRatio] = useState(() => calculateRatio());
  
  // 监听窗口大小变化
  useEffect(() => {
    const handleResize = () => {
      setRatio(calculateRatio());
    };
    
    window.addEventListener('resize', handleResize);
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, [calculateRatio]);
  
  // 自动旋转各类型的视频
  useEffect(() => {
    if (!autoRotate || !isHomePage) return;
    
    console.log('启动视频自动轮播，时间间隔: 30秒');
    
    // 为每种类型的视频设置自动轮播
    const rotationInterval = setInterval(() => {
      console.log('执行自动视频轮播...');
      
      // 检查是否所有播放器都初始化完成
      const allInitialized = Object.values(playersReady).every(ready => ready);
      if (!allInitialized) {
        console.log('部分播放器未初始化完成，暂不执行自动轮播');
        return;
      }
      
      setActiveVideoIndices(prevIndices => {
        const newIndices = { ...prevIndices };
        let logMessage = '轮播视频索引变化:';
        
        // 对每个类型，如果该类型有视频，则切换到下一个
        Object.keys(categoryVideos).forEach((type) => {
          const typedType = type as VideoType;
          const videos = categoryVideos[typedType];
          if (videos.length > 0) {
            const oldIndex = newIndices[typedType];
            newIndices[typedType] = (oldIndex + 1) % videos.length;
            logMessage += ` ${videoTypeNames[typedType]}: ${oldIndex} -> ${newIndices[typedType]},`;
          }
        });
        
        console.log(logMessage);
        return newIndices;
      });
      
      // 更新当前活动设备ID为当前正在播放的视频设备ID
      let activeVideoUpdated = false;
      const typeKeys = Object.keys(categoryVideos) as VideoType[];
      for (const type of typeKeys) {
        const videos = categoryVideos[type];
        if (videos.length > 0) {
          const currentIndex = activeVideoIndices[type];
          const targetVideo = videos[currentIndex];
          if (targetVideo) {
            console.log(`切换到${videoTypeNames[type]}的第${currentIndex + 1}个视频: ${targetVideo.title}`);
            setActiveDeviceId(targetVideo.deviceId);
            activeVideoUpdated = true;
            break;
          }
        }
      }
      
      if (!activeVideoUpdated) {
        console.log('未找到可切换的视频');
      }
    }, 30000); // 30秒切换一次
    
    return () => {
      console.log('清除视频轮播定时器');
      clearInterval(rotationInterval);
    };
  }, [categoryVideos, autoRotate, isHomePage, playersReady, activeVideoIndices, videoTypeNames]);
  
  // 处理视频初始化完成
  const handlePlayerInitialized = (success: boolean, type: VideoType) => {
    const typeString = videoTypeNames[type] || type;
    
    // 避免重复初始化标记
    if (playersReady[type] === true && success) {
      console.log(`播放器 ${typeString} 已经初始化过，忽略重复回调`);
      return;
    }
    
    console.log(`播放器 ${typeString} 初始化${success ? '成功' : '失败'}`);
    
    if (success) {
      setPlayersReady(prev => ({
        ...prev,
        [type]: true
      }));
      
      playerInstancesRef.current[type] = true;
      
      // 检查是否所有播放器都初始化完成
      const initializedPlayers = Object.keys(playersReady).filter(k => 
        (playersReady as any)[k] === true || (k === type && success)
      ).length;
      
      const totalPlayers = Object.keys(playersReady).length;
      console.log(`播放器初始化进度: ${initializedPlayers}/${totalPlayers}`);
      
      // 如果所有播放器都初始化完成，设置总状态为已初始化
      if (initializedPlayers === totalPlayers) {
        setPlayerInitialized(true);
        console.log('所有播放器初始化完成');
      }
    } else {
      console.error(`播放器 ${typeString} 初始化失败`);
    }
  };
  
  // 处理点击视频 - 导航到对应分类页面
  const handleVideoClick = (deviceId: string, type: VideoType) => {
    console.log('视频点击:', deviceId, type);
    
    // 如果点击了不同的视频类型，先将当前视频标记为需要销毁
    if (type !== destroyPlayerType) {
      // 标记上一个播放器类型为需要销毁
      setDestroyPlayerType(type);
      
      // 200ms后重置销毁标记，让组件能够再次接收销毁信号
      setTimeout(() => {
        setDestroyPlayerType(null);
      }, 200);
    }
    
    // 更新当前活动的设备ID
    setActiveDeviceId(deviceId);
    
    // 导航到对应的视频分类页面
    const targetPage = videoTypePageMap[type];
    if (targetPage) {
      navigateTo(targetPage);
    }
  };

  // 获取每种类型的第一个视频（用于四宫格展示）
  const getTypeVideo = (type: VideoType): VideoItem | null => {
    const videos = categoryVideos[type];
    if (!videos || videos.length === 0) return null;
    
    const index = activeVideoIndices[type];
    return videos[index];
  };

  // 四个类型的视频
  const video1 = getTypeVideo('1');
  const video2 = getTypeVideo('2');
  const video3 = getTypeVideo('3');
  const video4 = getTypeVideo('4');

  // 计算播放器尺寸
  const titleWidth = 60; // 标题区域宽度
  const playerWidth = useMemo(() => {
    return Math.floor((357 - titleWidth) * ratio);
  }, [ratio]);
  
  const playerHeight = useMemo(() => {
    return Math.floor(207 * ratio);
  }, [ratio]);

  // 渲染单个视频窗口的函数
  const renderVideoWindow = (type: VideoType, video: VideoItem | null, isActive: boolean | null) => {
    // 确定当前视频窗口是否需要隐藏
    const shouldHide = type === destroyPlayerType || triggerDestroy || !isHomePage;
    const isBeingDestroyed = destroyingPlayersRef.current.has(type);
    
    return (
      <div 
        className={classNames(styles.videoItem, { [styles.active]: !!isActive })}
        onClick={() => video && handleVideoClick(video.deviceId, type)}
      >
        <div className={styles.videoThumbnail}>
          {/* 左侧标题区域 */}
          <div className={styles.titleArea}>
            <div className={styles.videoTitle}>
              {videoTypeNames[type]}
            </div>
          </div>
          
          {/* 右侧海康播放器容器 */}
          <div className={styles.playerWrapper}>
            <div id={PLAYER_IDS[type]} className={styles.playerContainer}></div>
          </div>
          
          {/* 视频播放器组件 - 即使不可见也保持实例存在，只是隐藏显示 */}
          {showVideo && video && (
            <VideoPlayer 
              deviceId={video.deviceId}
              playerId={PLAYER_IDS[type]}
              visible={isHomePage}
              hide={shouldHide}
              width={playerWidth}
              height={playerHeight}
              onInitialized={(success) => handlePlayerInitialized(success, type)}
              onError={(err) => console.error(`Video player ${type} error:`, err)}
            />
          )}
        </div>
      </div>
    );
  };

  return (
    <div className={styles.container}>
      {/* 重点区域 */}
      {renderVideoWindow('3', video3, video3 && video3.deviceId === activeDeviceId)}
      
      {/* 背街小巷 */}
      {renderVideoWindow('2', video2, video2 && video2.deviceId === activeDeviceId)}
      
      {/* 农贸市场 */}
      {renderVideoWindow('1', video1, video1 && video1.deviceId === activeDeviceId)}
      
      {/* 地铁口 */}
      {renderVideoWindow('4', video4, video4 && video4.deviceId === activeDeviceId)}
    </div>
  );
};

export default VideoCarousel; 