import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { Space, Pagination } from 'antd';
import VideoPlayer from '@/pages/Home_v_2504/components/VideoPlayer';
import services from '@/services';
import styles from './index.less';
import { ChildrenModalMethods } from '@/pages/GlobalModalServices/type';
import { useGlobalModalServices } from '@/pages/GlobalModalServices/provider';

interface VideoInfo {
  id: string;
  title: string;
  deviceId: string;
  type: string;
}

interface VideoModalProps {
  title?: string;
  locationName?: string;
  deviceIds?: string[];
  videoType?: '1' | '2' | '3' | '4'; // 1-农贸市场，2-背街小巷，3-重点区域，4-地铁口
  modalDispatch?: ChildrenModalMethods;
}

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

const VideoModal: React.FC<VideoModalProps> = ({ 
  title, 
  locationName, 
  deviceIds = [], 
  videoType = '3',
  modalDispatch 
}) => {
  // 布局模式: 9分屏 or 4分屏
  const [layoutMode, setLayoutMode] = useState<'nine' | 'four'>('nine');
  
  // 视频数据
  const [videos, setVideos] = useState<VideoInfo[]>([]);
  
  // 加载状态
  const [loading, setLoading] = useState(true);
  
  // 播放器状态跟踪
  const [playersInitialized, setPlayersInitialized] = useState<Record<string, boolean>>({});
  
  // 分页状态
  const [currentPage, setCurrentPage] = useState(1);
  const { dispatch } = useGlobalModalServices();

  // 计算当前窗口比例，用于调整播放器大小
  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<number>(1);
  
  useEffect(() => {
    const updateRatio = () => {
      setRatio(calculateRatio());
    };
    
    // 初始更新
    updateRatio();
    
    // 监听窗口大小变化
    window.addEventListener('resize', updateRatio);
    return () => {
      window.removeEventListener('resize', updateRatio);
    };
  }, [calculateRatio]);

  // 根据布局模式获取视频显示数量和尺寸
  const getLayoutConfig = useMemo(() => {
    let isDebug = true;
    let debugRatio = isDebug ? 0.9 : 1;
    if (layoutMode === 'nine') {
      return {
        count: 9,
        width: Math.floor(390 * ratio * debugRatio) ,
        height: Math.floor(219 * ratio),
        horizontalGap: 10,
        verticalGap: 10,
        containerClass: styles.nineScreenLayout
      };
    } else {
      return {
        count: 4,
        width: Math.floor(581 * ratio * debugRatio) ,
        height: Math.floor(327 * ratio),
        horizontalGap: 17,
        verticalGap: 15,
        containerClass: styles.fourScreenLayout
      };
    }
  }, [layoutMode, ratio]);

  // 获取视频数据
  const fetchVideoData = async () => {
    try {
      setLoading(true);
      
      // 如果传入了deviceIds，则使用这些设备ID
      if (deviceIds && deviceIds.length > 0) {
        const mappedVideos = deviceIds.map((deviceId, index) => ({
          id: `video-${index}`,
          title: `${locationName || videoTypeNames[videoType] || '监控'} ${index + 1}`,
          deviceId: deviceId,
          type: videoType
        }));
        setVideos(mappedVideos);
        setLoading(false);
        return;
      }
      
      // 否则从API获取视频列表
      const res = await services.DataBase.getGzInfoData({
        typeCode: 'gz-spsbxx',
        "data": {
          "current": 1,
          "size": 20,
          "type": videoType
        }
      });
      
      if (res && res.records) {
        const mappedVideos = res.records.map((item: any, index: number) => ({
          id: `video-${index}`,
          title: item.cameraName || `${videoTypeNames[videoType] || '监控'} ${index + 1}`,
          deviceId: item.cameraIndexCode,
          type: videoType
        }));
        setVideos(mappedVideos);
      }
    } catch (error) {
      console.error('获取视频数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 初始化时获取视频数据
  useEffect(() => {
    fetchVideoData();
  }, [videoType]);
// }, [videoType, deviceIds]);
  
  // 处理播放器初始化完成
  const handlePlayerInitialized = (success: boolean, index: number) => {
    if (success) {
      setPlayersInitialized(prev => ({
        ...prev,
        [`player_${index}`]: true
      }));
      
      console.log(`视频播放器 ${index} 初始化成功`);
    } else {
      console.error(`视频播放器 ${index} 初始化失败`);
    }
  };

  // 初始化时设置顶部自定义按钮
  useEffect(() => {
    if (modalDispatch) {
      modalDispatch.setOptions({
        headerRight: () => {
          return (
            <Space size={9} style={{ marginRight: '40px' }}>
              <div 
                className={`${styles.layoutTab} ${layoutMode === 'nine' ? styles.activeTab : ''}`}
                onClick={() => setLayoutMode('nine')}
              >
                九分屏
              </div>
              <div 
                className={`${styles.layoutTab} ${layoutMode === 'four' ? styles.activeTab : ''}`}
                onClick={() => setLayoutMode('four')}
              >
                四分屏
              </div>
            </Space>
          );
        },
      });
    }
  }, [layoutMode]);
  
  // 处理分页变化
  const handlePageChange = (page: number) => {
    setCurrentPage(page);
    
    // 切换页面时重置播放器初始化状态
    setPlayersInitialized({});
  };
  
  // 计算总页数
  const totalPages = Math.ceil(videos.length / getLayoutConfig.count);
  
  // 获取当前页的视频
  const getCurrentPageVideos = () => {
    const startIndex = (currentPage - 1) * getLayoutConfig.count;
    return videos.slice(startIndex, startIndex + getLayoutConfig.count);
  };
  
  // 根据当前配置和分页获取要显示的视频
  const displayVideos = getCurrentPageVideos();
  
  // 处理视频点击 - 打开单个视频详情弹窗
  const handleVideoClick = (video: VideoInfo) => {
    if (!modalDispatch) return;
    
    // dispatch.push('SingleVideoModal', {
    modalDispatch.push('SingleVideoModal', {
      title: `${video.title} - 详情`,
      props: {
        deviceId: video.deviceId,
        videoTitle: video.title,
        videoType: video.type
      }
    }, 2); // 传入1表示是二级弹窗
  };

  return (
    <div className={styles.videoModalContainer}>
      <div className={getLayoutConfig.containerClass}>
        {displayVideos.map((video, index) => (
          <div 
            key={video.id} 
            className={styles.videoItem}
            onClick={() => handleVideoClick(video)}
          >
            <div className={styles.videoTitle}>{video.title}</div>
            <div className={styles.videoPlayerContainer} id={`playWnd_modal_${index}`}>
              <VideoPlayer
                deviceId={video.deviceId}
                playerId={`playWnd_modal_${index}`}
                visible={true}
                width={getLayoutConfig.width}
                height={getLayoutConfig.height}
                onInitialized={(success) => handlePlayerInitialized(success, index)}
                onError={(err) => console.error(`视频播放错误:`, err)}
              />
            </div>
          </div>
        ))}
        
        {/* 补充空占位，保持布局完整 */}
        {displayVideos.length < getLayoutConfig.count && (
          Array.from({ length: getLayoutConfig.count - displayVideos.length }).map((_, index) => (
            <div key={`placeholder-${index}`} className={styles.videoItem}>
              <div className={styles.videoTitle}>未连接</div>
              <div 
                className={styles.emptyPlayer}
                style={{ 
                  width: getLayoutConfig.width, 
                  height: getLayoutConfig.height 
                }}
              >
                <span>未连接</span>
              </div>
            </div>
          ))
        )}
      </div>
      
      {/* 分页控件 */}
      {videos.length > getLayoutConfig.count && (
        <div className={styles.paginationContainer}>
          <Pagination 
            current={currentPage}
            total={videos.length}
            pageSize={getLayoutConfig.count}
            onChange={handlePageChange}
            showSizeChanger={false}
            size="small"
          />
        </div>
      )}
    </div>
  );
};

export default VideoModal; 