import React, { useEffect, useState, useCallback } from 'react';
import ReactECharts from 'echarts-for-react';
import * as echarts from 'echarts';
import { PanelContainer, PanelTitle, ChartContainer } from '../styled/DashboardStyles';
import styled from 'styled-components';
import { getMockDailyPatientData, getMockDoctorData } from '../../utils/mockData';
import { apiGet } from '../../utils/request'; // 引入统一接口请求方法
import { getDefaultDate } from '../../App'; // 导入获取默认日期的函数
import { formatToMonthDay } from '../../utils/dateUtils'; // 从日期工具文件导入
import { GLOBAL_REFRESH_EVENT } from '../../App'; // 导入全局刷新事件
import useGlobalRefresh from '../../hooks/useGlobalRefresh';
import { useRefreshConfig } from '../../hooks/useRefreshConfig';

// 面板容器
const TraceabilityPanel = styled(PanelContainer)`
  height: 100%;
  padding: 0;
  position: relative;
  border-radius: 0.25vw;
`;

// 组件标题，字体大小自适应
const PanelHeader = styled.div<{fontSize: number}>`
  position: relative;
  width: 65%;
  height: 1.6vw;
  padding-left:4%;
  text-align: left;
  line-height: 1.6vw;
  font-size: 0.8vw;
  color: #fff;
  font-family: 'DingTalk JinBuTi', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  /* 去除加粗，按需自适应 */
  /* font-weight: bold; */
  background: url('/component_header_bg.png') no-repeat;
  background-size: 100% 100%;
`;

// 双面板布局样式
const DualPanelLayout = styled.div`
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 2vw; // 增加中间间距
  height: calc(100% - 1.6vw);
  align-items: stretch;
  
  @media (max-width: 1200px) {
    grid-template-columns: 1fr;
    grid-template-rows: 1fr 1fr;
  }
`;

// 单个图表容器
const ChartBox = styled.div`
  height: 100%;
  width: 100%;
  position: relative;
  padding: 0.5vw 0 0.5vw;
  display: flex;
  flex-direction: column;
  
  @media (max-width: 1200px) {
    padding: 0.25vw 0.25vw 0.25vw;
  }
  
  .chart-container {
    flex: 1;
    display: flex;
    flex-direction: column;
  }
`;

// 图表标题，字体大小自适应
const ChartTitle = styled.div<{fontSize: number}>`
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 1.875vw;
  padding: 0 0;
  margin-bottom: 0.5vw;
  overflow: hidden;
  
  @media (max-width: 768px) {
    height: auto;
    padding: 0.25vw 0.5vw;
    flex-direction: column;
    align-items: flex-start;
  }
  
  .title-text {
    font-size: ${props => props.fontSize}px;
    color: #fff;
    font-weight: bold;
    white-space: nowrap;
    min-width: 6vw;
    
    @media (max-width: 768px) {
      margin-bottom: 0.25vw;
      margin-right: 0;
    }
  }
`;

// 图例样式，字体大小自适应
const Legend = styled.div`
  display: flex;
  justify-content: flex-end;
  gap: 0.5vw;
  flex-wrap: nowrap;
  overflow: hidden;
  padding-right: 0%;
  
  @media (max-width: 768px) {
    flex-wrap: wrap;
    justify-content: flex-start;
    gap: 0.5vw;
  }
`;

// 图例样式，字体大小自适应
const LegendItem = styled.div<{fontSize?: number, blockWidth?: number, blockHeight?: number}>`
  display: flex;
  align-items: center;
  font-size: ${props => props.fontSize ? props.fontSize + 'px' : '12px'};
  color: #CCE6FF;
  white-space: nowrap;
  
  @media (max-width: 576px) {
    font-size: 0.625vw;
  }
  
  .color-block {
    width: ${props => props.blockWidth ? props.blockWidth + 'px' : '12px'};
    height: ${props => props.blockHeight ? props.blockHeight + 'px' : '12px'};
    margin-right: 0.2vw;
    
    @media (max-width: 576px) {
      width: 0.375vw;
      height: 0.375vw;
      margin-right: 0.125vw;
    }
  }
  
  &.blue .color-block {
    background: linear-gradient(to bottom, #66B3FF, rgba(102,179,255,0));
  }
  
  &.pink .color-block {
    background: linear-gradient(to bottom, #FF99AA, rgba(255,153,170,0));
  }
  
  &.green .color-block {
    background: linear-gradient(to bottom, #99FFAA, rgba(153,255,170,0));
  }
`;

