import React, { useEffect, useState, useRef, useCallback } from 'react';
import ReactECharts from 'echarts-for-react';
import * as echarts from 'echarts';
import { PanelContainer } from '../styled/DashboardStyles';
import styled from 'styled-components';
import useGlobalRefresh from '../../hooks/useGlobalRefresh'; // 导入全局刷新钩子
import { apiGet } from '../../utils/request'; // 引入API请求工具
import { getDefaultDate } from '../../App'; // 导入获取默认日期的函数

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

// 组件标题
const PanelHeader = styled.div`
  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 ContentLayout = styled.div`
  display: flex;
  flex-direction: column;
  height: calc(100% - 1.6vw);
  padding: 0.5vw 1.5%;
`;

// 指标区域
const MetricsArea = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 2vw;
`;

// 左侧指标
const LeftMetrics = styled.div`
  display: flex;
  gap: 2vw;
`;

// 单个指标（字体自适应）
const Metric = styled.div<{fontSize: number, valueColor?: string}>`
  font-size: ${props => props.fontSize}px;
  color: #fff;
  font-weight: bold;
  span {
    margin-left: 0.3vw;
    color: ${props => props.valueColor || '#99FFAA'};
  }
`;

// 右侧图例（字体和色块自适应）
const Legend = styled.div`
  display: flex;
  gap: 1vw;
`;

const LegendItem = styled.div<{ color: string, blockWidth: number, blockHeight: number, fontSize: number }>`
  display: flex;
  align-items: center;
  .legend-icon {
    width: ${props => props.blockWidth}px;
    height: ${props => props.blockHeight}px;
    margin-right: 0.3vw;
    background: ${props => props.color};
  }
  .legend-text {
    font-size: ${props => props.fontSize}px;
    color:#CCE6FF;
  }
`;

// 图表区域
const ChartArea = styled.div`
  flex: 1;
  width: 100%;
`;

