import React, { useState, useEffect, createContext, useContext } from 'react';
import styled from 'styled-components';
import {
  DashboardContainer,
  Header,
  Content,
  ContentInner,
  ComponentContainer,
  TimeDisplay,
  Footer,
  SecondScreenContentInner,
  ThirdScreenContentInner
} from './components/styled/DashboardStyles';
import HospitalStatusChart from './components/charts/HospitalStatusChart';
import MedicineStatusChart from './components/charts/MedicineStatusChart';
import HourlyTrendChart from './components/charts/HourlyTrendChart';
import TodayForecastTotalChart from './components/charts/TodayForecastTotalChart';
import WindowMonitorChart from './components/charts/WindowMonitorChart';
import PatientMedicineTimeChart from './components/charts/PatientMedicineTimeChart';
import InventoryManagement from './components/charts/InventoryManagement';
import MedicineExpiryChart from './components/charts/MedicineExpiryChart';
import DeviceOverviewChart from './components/charts/DeviceOverviewChart';
import DailyPrescriptionChart from './components/charts/DailyPrescriptionChart';
import DailyMedicineQuantityChart from './components/charts/DailyMedicineQuantityChart';
import PeakHoursChart from './components/charts/PeakHoursChart';
import DualGaugeChart from './components/charts/DualGaugeChart';
import PurpleDualGaugeChart from './components/charts/PurpleDualGaugeChart';
import CyanDualGaugeChart from './components/charts/CyanDualGaugeChart';
import GreenDualGaugeChart from './components/charts/GreenDualGaugeChart';
import PharmacistWorkloadChart from './components/charts/PharmacistWorkloadChart';
import PrescriptionDistributionChart from './components/charts/PrescriptionDistributionChart';
import ConsumedMedicineTop8Chart from './components/charts/ConsumedMedicineTop8Chart';
import PrescriptionBoxDistributionChart from './components/charts/PrescriptionBoxDistributionChart';
import DepartmentPrescriptionTop10Chart from './components/charts/DepartmentPrescriptionTop10Chart';
import DrawerButtons from './components/DrawerButtons';
import { apiGet } from './utils/request'; // 导入请求工具
import { getCurrentDateTime } from './utils/dateUtils'; // 导入日期工具
import AuthCheck from './components/AuthCheck';
import LoadingSpinner from './components/LoadingSpinner';
import AuthTest from './components/AuthTest';
import { useAuth } from './hooks/useAuth';
import './App.css';

// 模块刷新事件前缀
const REFRESH_EVENT_PREFIX = 'refresh-module-';

// 全局刷新事件名称（用于兼容旧代码）
export const GLOBAL_REFRESH_EVENT = 'refresh-dashboard-data';

// 全局默认日期变量，供所有组件使用
export let GLOBAL_DEFAULT_DATE = '';

// 提供一个全局函数来获取默认日期
// 这确保了即使组件在默认日期加载前初始化，也能在需要时获取到正确的日期
export function getDefaultDate() {
  // 如果全局默认日期已设置且不为空，返回它
  if (GLOBAL_DEFAULT_DATE && GLOBAL_DEFAULT_DATE.trim() !== '') {
    return GLOBAL_DEFAULT_DATE;
  }
  // 否则返回当前日期
  return getCurrentDateTime();
}

// 创建日期上下文
interface DateContextType {
  defaultDateTime: string;
  selectedMonth: number;
}

export const DateContext = createContext<DateContextType>({ 
  defaultDateTime: '', 
  selectedMonth: 0 
});

// 提供一个钩子函数，便于组件使用日期上下文
export const useDefaultDate = () => useContext(DateContext);

// 获取基于选择月份的时间范围
export const getSelectedMonthRange = (defaultDateTime: string, selectedMonth: number) => {
  // 修改：优先使用默认时间作为基准，如果没有默认时间才使用当前时间
  // 这样确保第三屏模块也能优先使用默认时间
  const baseDate = defaultDateTime ? new Date(defaultDateTime) : new Date();
  
  // 计算目标月份（当前月减去偏移量）
  const targetDate = new Date(baseDate.getFullYear(), baseDate.getMonth() - selectedMonth, 1);
  const year = targetDate.getFullYear();
  const month = targetDate.getMonth(); // 0-11
  
  // 目标月第一天
  const startDate = new Date(year, month, 1);
  // 目标月最后一天
  const endDate = new Date(year, month + 1, 0);
  
  // 格式化为 YYYY-MM-DD
  const formatDate = (date: Date) => {
    const y = date.getFullYear();
    const m = String(date.getMonth() + 1).padStart(2, '0');
    const d = String(date.getDate()).padStart(2, '0');
    return `${y}-${m}-${d}`;
  };
  
  console.log(`月份选择逻辑 - 基准时间: ${baseDate.toISOString()}, 选择偏移: ${selectedMonth}, 目标月份: ${year}-${String(month + 1).padStart(2, '0')}`);
  
  return {
    startTime: formatDate(startDate),
    endTime: formatDate(endDate)
  };
};

