import React, { useState, useEffect, useRef, useCallback } from 'react';
import styled from 'styled-components';
import ReactECharts from 'echarts-for-react';
import { apiGet } from '../../utils/request';
import { getDefaultDate } from '../../App';
import { PanelContainer } from '../styled/DashboardStyles';
import useGlobalRefresh from '../../hooks/useGlobalRefresh';

// 组件容器样式
const Container = styled(PanelContainer)`
  width: 100%;
  height: 35vh;
  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: #CCE6FF;
  font-family: 'DingTalk JinBuTi', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  background: url('/component_header_bg.png') no-repeat;
  background-size: 100% 100%;
`;

// 内容容器
const ContentBox = styled.div`
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 0.5vw;
  padding-top: 1.2vw;
  height: calc(100% - 1.6vw);
`;

interface ExpiryData {
  month: string;
  totalQuantity: number;
}

interface MedicineExpiryChartProps {
  selectedEquipCode: string;
  selectedEquipName: string;
}

const MedicineExpiryChart: React.FC<MedicineExpiryChartProps> = ({ selectedEquipCode, selectedEquipName }) => {
  const chartRef = useRef<ReactECharts>(null);
  const [data, setData] = useState<ExpiryData[]>([]);
  const [loading, setLoading] = useState(true);
  const [chartSize, setChartSize] = useState({ width: 800, height: 300 });

  // 监听容器大小变化
  useEffect(() => {
    const updateSize = () => {
      if (chartRef.current) {
        const container = chartRef.current.ele;
        if (container) {
          const newWidth = container.clientWidth;
          const newHeight = container.clientHeight;
          
          // 只有当尺寸真正变化且不为0时才更新状态
          if (newWidth > 0 && newHeight > 0 && 
              (Math.abs(newWidth - chartSize.width) > 5 || 
               Math.abs(newHeight - chartSize.height) > 5)) {
            setChartSize({
              width: newWidth,
              height: newHeight
            });
          }
        }
      }
    };
    
    // 初始更新
    setTimeout(updateSize, 300); // 给图表一些渲染时间
    
    // 监听窗口大小变化
    window.addEventListener('resize', updateSize);
    
    return () => {
      window.removeEventListener('resize', updateSize);
    };
  }, [chartSize.width, chartSize.height]);

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      // 获取默认日期
      const defaultDate = getDefaultDate();
      
      // 直接使用选中的设备代码
      const equipCode = selectedEquipCode;
      
      // 调用新的药品效期接口
      const response = await apiGet('/equipMana/drugExpiryDateInfo', {
        params: { 
          dateTime: defaultDate,
          equipCode: equipCode
        }
      });
      
      if (response.data && response.data.data && Array.isArray(response.data.data)) {
        setData(response.data.data);
      }
    } catch (error) {
      console.error('获取药品效期数据失败:', error);
      // 使用模拟数据
      const mockData: ExpiryData[] = [
        { month: '2025-06', totalQuantity: 0 },
        { month: '2025-07', totalQuantity: 0 },
        { month: '2025-08', totalQuantity: 0 },
        { month: '2025-09', totalQuantity: 0 },
        { month: '2025-10', totalQuantity: 14 },
        { month: '2025-11', totalQuantity: 8 },
        { month: '2025-12', totalQuantity: 8 },
        { month: '2026-01', totalQuantity: 0 },
        { month: '2026-02', totalQuantity: 121 },
        { month: '2026-03', totalQuantity: 103 },
        { month: '2026-04', totalQuantity: 71 },
        { month: '2026-05', totalQuantity: 175 }
      ];
      setData(mockData);
    } finally {
      setLoading(false);
    }
  }, [selectedEquipCode]);

  // 组件挂载时获取数据
  useEffect(() => {
    fetchData();
  }, [fetchData]);

  // 当选中的设备代码变化时重新获取数据
  useEffect(() => {
    fetchData();
  }, [selectedEquipCode, fetchData]);

  // 使用全局刷新钩子，指定模块代码'26'
  useGlobalRefresh(fetchData, '26');
  
  // 获取柱状图配置
  const getBarOption = () => {
    // 提取月份和数值
    const months = data.map(item => item.month);
    const values = data.map(item => item.totalQuantity);
    
    // 寻找最大值，用于Y轴设置
    const maxValue = Math.max(...values);
    
    // 计算自适应的字体大小
    const baseFontSize = Math.max(8, Math.min(12, chartSize.width / 80));
    const labelFontSize = Math.max(12, Math.min(10, chartSize.width / 100));
    
    // 计算柱宽 - 根据月份数量自动调整，增加柱子宽度
    const adaptiveBarWidth = Math.max(30, Math.min(60, 100 / (months.length * 0.4))); // 自适应百分比宽度，更宽的柱子
    
    // 计算自适应的圆角大小
    const adaptiveRadius = Math.max(2, Math.min(6, chartSize.width /300));
    
    return {
      backgroundColor: 'transparent',
      grid: {
        left: '0%',
        right: '3%',
        bottom: '12%',
        top: '14%',
        containLabel: true
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        textStyle: {
          fontSize: baseFontSize
        }
      },
      xAxis: {
        type: 'category',
        data: months.map(m => m.replace(/-/g, '/')),
        axisLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.2)'
          }
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: '#CCE6FF',
          fontSize: baseFontSize,
          interval: 0 // 显示所有标签
        }
      },
      yAxis: {
        type: 'value',
        max: function(value: { max: number }) {
          if (value.max === 0) return 10;
          // 取比最大值大且能被100整除的下一个数
          return Math.ceil(value.max / 100) * 100 + 100;
        },
        splitNumber: 4, // 减少分割线数量
        boundaryGap: [0, '10%'], // 增加顶部边界间隙
        splitLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.1)',
            width: 1 // 线宽为1，避免加粗
          }
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          show: false
        }
      },
      series: [
        {
          name: '药品数量',
          type: 'bar',
          barWidth: `${adaptiveBarWidth}%`,
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 1,
              x2: 0,
              y2: 0,
              colorStops: [
                { offset: 0, color: '#65CCFF' }, // 底部深色
                { offset: 1, color: '#CBEEFF' }  // 顶部浅色
              ]
            },
            borderRadius: [adaptiveRadius, adaptiveRadius, 0, 0]
          },
          label: {
            show: true,
            position: 'top',
            fontSize: labelFontSize,
            color: '#fff',
            formatter: '{c}'
          },
          data: values
        }
      ]
    };
  };

  return (
    <Container>
      <PanelHeader>药品效期</PanelHeader>
      <ContentBox>
        {loading ? (
          <div style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '100%',
            color: '#7e9bcc',
            fontSize: '0.8vw'
          }}>
            数据加载中...
          </div>
        ) : (
          <ReactECharts
            ref={chartRef}
            option={getBarOption()}
            style={{ height: '100%', width: '100%' }}
            opts={{ renderer: 'canvas' }}
            notMerge={true}
            onEvents={{
              // 图表渲染完成后更新尺寸
              'finished': () => {
                if (chartRef.current) {
                  const instance = chartRef.current.getEchartsInstance();
                  if (instance) {
                    instance.resize();
                  }
                }
              }
            }}
          />
        )}
      </ContentBox>
    </Container>
  );
};

export default MedicineExpiryChart; 