// 就诊进度一览样式组件
const ProgressOverviewContainer = styled.div`
  width: 100%;
  height: calc(100% - 1.6vw);
  display: flex;
  gap: 0.5vw;
  margin-top: 1vw;
  box-sizing: border-box;
`;

const ProgressCard = styled.div`
  flex: 1;
  background: transparent;
 
  display: flex;
  flex-direction: column;
  height: 100%;
  box-sizing: border-box;
`;

const ProgressCardHeader = styled.div`
  display: flex;
  align-items: center;
  margin-bottom: 0.3vw;
  flex-shrink: 0;
  width: 100%;
`;

const ProgressCardIcon = styled.div`
  width: 1vw;
  height: 1vw;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  filter: brightness(1.2);
  flex-shrink: 0;
`;

const ProgressCardRight = styled.div`
  display: flex;
  align-items: center;
  gap: 0.5vw;
  flex: 1;
  margin-left:0.5vw;
`;

const ProgressCardTitleContainer = styled.div`
  display: flex;
  align-items: center;
  gap: 0.5vw;
`;

const ProgressCardTitle = styled.div`
  font-size: 0.65vw;
  color: #CCE6FF;
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  line-height: 1.2;
  white-space: nowrap;
`;

const ProgressCardDecorator = styled.div`
  width: 6vw;
  height: 1vw;
  margin-left: 2vw;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
`;

const ProgressCardValueRow = styled.div`
  width: 100%;
  margin-bottom: 0.8vw;
`;

const ProgressCardValue = styled.div`
  font-size: 1vw;
  color: #FFFFFF;
  font-weight: bold;
  font-family: 'DingTalk JinBuTi', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  line-height: 1;
  text-align: left;
  padding-left: 1.5vw;  
`;

const DepartmentList = styled.div<{ backgroundImage?: string }>`

  display: flex;
  flex-direction: column;
  gap: 0.1vw;
  background-image: ${props => props.backgroundImage ? `url('${props.backgroundImage}')` : 'none'};
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
  overflow: hidden;
  padding: 0.3vw 0.8vw;
`;

const DepartmentItem = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 1.2vw;
  flex-shrink: 0;
`;

const DepartmentName = styled.div`
  font-size: 0.6vw;
  color: #CCE6FF;
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  width: 4vw;
  text-align: left;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
`;

const DepartmentProgressContainer = styled.div`
  flex: 1;
  display: flex;
  align-items: center;
  margin: 0 0.6vw;