// 简化版：全局刷新函数
export const refreshAllModules = () => {
  const event = new CustomEvent(GLOBAL_REFRESH_EVENT);
  window.dispatchEvent(event);
  console.log('触发全局数据刷新');
};

// 模块配置，包含id和code
export const MODULE_CONFIG = {
  // 第一屏模块
  MEDICINE_STATUS: { id: 'medicine-status', code: '18' }, // 发药状态一览
  TODAY_FORECAST: { id: 'today-forecast', code: '19' }, // 今日预测总量
  HOURLY_TREND: { id: 'hourly-trend', code: '21' }, // 分时趋势
  WINDOW_MONITOR: { id: 'window-monitor', code: '20' }, // 窗口监控
  HOSPITAL_STATUS: { id: 'hospital-status', code: '24' }, // 追溯码情况
  PATIENT_MEDICINE_TIME: { id: 'patient-medicine-time', code: '22' }, // 患者取药时间
  
  // 第二屏模块
  INVENTORY_MANAGEMENT: { id: 'inventory-management', code: '25' }, // 库存管理
  MEDICINE_EXPIRY: { id: 'medicine-expiry', code: '26' }, // 药品效期
  DEVICE_MAINTENANCE: { id: 'device-maintenance', code: '28' }, // 设备保养
  DEVICE_INSPECTION: { id: 'device-inspection', code: '29' }, // 设备巡检
  
  // 第三屏模块
  DAILY_PRESCRIPTION: { id: 'daily-prescription', code: '33' }, // 每周处方概况
  DAILY_MEDICINE_QUANTITY: { id: 'daily-medicine-quantity', code: '34' }, // 每周药品概况  
  DUAL_GAUGE: { id: 'dual-gauge', code: '37' }, // 第2模块：取药效率监控
  PHARMACIST_WORKLOAD: { id: 'pharmacist-workload', code: '42' }, // 药师工作量统计
  PURPLE_DUAL_GAUGE: { id: 'purple-dual-gauge', code: '43' }, // 紫色双仪表盘
  GREEN_DUAL_GAUGE: { id: 'green-dual-gauge', code: '44' }, // 第5模块：绿色双仪表盘（月度转换状态）
  CONSUMED_MEDICINE_TOP8: { id: 'consumed-medicine-top8', code: '41' }, // 消耗药品Top8
  PEAK_HOURS: { id: 'peak-hours', code: '38' }, // 每周高峰时刻
  CYAN_DUAL_GAUGE: { id: 'cyan-dual-gauge', code: '39' }, // 第8模块：青色双仪表盘
  DEPARTMENT_PRESCRIPTION_TOP10: { id: 'department-prescription-top10', code: '40' }, // 科室处方量Top10
  PRESCRIPTION_DISTRIBUTION: { id: 'prescription-distribution', code: '35' }, // 处方品规数分布
  PRESCRIPTION_BOX_DISTRIBUTION: { id: 'prescription-box-distribution', code: '36' } // 处方盒数分布
};

// 添加背景装饰元素
const BackgroundDecorator = styled.div`
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  overflow: hidden;
  z-index: 0;
  
  &::before, &::after {
    content: '';
    position: absolute;
    background-size: contain;
    background-repeat: no-repeat;
    opacity: 0.1;
  }
  
  &::before {
    width: 300px;
    height: 300px;
    top: 10%;
    left: -100px;
    background-image: radial-gradient(circle, rgba(0, 180, 255, 0.3) 0%, rgba(0, 0, 0, 0) 70%);
  }
  
  &::after {
    width: 400px;
    height: 400px;
    bottom: 5%;
    right: -150px;
    background-image: radial-gradient(circle, rgba(0, 255, 200, 0.2) 0%, rgba(0, 0, 0, 0) 70%);
  }
`;