const HourlyTrendChart: React.FC = () => {
  const chartRef = useRef<ReactECharts>(null);
  // 统一自适应参数
  const [barRadius, setBarRadius] = useState(4);
  const [barLabelFontSize, setBarLabelFontSize] = useState(10);
  const [axisFontSize, setAxisFontSize] = useState(10);
  const [legendFontSize, setLegendFontSize] = useState(10);
  const [legendBlockWidth, setLegendBlockWidth] = useState(12);
  const [legendBlockHeight, setLegendBlockHeight] = useState(6);
  const [metricFontSize, setMetricFontSize] = useState(12);
  const [lineWidth, setLineWidth] = useState(3);

  const useMock = import.meta.env.VITE_USE_MOCK === 'true'; // 判断是否为mock模式

  // 新增：本时段实际处方数和预测处方数
  const [actualPrescriptionCount, setActualPrescriptionCount] = useState(0); // 本时段取号处方数
  const [periodPrescriptionCount, setPeriodPrescriptionCount] = useState(0); // 本时段预测处方数

  // 统一计算自适应参数
  const calcAdaptiveParams = () => {
    const container = document.getElementById('hourly-trend-panel');
    if (container) {
      const width = container.offsetWidth;
      setBarRadius(Math.max(2, Math.min(12, Math.floor(width * 0.00001))));
      setBarLabelFontSize(Math.max(8, Math.min(18, Math.floor(width * 0.008))));
      setAxisFontSize(Math.max(8, Math.min(16, Math.floor(width * 0.012))));
      setLegendFontSize(Math.max(12, Math.min(20, Math.floor(width * 0.0016))));
      setLegendBlockWidth(Math.max(8, Math.min(24, Math.floor(width * 0.018))));
      setLegendBlockHeight(Math.max(4, Math.min(12, Math.floor(width * 0.009))));
      setMetricFontSize(Math.max(10, Math.min(20, Math.floor(width * 0.016))));
      setLineWidth(Math.max(2, Math.min(8, Math.floor(width * 0.004))));
    }
  };

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

  // 调试：打印当前圆角值
  useEffect(() => {
    console.log('barRadius:', barRadius);
  }, [barRadius]);

  // chartData初始值为空，后续根据mock/接口填充
  const [chartData, setChartData] = useState<{
    xAxis: string[];
    prescriptionData: number[];
    medicineData: number[];
    predictionData: number[];
  }>({
    xAxis: [],
    prescriptionData: [],
    medicineData: [],
    predictionData: []
  });

  // 获取数据函数
  const fetchData = useCallback(() => {
    if (useMock) {
      // 使用模拟数据
      setChartData({
        xAxis: ['08:00', '08:30', '09:00', '09:30', '10:00', '10:30', '11:00', '11:30', '12:00', '12:30', '13:00', '13:30', '14:00', '14:30', '15:00', '15:30', '16:00', '16:30', '17:00', '17:30', '18:00'],
        prescriptionData: [200, 250, 300, 400, 600, 750, 850, 800, 700, 400, 200, 250, 350, 500, 650, 800, 700, 500, 350, 250, 300],
        medicineData: [100, 150, 200, 300, 500, 650, 750, 700, 600, 300, 100, 150, 250, 400, 550, 700, 600, 400, 250, 150, 200],
        predictionData: [250, 300, 350, 450, 650, 800, 900, 850, 750, 450, 250, 300, 400, 550, 700, 850, 750, 550, 400, 300, 350]
      });
      // mock模式下也给顶部数值赋模拟值
      setActualPrescriptionCount(100);
      setPeriodPrescriptionCount(150);
      // 定时器只在mock模式下启用
      const timer = setInterval(() => {
        setChartData(prev => {
          const newPrescriptionData = prev.prescriptionData.map(val => Math.max(100, Math.min(900, val + Math.floor(Math.random() * 100) - 50)));
          const newMedicineData = prev.medicineData.map(val => Math.max(50, Math.min(800, val + Math.floor(Math.random() * 80) - 40)));
          const newPredictionData = prev.predictionData.map(val => Math.max(150, Math.min(950, val + Math.floor(Math.random() * 120) - 60)));
          return {
            ...prev,
            prescriptionData: newPrescriptionData,
            medicineData: newMedicineData,
            predictionData: newPredictionData
          };
        });
      }, 5000);
      return () => clearInterval(timer);
    } else {
      // 使用实际API
      const dateTime = getDefaultDate();
      apiGet('/todayData/timePeriodPrescription', { params: { dateTime } })
        .then(res => {
          if (res.data && res.data.data) {
            const d = res.data.data;
            const arr = d?.timePeriodPrescriptions || [];
            setChartData({
              xAxis: arr.map((item: any) => item.timePeriod),
              prescriptionData: arr.map((item: any) => item.takenCount),
              medicineData: arr.map((item: any) => item.issuedCount),
              predictionData: arr.map((item: any) => item.predictionCount)
            });
            // 新增：赋值本时段实际处方数和预测处方数
            setActualPrescriptionCount(d?.actualPrescriptionCount ?? 0);
            setPeriodPrescriptionCount(d?.periodPrescriptionCount ?? 0);
          }
        })
        .catch(error => {
          console.error('获取分时趋势数据失败:', error);
        });
    }
  }, [useMock]);

  // 初始加载数据
  useEffect(() => {
    fetchData();
  }, [fetchData]);
  
  // 使用全局刷新钩子，指定模块代码'21'
  useGlobalRefresh(fetchData, '21');

  // 图表配置
  const getOption = () => {
    return {
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' },
        backgroundColor: 'rgba(24, 32, 56, 0.95)', // 深色背景
        borderColor: 'rgba(102,179,255,0.2)',
        borderWidth: 1,
        textStyle: { color: '#fff', fontSize: axisFontSize },
        // 自定义tooltip内容和色块，保证和图表一致
        formatter: function(params: any[]) {
          // params顺序和series一致
          return `
            <div style="font-size:14px;margin-bottom:4px;">${params[0].axisValue}</div>
            <div style="display:flex;align-items:center;margin-bottom:2px;">
              <span style="display:inline-block;width:10px;height:10px;border-radius:2px;background:#66B3FF;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:2px;background:#F3F9FF;margin-right:6px;"></span>
              发药处方量：${params[1].value}
            </div>
            <div style="display:flex;align-items:center;">
              <span style="display:inline-block;width:10px;height:10px;border-radius:2px;background:#67DD81;margin-right:6px;"></span>
              预测处方量：${params[2].value}
            </div>
          `;
        }
      },
      grid: {
        left: '0%', right: '0%', bottom: '0%', top: '3%', containLabel: true
      },
      xAxis: {
        type: 'category',
        data: chartData.xAxis,
        axisLine: { lineStyle: { color: 'rgba(255, 255, 255, 0.3)' } },
        axisLabel: {
          color: '#CCE6FF',
          fontSize: axisFontSize, // 刻度字体自适应
          align: 'center',
        },
        axisTick: { alignWithLabel: true }
      },
      yAxis: [
        {
          type: 'value',
          max: function() {
            // 取所有数据的最大值
            const maxValue = Math.max(
              ...chartData.prescriptionData,
              ...chartData.medicineData,
              ...chartData.predictionData
            );
            // 数据很小时，max=最大值+10，保证柱子不太矮
            if (maxValue < 100) return maxValue + 10;
            // 数据较大时，max=1.2倍并向上取整到100
            return Math.ceil(maxValue * 1.2 / 100) * 100;
          },
          splitNumber: 5,
          axisLine: { show: false },
          axisTick: { show: false },
          splitLine: { lineStyle: { color: 'rgba(255, 255, 255, 0.1)', type: 'solid' } },
          axisLabel: { color: '#CCE6FF', fontSize: axisFontSize } // 刻度字体自适应
        }
      ],
      series: [
        {
          name: '取号处方量',
          type: 'bar',
          barWidth: '20%',
          itemStyle: {
            color: {
              type: 'linear', x: 0, y: 0, x2: 0, y2: 1,
              colorStops: [
                { offset: 0, color: '#66B3FF' },
                { offset: 1, color: 'rgba(102,179,255,0)' }
              ]
            },
            borderRadius: [barRadius, barRadius, 0, 0]
          },
          label: {
            show: false,
            position: 'top',
            color: '#fff',
            fontSize: barLabelFontSize,
            fontWeight: 'bold',
            formatter: '{c}'
          },
          data: chartData.prescriptionData
        },
        {
          name: '发药处方量',
          type: 'bar',
          barWidth: '20%',
          barGap: '30%',
          itemStyle: {
            color: {
              type: 'linear', x: 0, y: 0, x2: 0, y2: 1,
              colorStops: [
                { offset: 0, color: '#F3F9FF' },
                { offset: 1, color: 'rgba(242,249,255,0)' }
              ]
            },
            borderRadius: [barRadius, barRadius, 0, 0]
          },
          label: {
            show: false,
            position: 'top',
            color: '#fff',
            fontSize: barLabelFontSize,
            fontWeight: 'bold',
            formatter: '{c}'
          },
          data: chartData.medicineData
        },
        {
          name: '预测处方量',
          type: 'line',
          smooth: true,
          symbol: 'none',
          lineStyle: {
            width: lineWidth * 0.6, // 减小线宽度
            color: '#99FFAA'
          },
          data: chartData.predictionData
        }
      ]
    };
  };
  
  // 自适应调整
  useEffect(() => {
    const handleResize = () => {
      if (chartRef.current) {
        const chart = chartRef.current.getEchartsInstance();
        chart.resize();
      }
    };
    
    window.addEventListener('resize', handleResize);
    
    // 确保组件加载后也调整一次
    setTimeout(handleResize, 200);
    
    return () => window.removeEventListener('resize', handleResize);
  }, []);
  
  return (
    <HourlyTrendPanel id="hourly-trend-panel">
      <PanelHeader>分时趋势</PanelHeader>
      <ContentLayout>
        <MetricsArea>
          <LeftMetrics>
            {/* 顶部数值用接口数据渲染 */}
            <Metric fontSize={metricFontSize}>本时段预测处方数：<span>{periodPrescriptionCount}</span></Metric>
            <Metric fontSize={metricFontSize} valueColor="#66B2FF">本时段取号处方数：<span>{actualPrescriptionCount}</span></Metric>
          </LeftMetrics>
          <Legend>
            <LegendItem color="#66B3FF" blockWidth={legendBlockWidth} blockHeight={legendBlockHeight} fontSize={legendFontSize}>
              <div className="legend-icon"></div>
              <div className="legend-text">取号处方量</div>
            </LegendItem>
            <LegendItem color="#F3F9FF" blockWidth={legendBlockWidth} blockHeight={legendBlockHeight} fontSize={legendFontSize}>
              <div className="legend-icon"></div>
              <div className="legend-text">发药处方量</div>
            </LegendItem>
            <LegendItem color="#99FFAA" blockWidth={legendBlockWidth} blockHeight={legendBlockHeight} fontSize={legendFontSize}>
              <div className="legend-icon"></div>
              <div className="legend-text">预测处方量</div>
            </LegendItem>
          </Legend>
        </MetricsArea>
        <ChartArea>
          <ReactECharts 
            key={barRadius + '-' + barLabelFontSize + '-' + axisFontSize + '-' + legendFontSize + '-' + legendBlockWidth + '-' + legendBlockHeight + '-' + metricFontSize + '-' + lineWidth}
            ref={chartRef}
            option={getOption()} 
            style={{ height: '100%', width: '100%' }} 
            opts={{ renderer: 'canvas' }}
          />
        </ChartArea>
      </ContentLayout>
    </HourlyTrendPanel>
  );
};

export default HourlyTrendChart; 