`;

const DepartmentProgressBar = styled.div<{ percentage: number }>`
  flex: 1;
  height: 0.25vw;
  border-radius: 0.05vw;
  position: relative;
  overflow: hidden;
  
  &::after {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    height: 100%;
    width: ${props => props.percentage}%;
    background: linear-gradient(90deg, #65CCFF 0%, #CBEEFF 100%);
    border-radius: 0.05vw;
    transition: width 0.8s ease;
  }
`;

const DepartmentValue = styled.div`
  font-size: 0.6vw;
  color: #FFFFFF;
  font-family: 'DingTalk JinBuTi', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  font-weight: bold;
  width: 1.8vw;
  text-align: right;
`;

// 科室数据类型
interface DepartmentProgressItem {
  departmentName: string;
  count: number;
  percentage: number;
}

// 就诊进度数据类型
interface ProgressData {
  waitingVisit: {
    total: number;
    departments: DepartmentProgressItem[];
  };
  waitingPayment: {
    total: number;
    departments: DepartmentProgressItem[];
  };
  waitingMedicine: {
    total: number;
    departments: DepartmentProgressItem[];
  };
}

const HospitalStatusChart: React.FC = () => {
  // 1. 自适应字体 hooks 必须放在组件内部
  const [axisFontSize, setAxisFontSize] = useState(10); // 坐标轴字体
  const [legendFontSize, setLegendFontSize] = useState(12); // 图例字体
  const [legendBlockWidth, setLegendBlockWidth] = useState(12); // 图例色块宽度
  const [legendBlockHeight, setLegendBlockHeight] = useState(6); // 图例色块高度
  const [barRadius, setBarRadius] = useState(4); // 柱状图圆角

  // 获取刷新配置，模块code为'24'
  const { defaultFlag } = useRefreshConfig('24');
  
  // 就诊进度数据状态
  const [progressData, setProgressData] = useState<ProgressData>({
    waitingVisit: {
      total: 0,
      departments: []
    },
    waitingPayment: {
      total: 0,
      departments: []
    },
    waitingMedicine: {
      total: 0,
      departments: []
    }
  });

  // 2. 定义接口数据类型，mock数据和useMock变量，全部放到组件内部
  interface InputStat {
    inputDate: string;
    totalInputQty: number;
    inputTraceableCodeCount: number;
    inputRatio: number;
  }
  interface OutputStat {
    outputDate: string;
    totalDispensedCount: number;
    traceableCodeCount: number;
    outputRatio: number;
  }
  interface TraceableCodeStatsRes {
    inputStats: InputStat[];
    outputStats: OutputStat[];
  }
  // mock数据，结构与接口一致
  const mockTraceableCodeStats: TraceableCodeStatsRes = {
    inputStats: [
      { inputDate: '2025-05-30', totalInputQty: 19081, inputTraceableCodeCount: 13189, inputRatio: 14507.9 },
      { inputDate: '2025-05-31', totalInputQty: 12000, inputTraceableCodeCount: 9000, inputRatio: 10000.1 },
      { inputDate: '2025-06-01', totalInputQty: 15000, inputTraceableCodeCount: 11000, inputRatio: 12000.2 },
      { inputDate: '2025-06-02', totalInputQty: 17000, inputTraceableCodeCount: 13000, inputRatio: 14000.3 },
      { inputDate: '2025-06-03', totalInputQty: 21000, inputTraceableCodeCount: 15000, inputRatio: 16000.4 },
      { inputDate: '2025-06-04', totalInputQty: 18000, inputTraceableCodeCount: 12000, inputRatio: 13000.5 },
      { inputDate: '2025-06-05', totalInputQty: 20000, inputTraceableCodeCount: 14000, inputRatio: 15000.6 },
    ],
    outputStats: [
      { outputDate: '2025-05-30', totalDispensedCount: 21843, traceableCodeCount: 18954, outputRatio: 19901.7 },
      { outputDate: '2025-05-31', totalDispensedCount: 15000, traceableCodeCount: 12000, outputRatio: 13000.1 },
      { outputDate: '2025-06-01', totalDispensedCount: 17000, traceableCodeCount: 14000, outputRatio: 15000.2 },
      { outputDate: '2025-06-02', totalDispensedCount: 18000, traceableCodeCount: 15000, outputRatio: 16000.3 },
      { outputDate: '2025-06-03', totalDispensedCount: 21000, traceableCodeCount: 17000, outputRatio: 18000.4 },
      { outputDate: '2025-06-04', totalDispensedCount: 19000, traceableCodeCount: 13000, outputRatio: 14000.5 },
      { outputDate: '2025-06-05', totalDispensedCount: 20000, traceableCodeCount: 15000, outputRatio: 16000.6 },
    ]
  };
  // 判断是否为mock模式
  const useMock = import.meta.env.VITE_USE_MOCK === 'true';

  // 3. 计算自适应字体和圆角函数，参考分时趋势
  const calcAdaptiveParams = () => {
    const container = document.getElementById('hospital-status-panel');
    if (container) {
      const width = container.offsetWidth;
      setAxisFontSize(Math.max(8, Math.min(16, Math.floor(width * 0.012))));
      setLegendFontSize(Math.max(8, Math.min(16, Math.floor(width * 0.015))));
      setLegendBlockWidth(Math.max(8, Math.min(24, Math.floor(width * 0.018))));
      setLegendBlockHeight(Math.max(4, Math.min(12, Math.floor(width * 0.009))));
      // 柱状图圆角自适应，比例可根据实际视觉微调
      setBarRadius(Math.max(2, Math.min(12, Math.floor(width * 0.0002))));
    }
  };

  // 4. 监听窗口resize事件
  useEffect(() => {
    setTimeout(calcAdaptiveParams, 100); // 延迟，确保容器已挂载
    window.addEventListener('resize', calcAdaptiveParams);
    return () => window.removeEventListener('resize', calcAdaptiveParams);
  }, []);

  // 5. 追溯码接口数据state
  const [traceData, setTraceData] = useState<TraceableCodeStatsRes | null>(null);
  
  // 获取追溯码数据的函数
  const fetchTraceData = useCallback(() => {
    if (useMock) {
      // mock模式下使用模拟数据
      setTraceData(mockTraceableCodeStats);
    } else {
      // 正式环境下请求接口
      const dateTimeValue = getDefaultDate(); 
      apiGet('/todayData/traceableCodeStats', { params: { dateTime: dateTimeValue } })
        .then(res => {
          if (res.data && res.data.data) {
            setTraceData(res.data.data);
          }
        })
        .catch(error => {
          console.error('获取追溯码数据失败:', error);
        });
    }
  }, [useMock]);

  // 获取就诊进度数据的函数
  const fetchProgressData = useCallback(() => {
    const dateTimeValue = getDefaultDate();
    apiGet('/todayData/patientVisitStats', { params: { dateTime: dateTimeValue } })
      .then(res => {
        if (res.data && res.data.data) {
          const data = res.data.data;
          setProgressData({
            waitingVisit: {
              total: data.waitingForConsultation || 0,
              departments: (data.consultationDepartments || []).map((dept: any) => ({
                departmentName: dept.departmentName,
                count: dept.patientCount,
                percentage: 0 // 会在渲染时计算
              }))
            },
            waitingPayment: {
              total: data.waitingForPayment || 0,
              departments: (data.paymentDepartments || []).map((dept: any) => ({
                departmentName: dept.departmentName,
                count: dept.patientCount,
                percentage: 0 // 会在渲染时计算
              }))
            },
            waitingMedicine: {
              total: data.waitingForPickup || 0,
              departments: (data.pickupDepartments || []).map((dept: any) => ({
                departmentName: dept.departmentName,
                count: dept.patientCount,
                percentage: 0 // 会在渲染时计算
              }))
            }
          });
        }
      })
      .catch(error => {
        console.error('获取就诊进度数据失败:', error);
        // 为了演示效果，提供一些测试数据
        setProgressData({
          waitingVisit: {
            total: 3290,
            departments: [
              { departmentName: '消化内科', count: 200, percentage: 0 },
              { departmentName: '心内科', count: 183, percentage: 0 },
              { departmentName: '骨科', count: 172, percentage: 0 },
              { departmentName: '生殖医学中心', count: 165, percentage: 0 },
              { departmentName: '皮肤科', count: 132, percentage: 0 }
            ]
          },
          waitingPayment: {
            total: 3290,
            departments: [
              { departmentName: '消化内科', count: 200, percentage: 0 },
              { departmentName: '心内科', count: 183, percentage: 0 },
              { departmentName: '骨科', count: 172, percentage: 0 },
              { departmentName: '生殖医学中心', count: 165, percentage: 0 },
              { departmentName: '皮肤科', count: 132, percentage: 0 }
            ]
          },
          waitingMedicine: {
            total: 3290,
            departments: [
              { departmentName: '消化内科', count: 200, percentage: 0 },
              { departmentName: '心内科', count: 183, percentage: 0 },
              { departmentName: '骨科', count: 172, percentage: 0 },
              { departmentName: '生殖医学中心', count: 165, percentage: 0 },
              { departmentName: '皮肤科', count: 132, percentage: 0 }
            ]
          }
        });
      });
  }, []);

  // 获取数据的函数（根据条件获取不同数据）
  const fetchData = useCallback(() => {
    if (defaultFlag) {
      fetchTraceData();
    } else {
      fetchProgressData();
    }
  }, [defaultFlag, fetchTraceData, fetchProgressData]);
  
  // 初始加载数据
  useEffect(() => {
    fetchData();
  }, [fetchData]);

  // 入库数据适配，日期统一 MM/DD 格式
  const inDays = traceData?.inputStats.map((i: any) => formatToMonthDay(i.inputDate)) ?? [];
  const inTraceable = traceData?.inputStats.map((i: any) => i.inputTraceableCodeCount) ?? [];
  const inTotal = traceData?.inputStats.map((i: any) => i.totalInputQty) ?? [];
  const inRatio = traceData?.inputStats.map((i: any) => i.inputRatio) ?? [];
  // 出库数据适配，日期统一 MM/DD 格式
  const outDays = traceData?.outputStats.map((i: any) => formatToMonthDay(i.outputDate)) ?? [];
  const outTraceable = traceData?.outputStats.map((i: any) => i.traceableCodeCount) ?? [];
  const outTotal = traceData?.outputStats.map((i: any) => i.totalDispensedCount) ?? [];
  const outRatio = traceData?.outputStats.map((i: any) => i.outputRatio) ?? [];

  // 6. 创建图表配置的通用函数，确保依赖自适应字体变量
  const createChartOption = (days: string[], barData1: number[], barData2: number[], lineData: number[], 
    color1: string, color2: string, legendType: 'in' | 'out') => {
    // 定义色块颜色
    const legendColors = legendType === 'in'
      ? ['#66B3FF', '#FF99AA', '#fff']
      : ['#66B3FF', '#99FFAA', '#fff'];
    
    // 计算左侧Y轴最大值（柱状图数据）
    const maxBarValue = Math.max(
      ...barData1.filter(v => !isNaN(Number(v))),
      ...barData2.filter(v => !isNaN(Number(v)))
    );
    const leftYAxisMax = maxBarValue === 0 ? 10 : Math.ceil(maxBarValue * 1.2 / 1000) * 1000;
    
    // 计算右侧Y轴最大值（线图数据）
    const maxLineValue = Math.max(...lineData.filter(v => !isNaN(Number(v))));
    // 比例值转为百分比后的最大值（乘以100）
    const rightYAxisMax = Math.ceil(maxLineValue * 100 * 1.2);
    
    return {
      backgroundColor: 'transparent',
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' },
        backgroundColor: 'rgba(24, 56, 128, 0.8)',
        borderColor: 'rgba(0, 180, 255, 0.3)',
        borderRadius: 4,
        padding: 12,
        textStyle: { color: '#fff', fontSize: legendFontSize },
        formatter: function(params: any) {
          // params: [追溯码个数, 总盒数, 比例]
          const date = params[0].axisValue;
          return `
            <div style="font-size:${legendFontSize}px;min-width:120px;">
              <div style="color:#00b4ff;font-weight:bold;margin-bottom:4px;">${date}</div>
              <div style="display:flex;align-items:center;margin-bottom:2px;">
                <span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:${legendColors[0]};margin-right:6px;"></span>
                追溯码个数：${params[0].value}
              </div>
              <div style="display:flex;align-items:center;margin-bottom:2px;">
                <span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:${legendColors[1]};margin-right:6px;"></span>
                ${legendType === 'in' ? '入库总盒数' : '出库总盒数'}：${params[1].value}
              </div>
              <div style="display:flex;align-items:center;">
                <span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:${legendColors[2]};margin-right:6px;"></span>
                比例：${typeof params[2].value === 'number' ? params[2].value.toFixed(2) + '%' : params[2].value}
              </div>
            </div>
          `;
        }
      },
      grid: {
        left: '3%',
        right: legendType === 'out' ? '5%' : '0%', // 右侧图表需要更多空间显示刻度
        bottom: '4%',
        top: '5%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: days,
        axisLine: {
          onZero: true,
          lineStyle: {
            color: 'rgba(255,255,255,0.3)'
          }
        },
        axisTick: {
          show: true,
          alignWithLabel: true,
          length: 3
        },
        axisLabel: {
          color: '#CCE6FF',
          fontSize: axisFontSize, // x轴字体自适应
          interval: window.innerWidth < 576 ? 1 : 0,
          align: 'center',
          margin: 4,
          formatter: function(value: string) {
            // 确保日期格式统一
            return value;
          }
        }
      },
      yAxis: [
        {
          // 左侧Y轴 - 用于柱状图数据（大数值）
          type: 'value',
          name: '',
          min: 0,
          max: leftYAxisMax,
          interval: leftYAxisMax <= 100 ? 20 : Math.ceil(leftYAxisMax / 5),
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(26, 57, 121, 0.4)',
              type: 'dashed'
            }
          },
          axisLabel: {
            color: '#CCE6FF',
            fontSize: axisFontSize, // y轴字体自适应
            formatter: function(value: number) {
              if (value >= 1000) {
                return value / 1000 + 'k';
              }
              return value;
            }
          }
        },
        {
          // 右侧Y轴 - 用于线图数据（比例值）
          type: 'value',
          name: '',
          min: 0,
          max: rightYAxisMax,
          interval: rightYAxisMax <= 20 ? 5 : Math.ceil(rightYAxisMax / 5),
          position: 'right',
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          splitLine: {
            show: false // 不显示右轴的网格线
          },
          axisLabel: {
            color: '#CCE6FF', // 修改为浅蓝色，与左侧Y轴颜色一致
            fontSize: axisFontSize,
            formatter: function(value: number) {
              // 将值格式化为百分比
              return value + '%';
            }
          }
        }
      ],
      series: [
        {
          name: '系列1',
          type: 'bar',
          barWidth: '7vw',
          barCategoryGap: '30%',
          barGap: '30%',
          yAxisIndex: 0, // 使用左侧Y轴
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: color1 },
              { offset: 1, color: 'rgba(102,179,255,0)' }
            ]),
            borderRadius: [barRadius, barRadius, 0, 0] // 圆角自适应
          },
          data: barData1
        },
        {
          name: '系列2',
          type: 'bar',
          barWidth: '7vw',
          yAxisIndex: 0, // 使用左侧Y轴
          itemStyle: {
            color: function(params: any) {
              if (color2.includes('FF99AA')) {
                return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#FF99AA' },
                  { offset: 1, color: 'rgba(255,153,170,0)' }
                ]);
              } else {
                return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#99FFAA' },
                  { offset: 1, color: 'rgba(153,255,170,0)' }
                ]);
              }
            },
            borderRadius: [barRadius, barRadius, 0, 0] // 圆角自适应
          },
          data: barData2
        },
        {
          name: '比例',
          type: 'line',
          smooth: true,
          symbol: 'none',
          symbolSize: 6,
          yAxisIndex: 1, // 使用右侧Y轴
          z: 3,
          lineStyle: {
            color: '#ffffff',
            width: 2
          },
          // 将数据转换为百分比格式（乘以100）
          data: lineData.map(value => typeof value === 'number' ? value * 100 : value)
        }
      ]
    };
  };

  // 入库追溯码图表配置
  const getInpatientOption = () => {
    return createChartOption(
      inDays,
      inTraceable, // 蓝色：追溯码个数
      inTotal,     // 粉色：入库总盒数
      inRatio,     // 白色：比例
      '#66B3FF',
      '#FF99AA',
      'in',
      
    );
  };
  // 出库追溯码图表配置
  const getOutpatientOption = () => {
    return createChartOption(
      outDays,
      outTraceable, // 蓝色：追溯码个数
      outTotal,     // 绿色：出库总盒数
      outRatio,     // 白色：比例
      '#66B3FF',
      '#40E386',
      'out'
    );
  };
  
  const [chartSize, setChartSize] = useState({ width: '100%', height: 'calc(100% - 30px)' });
  
  // 监听窗口大小变化，调整图表大小
  useEffect(() => {
    const handleResize = () => {
      setChartSize({
        width: '100%',
        height: 'calc(100% - 30px)'
      });
    };
    
    window.addEventListener('resize', handleResize);
    handleResize(); // 初始化大小
    
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  // 使用刷新Hook，配置对应的模块代码
  useGlobalRefresh(fetchData, '24');

  // 渲染追溯码情况内容
  const renderTraceabilityContent = () => (
    <>
      <PanelHeader fontSize={legendFontSize + 4}>追溯码情况</PanelHeader>
      <DualPanelLayout>
        <ChartBox>
          <ChartTitle fontSize={legendFontSize + 1}>
            <div className="title-text">入库追溯码情况</div>
            <Legend >
              <LegendItem className="blue" fontSize={legendFontSize} blockWidth={legendBlockWidth} blockHeight={legendBlockHeight}><div className="color-block"></div>追溯码个数</LegendItem>
              <LegendItem className="pink" fontSize={legendFontSize} blockWidth={legendBlockWidth} blockHeight={legendBlockHeight}><div className="color-block"></div>入库总盒数</LegendItem>
              <LegendItem fontSize={legendFontSize} blockWidth={legendBlockWidth} blockHeight={legendBlockHeight}><div className="color-block" style={{background: '#fff'}}></div>比例</LegendItem>
            </Legend>
          </ChartTitle>
          <div className="chart-container">
            <ReactECharts 
              option={getInpatientOption()} 
              style={{ height: '100%', width: '100%' }} 
              opts={{ renderer: 'canvas' }}
              notMerge={true}
            />
          </div>
        </ChartBox>
        
        <ChartBox>
          <ChartTitle fontSize={legendFontSize + 1}>
            <div className="title-text">出库追溯码情况</div>
            <Legend style={{paddingRight: '5%'}}>
              <LegendItem className="blue" fontSize={legendFontSize} blockWidth={legendBlockWidth} blockHeight={legendBlockHeight}><div className="color-block"></div>追溯码个数</LegendItem>
              <LegendItem className="green" fontSize={legendFontSize} blockWidth={legendBlockWidth} blockHeight={legendBlockHeight}><div className="color-block"></div>出库总盒数</LegendItem>
              <LegendItem fontSize={legendFontSize} blockWidth={legendBlockWidth} blockHeight={legendBlockHeight}><div className="color-block" style={{background: '#fff'}}></div>比例</LegendItem>
            </Legend>
          </ChartTitle>
          <div className="chart-container">
            <ReactECharts 
              option={getOutpatientOption()} 
              style={{ height: '100%', width: '100%' }} 
              opts={{ renderer: 'canvas' }}
              notMerge={true}
            />
          </div>
        </ChartBox>
      </DualPanelLayout>
    </>
  );

  // 渲染单个进度卡片
  const renderProgressCard = (title: string, data: { total: number; departments: DepartmentProgressItem[] }, iconUrl: string, decoratorUrl?: string) => {
    // 计算最大值用于进度条百分比
    const maxCount = Math.max(...data.departments.map(d => d.count), 1);
    
    return (
      <ProgressCard>
        <ProgressCardHeader>
          <ProgressCardIcon style={{ backgroundImage: `url('${iconUrl}')` }} />
          <ProgressCardRight>
            <ProgressCardTitleContainer>
              <ProgressCardTitle>{title} (人)</ProgressCardTitle>
              {decoratorUrl && (
                <ProgressCardDecorator style={{ backgroundImage: `url('${decoratorUrl}')` }} />
              )}
            </ProgressCardTitleContainer>
          </ProgressCardRight>
        </ProgressCardHeader>
        
        <ProgressCardValueRow>
          <ProgressCardValue>{data.total}</ProgressCardValue>
        </ProgressCardValueRow>
        
        <DepartmentList backgroundImage="/juxingkapian_bg.png">
          {data.departments.slice(0, 5).map((dept, index) => {
            const percentage = maxCount > 0 ? (dept.count / maxCount) * 100 : 0;
            return (
              <DepartmentItem key={index}>
                <DepartmentName>{dept.departmentName}</DepartmentName>
                <DepartmentProgressContainer>
                  <DepartmentProgressBar percentage={percentage} />
                </DepartmentProgressContainer>
                <DepartmentValue>{dept.count}</DepartmentValue>
              </DepartmentItem>
            );
          })}
          {data.departments.length === 0 && (
            <DepartmentItem>
              <DepartmentName style={{ color: '#888', textAlign: 'center', width: '100%' }}>
                暂无数据
              </DepartmentName>
            </DepartmentItem>
          )}
        </DepartmentList>
      </ProgressCard>
    );
  };

  // 渲染就诊进度一览内容
  const renderProgressContent = () => (
    <>
      <PanelHeader fontSize={legendFontSize + 4}>就诊进度一览</PanelHeader>
      <ProgressOverviewContainer>
        {renderProgressCard('待就诊', progressData.waitingVisit, '/daijiuzheng_icon.png', '/jiantouzhuangshi.png')}
        {renderProgressCard('待缴费', progressData.waitingPayment, '/daijiaofei_icon.png', '/jiantouzhuangshi.png')}
        {renderProgressCard('待取药', progressData.waitingMedicine, '/daiquhao_icon.png', '/jiantouzhuangshi.png')}
      </ProgressOverviewContainer>
    </>
  );
  
  return (
    <TraceabilityPanel id="hospital-status-panel">
      {defaultFlag ? renderTraceabilityContent() : renderProgressContent()}
    </TraceabilityPanel>
  );
};

export default HospitalStatusChart; 