// 底部导航按钮样式
const NavButton = styled.button<{ active: boolean }>`
  background: transparent;
  background-image: url(${props => props.active ? '/tabxuanzhong.png' : '/tabweixuanzhong.png'});
  background-size: 100% 100%;
  background-repeat: no-repeat;
  color: ${props => props.active ? '#0A1433' : '#CCDDFF'};
  display: flex;
  position: relative;
  top:-1.5vw;
  justify-content: center ;
  align-items: center;
  border: none;
  width: 7vw;
  margin: 0 0.2vw;
  font-size: 0.8vw;
  cursor: pointer;
  transition: all 0.3s ease;
  text-align: center;
  
  &:focus {
    outline: none;
  }
`;

// 第二屏左侧按钮容器
const SecondScreenLeftButtons = styled.div`
  position: fixed;
  left: 1vw;
  top: 79%;
  transform: translateY(-50%);
  display: flex;
  flex-direction: column;
  z-index: 1000;
`;

// 第二屏左侧单个按钮
const SecondScreenButton = styled.div<{ isActive: boolean; buttonIndex: number }>`
  width: 1.5vw;
  height: 6vh;
  background-image: ${props => 
    props.isActive 
      ? `url('/侧航左${props.buttonIndex}H.png')` 
      : `url('/侧航左${props.buttonIndex}N.png')`};
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-position: center;
  border: none;
  border-radius: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: ${props => props.isActive ? '#0A1433' : '#CCDDFF'};
  font-size: 0.6vw;
  font-family: 'DingTalk JinBuTi', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  cursor: pointer;
  position: relative;
  padding: 0;
  writing-mode: vertical-lr;
  text-orientation: upright;
  letter-spacing: 0.1vw;
  margin-bottom: -1vh;
  transition: all 0.3s ease;
  
  &:last-child {
    margin-bottom: 0;
  }
`;

// 第三屏左下角月份选择按钮容器
const ThirdScreenMonthButtons = styled.div`
  position: fixed;
  left: 1vw;
  bottom: 7.5vh;
  display: flex;
  flex-direction: column;
  z-index: 1000;
`;

// 第三屏月份选择单个按钮
const MonthSelectButton = styled.div<{ isActive: boolean; isCurrentMonth?: boolean; isBottomButton?: boolean }>`
  width: 1.2vw;
  height: ${props => props.isCurrentMonth ? '6.5vh' : '5.5vh'};
  background: ${props => {
    // 如果是本月按钮
    if (props.isCurrentMonth) {
      return props.isActive ? "url('/side_benyue.png')" : "url('/side_benyue_gray.png')";
    }
    // 如果是最底部按钮
    if (props.isBottomButton) {
      return props.isActive ? "url('/side_bottom_light.png')" : "url('/side_bottom.png')";
    }
    // 其他月份按钮
    return props.isActive ? "url('/side_other_light.png')" : "url('/side_other.png')";
  }};
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
  border-radius: 0.3vw;
  display: flex;
  justify-content: center;
  align-items: center;
  color: ${props => props.isActive ? '#0A1433' : '#CCDDFF'}; /* 修改颜色：选中时为#0A1433，未选中时为#CCDDFF */
  font-size: 0.7vw;
  cursor: pointer;
  font-family:'PingFang SC';
  margin-bottom: -1.5vh;
  writing-mode: vertical-lr; /* 文字竖向排布 */
  text-orientation: upright; /* 文字保持正立 */


  &:hover {
    background: ${props => {
      // 悬浮时，本月按钮
      if (props.isCurrentMonth) {
        return props.isActive ? "url('/side_benyue.png')" : "url('/side_benyue_gray.png')";
      }
      // 悬浮时，最底部按钮
      if (props.isBottomButton) {
        return props.isActive ? "url('/side_bottom_light.png')" : "url('/side_bottom.png')";
      }
      // 悬浮时，其他按钮
      return props.isActive ? "url('/side_other_light.png')" : "url('/side_other.png')";
    }};
    background-size: 100% 100%;
    background-repeat: no-repeat;
    background-position: center;
 
  }
  
  &:last-child {
    margin-bottom: 0;
  }
  
`;

// 默认刷新间隔（毫秒）- 当接口获取失败时使用
const DEFAULT_REFRESH_INTERVAL = 60000; // 默认1分钟

// 刷新时间配置类型
interface RefreshRateItem {
  code: string;
  value: string;
  expandOne?: number; // 屏幕编号字段
  expandTwo?: number; // 第三屏位置字段  
  defaultFlag?: boolean; // 模块显示/隐藏标志
  [key: string]: any;
}

// 设备字典类型
interface EquipDictItem {
  id: number;
  code: string;
  name: string;
  value: string | null;
  type: string;
  defaultFlag: boolean;
  sort: number;
  createUser: string | null;
  createTime: string | null;
  updateUser: string | null;
  updateTime: string;
  deleteUser: string | null;
  deleteTime: string | null;
  delFlag: boolean;
}

const App: React.FC = () => {
  // 鉴权检查
  const { isAuthenticated, isLoading: authLoading, error: authError } = useAuth();
  
  const [currentTime, setCurrentTime] = useState<string>('');
  const [refreshRates, setRefreshRates] = useState<RefreshRateItem[]>([]);
  const [hospitalName, setHospitalName] = useState('药房运营监控');
  const [defaultDateTime, setDefaultDateTime] = useState('');
  const [isLoading, setIsLoading] = useState(true); // 添加加载状态
  const [isDateReady, setIsDateReady] = useState(false); // 添加日期准备状态
  const [currentScreen, setCurrentScreen] = useState<number>(1); // 当前显示的屏幕，1表示第一屏，2表示第二屏
  const [activeSecondScreenButton, setActiveSecondScreenButton] = useState<string>('');
  const [equipDict, setEquipDict] = useState<EquipDictItem[]>([]); // 设备字典数据
  const [selectedMonth, setSelectedMonth] = useState<number>(0); // 选中的月份，0表示本月，1表示上个月，以此类推
  const [showModule6, setShowModule6] = useState<boolean>(true); // 控制第6个模块的显示（默认显示消耗药品Top8）
  const [showModule9, setShowModule9] = useState<boolean>(false); // 控制第9个模块（处方盒数分布）的显示
  const [thirdScreenModules, setThirdScreenModules] = useState<React.ReactNode[]>([]);
  const [forceUpdate, setForceUpdate] = useState<number>(0); // 强制更新计数器 // 第三屏模块动态排列

  // 第三屏模块映射表 - 根据code映射到对应的组件
  const getThirdScreenModuleComponent = (code: string): React.ReactNode => {
    switch (code) {
      case '33': // 每日总方数统计
        return <DailyPrescriptionChart />;
      case '37': // 取药效率监控
        return <DualGaugeChart />;
      case '42': // 药师工作量统计
        return <PharmacistWorkloadChart />;
      case '34': // 每日药品数量概况
        return <DailyMedicineQuantityChart />;
      case '44': // 绿色双仪表盘（月度转换状态）
        return <GreenDualGaugeChart />;
      case '35': // 处方品规数分布
        return <PrescriptionDistributionChart />;
      case '38': // 高峰时刻
        return <PeakHoursChart />;
      case '39': // 青色双仪表盘
        return <CyanDualGaugeChart />;
      case '36': // 处方盒数分布
        return <PrescriptionBoxDistributionChart />;
      case '41': // 消耗药品Top8
        return <ConsumedMedicineTop8Chart />;
      case '43': // 紫色双仪表盘
        return <PurpleDualGaugeChart />;
      case '40': // 科室处方量Top10
        return <DepartmentPrescriptionTop10Chart />;
      default:
        return null;
    }
  };

  // 使用默认的第三屏模块排列（当接口失败时使用）
  const useDefaultThirdScreenArrangement = () => {
    const defaultModules = [
      <ComponentContainer key="default-1"><DailyPrescriptionChart /></ComponentContainer>,
      <ComponentContainer key="default-2"><DualGaugeChart /></ComponentContainer>,
      <ComponentContainer key="default-3"><PharmacistWorkloadChart /></ComponentContainer>,
      <ComponentContainer key="default-4"><DailyMedicineQuantityChart /></ComponentContainer>,
      <ComponentContainer key="default-5"><GreenDualGaugeChart /></ComponentContainer>,
      <ComponentContainer key="default-6"><PrescriptionDistributionChart /></ComponentContainer>,
      <ComponentContainer key="default-7"><PeakHoursChart /></ComponentContainer>,
      <ComponentContainer key="default-8"><CyanDualGaugeChart /></ComponentContainer>,
      <ComponentContainer key="default-9"><PrescriptionBoxDistributionChart /></ComponentContainer>,
    ];
    setThirdScreenModules(defaultModules);
    console.log('使用默认第三屏模块排列');
  };

  // 根据defaultFlag和expandTwo字段排列第三屏模块
  const arrangeThirdScreenModules = (refreshRatesData: RefreshRateItem[]) => {
    console.log('=== arrangeThirdScreenModules 开始执行 ===');
    console.log('接收到的配置数据长度:', refreshRatesData.length);
    
    const moduleComponents: React.ReactNode[] = [];
    
    // 遍历刷新配置数据，根据defaultFlag和expandTwo字段生成模块
    refreshRatesData.forEach((item) => {
      // 首先检查是否是第三屏模块（expandOne=3）且defaultFlag为true
      const isThirdScreen = item.expandOne === 3;
      const shouldDisplay = item.defaultFlag === true && isThirdScreen;
      
      if (shouldDisplay) {
        const position = item.expandTwo || 0;
        // 确保位置在1-9范围内
        if (position >= 1 && position <= 9) {
          const component = getThirdScreenModuleComponent(item.code);
          if (component) {
            // 计算Grid坐标
            const row = Math.floor((position - 1) / 3) + 1;
            const col = ((position - 1) % 3) + 1;
            
            moduleComponents.push(
              <ComponentContainer 
                key={`module-${item.code}-${position}-${Date.now()}`} 
                style={{ 
                  gridArea: `${row} / ${col} / ${row + 1} / ${col + 1}`
                }}
              >
                {component}
              </ComponentContainer>
            );
            
            console.log(`第三屏模块 ${item.code} (expandTwo: ${item.expandTwo}) 放置在Grid位置 ${position}，Grid坐标: 行${row} 列${col}，defaultFlag: ${item.defaultFlag}`);
          }
        } else if (position === 0) {
          // 如果expandTwo为0或未设置，但defaultFlag为true，记录日志但不显示
          console.log(`第三屏模块 ${item.code} defaultFlag为true，但expandTwo未设置有效位置 (${item.expandTwo})`);
        }
      } else {
        if (isThirdScreen) {
          console.log(`第三屏模块 ${item.code} 被隐藏，defaultFlag: ${item.defaultFlag}`);
        }
        // 非第三屏模块不记录日志，避免干扰
      }
    });
    
    // 直接设置模块数组，不依赖位置顺序，完全由grid-area控制
    setThirdScreenModules(moduleComponents);
    
    // 触发强制更新以确保重新渲染
    setForceUpdate(prev => prev + 1);
    
    console.log('第三屏模块排列完成，共', moduleComponents.length, '个模块显示');
    console.log('thirdScreenModules 数组:', moduleComponents.map((comp: any) => comp.key));
    
    // 显示最终的模块配置
    const modulePositions = refreshRatesData
      .filter(item => item.expandOne === 3 && item.defaultFlag === true && (item.expandTwo || 0) >= 1 && (item.expandTwo || 0) <= 9)
      .map(item => ({ code: item.code, position: item.expandTwo || 0 }))
      .sort((a, b) => a.position - b.position);
    
    console.log('模块位置映射:', modulePositions.map(m => `位置${m.position}: code${m.code}`).join(', '));
  };

  // 获取默认日期 - 只在组件挂载时执行一次
  useEffect(() => {
    setIsLoading(true); // 开始加载
    setIsDateReady(false); // 重置日期准备状态
    
    // 初始化默认的第三屏模块排列
    useDefaultThirdScreenArrangement();
    
    // 在进行任何其他操作前，先获取默认日期
    apiGet('/getSysParameter', { params: { parameterCode: 'DEFAULT_DATE' } })
      .then(res => {
        // 检查返回值是否存在且非空
        if (res.data && res.data.data && res.data.data.value && res.data.data.value.trim() !== '') {
          const dateValue = res.data.data.value;
          setDefaultDateTime(dateValue);
          // 更新全局变量，供其他组件使用
          GLOBAL_DEFAULT_DATE = dateValue;
          console.log('获取到默认日期:', dateValue);
        } else {
          // 如果接口返回成功但值为空，将全局变量设置为空字符串
          // 这样getDefaultDate()函数会每次都返回当前时间
          setDefaultDateTime('');
          GLOBAL_DEFAULT_DATE = '';
          console.log('接口返回的日期为空，全局变量设置为空，将使用实时当前时间');
        }
      })
      .catch(error => {
        console.error('获取默认日期失败:', error);
        // 如果接口失败，将全局变量设置为空字符串
        // 这样getDefaultDate()函数会每次都返回当前时间
        setDefaultDateTime('');
        GLOBAL_DEFAULT_DATE = '';
        console.log('接口请求失败，全局变量设置为空，将使用实时当前时间');
      })
      .finally(() => {
        setIsDateReady(true); // 日期已准备好
      });
  }, []);
  
  // 所有其他数据加载都依赖于日期准备好
  useEffect(() => {
    // 只有当日期准备好后，才加载其他数据
    if (!isDateReady) return;
    
    // 获取医院名称
    apiGet('/getSysParameter', { params: { parameterCode: 'HOSPITAL_NAME' } })
      .then(res => {
        if (res.data && res.data.data && res.data.data.value) {
          setHospitalName(res.data.data.value);
        }
      })
      .catch(error => {
        console.error('获取医院名称失败:', error);
      });
      
    // 获取刷新配置
    const fetchRefreshRates = async () => {
      try {
        // 调用获取刷新时间的接口
        const response = await apiGet('/getDict', { params: { dictCode: 'refresh_rate' } });
        if (response.data && response.data.data && Array.isArray(response.data.data)) {
          setRefreshRates(response.data.data);
          console.log('获取到模块刷新时间配置:', response.data.data);
          
          // 过滤出第三屏相关的配置进行调试
          const thirdScreenConfigs = response.data.data.filter((item: RefreshRateItem) => 
            item.expandOne === 3 || (parseInt(item.code) >= 33 && parseInt(item.code) <= 44)
          );
          console.log('第三屏相关配置:', thirdScreenConfigs);
          
          // 根据defaultFlag和expandTwo字段排列第三屏模块
          arrangeThirdScreenModules(response.data.data);
        } else {
          console.warn('刷新时间接口返回格式不符合预期:', response.data);
          // 如果接口失败，使用默认排列
          useDefaultThirdScreenArrangement();
        }
      } catch (error) {
        console.error('获取刷新时间失败:', error);
        // 如果接口失败，使用默认排列
        useDefaultThirdScreenArrangement();
      }
    };

    // 获取设备字典数据
    const fetchEquipDict = async () => {
      try {
        const response = await apiGet('/equipMana/getEquipDict');
        if (response.data && response.data.data && Array.isArray(response.data.data)) {
          const equipData = response.data.data;
          setEquipDict(equipData);
          console.log('获取到设备字典数据:', equipData);
          
          // 如果有设备数据，自动选择第一个设备
          if (equipData.length > 0) {
            const firstEquipCode = equipData[0].code;
            setActiveSecondScreenButton(firstEquipCode);
            console.log('自动选择第一个设备:', firstEquipCode, equipData[0].name);
          }
        } else {
          console.warn('设备字典接口返回格式不符合预期:', response.data);
        }
      } catch (error) {
        console.error('获取设备字典数据失败:', error);
      }
    };

    // 并行获取数据
    Promise.all([fetchRefreshRates(), fetchEquipDict()])
      .finally(() => {
        setIsLoading(false); // 所有数据加载完成
      });
  }, [isDateReady]);

  // 为所有模块设置独立的刷新定时器，而不是统一定时器
  useEffect(() => {
    if (!refreshRates.length) return;
    
    console.log('=== 开始设置模块刷新定时器 ===');
    console.log('refreshRates配置:', refreshRates);
    
    // 检查模块22是否在配置中
    const module22Config = refreshRates.find(item => item.code === '22');
    console.log('🔍 模块22在配置中？', module22Config ? '是' : '否');
    if (module22Config) {
      console.log('🔍 模块22配置详情:', module22Config);
    } else {
      console.log('❌ 模块22不在刷新配置中！这可能是1秒刷新的原因');
    }
    
    // 输出所有模块代码列表
    const allModuleCodes = refreshRates.map(item => item.code);
    console.log('📋 所有模块代码列表:', allModuleCodes);
    
    const timers: number[] = [];
    
    // 为每个模块设置独立的定时器
    refreshRates.forEach(item => {
      const moduleCode = item.code;
      const refreshInterval = Math.max(10, parseInt(item.value) || 60); // 最小10秒，默认60秒
      

      
      // 为每个模块设置独立的定时器
      const timer = setInterval(() => {
        // 触发特定模块的刷新事件
        const moduleRefreshEvent = new CustomEvent(GLOBAL_REFRESH_EVENT, {
          detail: { moduleCode: moduleCode }
        });
        window.dispatchEvent(moduleRefreshEvent);

      }, refreshInterval * 1000);
      
      timers.push(timer);
    });
    
    // 清理所有定时器
    return () => {
      timers.forEach(timer => clearInterval(timer));
    };
  }, [refreshRates]);

  // 更新当前时间
  useEffect(() => {
    const updateTime = () => {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');

      setCurrentTime(`${year}-${month}-${day} ${hours}:${minutes}`);
    };

    updateTime();
    const timer = setInterval(updateTime, 60000);

    return () => clearInterval(timer);
  }, []);

  // 切换屏幕显示
  const handleScreenChange = (screenNum: number) => {
    setCurrentScreen(screenNum);
  };

  // 第二屏按钮点击处理
  const handleSecondScreenButtonClick = (buttonName: string) => {
    setActiveSecondScreenButton(buttonName);
    console.log(`点击了第二屏按钮: ${buttonName}`);
  };

  // 第三屏月份选择处理
  const handleMonthSelect = (monthOffset: number) => {
    setSelectedMonth(monthOffset);
    console.log(`选择了月份偏移: ${monthOffset}`);
    // 触发全局刷新，让所有第三屏组件使用新的月份
    refreshAllModules();
  };

  // 生成月份按钮数据
  const generateMonthButtons = () => {
    const buttons = [];
    // 修复：使用与getSelectedMonthRange相同的基准时间
    const baseDate = defaultDateTime ? new Date(defaultDateTime) : new Date();
    
    for (let i = 0; i < 6; i++) {
      const targetDate = new Date(baseDate.getFullYear(), baseDate.getMonth() - i, 1);
      const year = targetDate.getFullYear();
      const month = targetDate.getMonth() + 1;
      
      let label;
      if (i === 0) {
        label = '本月';
      } else {
        label = `${month}`;
      }
      
      buttons.push({
        offset: i,
        label: label,
        isCurrentMonth: i === 0,
        year: year,
        month: month
      });
    }
    
    return buttons;
  };

  // 渲染第一屏内容
  const renderFirstScreen = () => (
    <ContentInner>
      {/* 容器1 - 发药状态一览 */}
      <ComponentContainer>
        <MedicineStatusChart />
      </ComponentContainer>

      {/* 容器2 - 今日预测总量 */}
      <ComponentContainer>
        <TodayForecastTotalChart />
      </ComponentContainer>

      {/* 容器3 - 分时趋势 */}
      <ComponentContainer>
        <HourlyTrendChart />
      </ComponentContainer>

      {/* 容器4 - 窗口监控 */}
      <ComponentContainer>
        <WindowMonitorChart />
      </ComponentContainer>

      {/* 容器5 - 追溯码情况 */}
      <ComponentContainer>
        <HospitalStatusChart />
      </ComponentContainer>

      {/* 容器6 - 患者取药时间 */}
      <ComponentContainer>
        <PatientMedicineTimeChart />
      </ComponentContainer>
    </ContentInner>
  );

  // 渲染第二屏内容
  const renderSecondScreen = () => (
    <SecondScreenContentInner>
      {/* 第二屏第一个模块 - 库存管理 (左上) */}
      <ComponentContainer>
        <InventoryManagement 
          selectedEquipCode={activeSecondScreenButton}
          selectedEquipName={
            equipDict.find(item => item.code === activeSecondScreenButton)?.name || activeSecondScreenButton
          }
        />
      </ComponentContainer>
      
      {/* 第二屏第二个模块 - 药品效期 (左下) */}
      <ComponentContainer>
        <MedicineExpiryChart 
          selectedEquipCode={activeSecondScreenButton}
          selectedEquipName={
            equipDict.find(item => item.code === activeSecondScreenButton)?.name || activeSecondScreenButton
          }
        />
      </ComponentContainer>
      
      {/* 第二屏第三个模块 - 设备一览 (右侧) */}
      <ComponentContainer>
        <DeviceOverviewChart 
          selectedEquipCode={activeSecondScreenButton}
          selectedEquipName={
            equipDict.find(item => item.code === activeSecondScreenButton)?.name || activeSecondScreenButton
          }
          selectedEquipValue={
            equipDict.find(item => item.code === activeSecondScreenButton)?.value || ''
          }
        />
      </ComponentContainer>
    </SecondScreenContentInner>
  );

  // 渲染第三屏内容 - 使用动态排列的模块
  const renderThirdScreen = () => {
    console.log('renderThirdScreen 被调用，thirdScreenModules.length:', thirdScreenModules.length);
    console.log('当前使用:', thirdScreenModules.length > 0 ? '动态模块' : '默认布局');
    return (
      <ThirdScreenContentInner key={`third-screen-${forceUpdate}`}>
        {thirdScreenModules.length > 0 ? (
          // 直接渲染所有模块，位置完全由每个模块的grid-area样式控制
          thirdScreenModules
        ) : (
        // 如果动态模块还没有加载完成，显示加载状态或使用默认布局
        <>
          <ComponentContainer><DailyPrescriptionChart /></ComponentContainer>
          <ComponentContainer><DualGaugeChart /></ComponentContainer>
          <ComponentContainer><PharmacistWorkloadChart /></ComponentContainer>
          <ComponentContainer><DailyMedicineQuantityChart /></ComponentContainer>
          <ComponentContainer><GreenDualGaugeChart /></ComponentContainer>
          <ComponentContainer><PrescriptionDistributionChart /></ComponentContainer>
          <ComponentContainer><PeakHoursChart /></ComponentContainer>
          <ComponentContainer><CyanDualGaugeChart /></ComponentContainer>
          <ComponentContainer><PrescriptionBoxDistributionChart /></ComponentContainer>
        </>
      )}
    </ThirdScreenContentInner>
    );
  };

  // 如果正在进行鉴权检查，显示加载状态
  if (authLoading) {
    return <LoadingSpinner text="正在验证权限..." />;
  }
  
  // 如果鉴权失败，显示无权限界面
  if (!isAuthenticated) {
    return <AuthCheck>{null}</AuthCheck>;
  }

  return (
    <DashboardContainer>
      <BackgroundDecorator />
      <Header secondScreen={currentScreen === 2} thirdScreen={currentScreen === 3}>
        {/* 院名，左上角显示 */}
        <div style={{
          position: 'absolute',
          left: '2vw',
          top: '68%',
          transform: 'translateY(-50%)',
          borderRadius: '0.4vw',
          padding: '0.3vw 1vw',
          fontSize: '1.5vw',
          color: '#fff',
          fontWeight: 500,
          fontFamily: 'DingTalk JinBuTi',
          letterSpacing: '1px',
          boxShadow: '0 0 6px rgba(0,0,0,0.12)'
        }}>
          {hospitalName}
        </div>
        {/* <h1>本日运营数据</h1> */}
        <TimeDisplay>{currentTime}</TimeDisplay>
      </Header>
      
      {isLoading ? (
        <div style={{
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          height: 'calc(100vh - 10vh)',
          color: '#fff',
          fontSize: '1.5vw'
        }}>
          数据加载中...
        </div>
      ) : (
        <DateContext.Provider value={{ defaultDateTime, selectedMonth }}>
          <Content>
            {currentScreen === 1 ? renderFirstScreen() : 
             currentScreen === 2 ? renderSecondScreen() : 
             renderThirdScreen()}
          </Content>
        </DateContext.Provider>
      )}
      
      {/* 第二屏左侧按钮 - 只有当设备数量大于1时才显示 */}
      {currentScreen === 2 && equipDict.length > 1 && (
        <SecondScreenLeftButtons>
          {/* 根据设备字典数组动态渲染按钮 */}
          {equipDict.map((item, index) => (
            <SecondScreenButton 
              key={item.id}
              isActive={activeSecondScreenButton === item.code} 
              buttonIndex={index + 1}
              onClick={() => handleSecondScreenButtonClick(item.code)}
            >
              {item.name}
            </SecondScreenButton>
          ))}
        </SecondScreenLeftButtons>
      )}
      
      {/* 第三屏左下角月份选择按钮 */}
      {currentScreen === 3 && (
        <ThirdScreenMonthButtons>
          {generateMonthButtons().map((button, index, array) => (
            <MonthSelectButton
              key={button.offset}
              isActive={selectedMonth === button.offset}
              isCurrentMonth={button.isCurrentMonth}
              isBottomButton={index === array.length - 1}
              onClick={() => handleMonthSelect(button.offset)}
            >
              {button.label}
            </MonthSelectButton>
          ))}
        </ThirdScreenMonthButtons>
      )}

      {/* 添加右侧抽屉按钮 */}
      <DrawerButtons currentScreen={currentScreen} equipCode={activeSecondScreenButton} dateTime={defaultDateTime} />
      
      {/* 开发模式鉴权测试工具 */}
      {import.meta.env.DEV && <AuthTest />}
      
      {/* 底部导航 */}
      <Footer>
        <NavButton 
          active={currentScreen === 1}
          onClick={() => handleScreenChange(1)}
        >
          本日数据
        </NavButton>
        <NavButton 
          active={currentScreen === 2}
          onClick={() => handleScreenChange(2)}
        >
          库存/设备
        </NavButton>
        <NavButton 
          active={currentScreen === 3}
          onClick={() => handleScreenChange(3)}
        >
          阶段统计
        </NavButton>
      </Footer>
    </DashboardContainer>
  );
};

export default App;
