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 request, { apiGet } from '../../utils/request'; // 引入API请求工具
import { getMockDispensingData } from '../../utils/mockData'; // 引入mock数据
import { getDefaultDate } from '../../App'; // 导入获取默认日期的函数
import useGlobalRefresh from '../../hooks/useGlobalRefresh'; // 导入全局刷新钩子

// 面板容器
const MedicineStatusPanel = 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;
  height: calc(100% - 1.6vw);  // 只减去标题高度
  padding: 0.5vw;
`;

// 左侧饼图容器
const PieChartContainer = styled.div`
  width: 28%;
  height: 100%;
  position: relative;
  display: flex;
  padding-top: 2vw;
`;

// 饼图区域
const ChartArea = styled.div`
  position: relative;
  width:70%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start; // 顶部对齐
  align-items: flex-start; // 左上对齐
  padding-left: 0vw;
`;

// 图例区域
const LegendArea = styled.div`
  width: 3vw;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start; // 顶部对齐
  align-items: flex-start;
  margin-left: 0vw;
`;

// 右侧指标卡片布局
const MetricsLayout = styled.div`
  width: 72%;
  display: flex;
  flex-wrap: wrap;
  justify-content:flex-end;
  align-items: center;
`;

// 指标卡片
const MetricCard = styled.div`
  width: 28%;
  height:45%;
  position: relative;
  padding: 0.5vw;
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  padding-top: 0;
  margin-right: 5%;
  /* background: rgba(1, 19, 67, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.2); */
  background: url('/fayaocard_bg.png') no-repeat;
  background-size: 100% 100%;
  border-radius: 0.4vw;
  &:last-child {
    margin-right: 0;
  }
`;

// 指标环图
const CircleChart = styled.div`
  position: absolute;
  width: 100%;
  height: 65%;
  left:-4vw;
  top:-0.5vw;
  display: flex;
  justify-content: center;
  align-items: center;
`;

// 指标数据
const MetricData = styled.div`
  width: 100%;
  height: 50%;
  /* margin-top: 0.8vw; */
  display: flex;
  padding-left: 3vw;
  padding-top: 6%;
  flex-direction: column;
  align-items: flex-start;
  
  .title {
    font-size: 0.6vw;
    color: #CCE6FF;
    white-space: nowrap;
    margin-bottom: 0.1vw;
  }
  
  .value {
    font-size: 1.4vw;
    /* font-weight: bold; */
    color: #fff;
    line-height: 1.8vw;
    margin-bottom: 1vw;
    font-family: 'DingTalk JinBuTi', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  }
  
  .change {
    font-size: 0.6vw;
    white-space: nowrap;
    display: flex;
    align-items: center;
    font-family: inherit;
    color: #CCE6FF;
    margin-left: -40%;
    
    .percent-arrow {
      display: flex;
      align-items: center;
      margin-left: 0.3vw;
    }
    .percent {
      font-size: 0.6vw;
      font-weight: bold;
      margin-right: 0.15vw;
      font-family: 'DingTalk JinBuTi', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
      color: inherit;
    }
    .arrow-img {
      width: 0.7vw;
      height: 0.7vw;
      margin-left: 0.05vw;
      vertical-align: middle;
      /* 上下浮动动画 */
      animation: arrowFloat 1.2s infinite ease-in-out;
    }
    /* 定义动画关键帧 */
    @keyframes arrowFloat {
      0% { transform: translateY(0); }
      50% { transform: translateY(-0.3vw); }
      100% { transform: translateY(0); }
    }
  }
`;

// 图例
const Legend = styled.div`
  display: flex;
  flex-direction: column;
  gap: 0.2vw;
`;

const LegendItem = styled.div<{ color: string }>`
  display: flex;
  align-items: center;
  
  .color-block {
    width: 0.2vw;
    height: 0.5vw;
    margin-right: 0.3vw;
    background: ${props => props.color};
  }
  
  .item-text {
    font-size: 0.5vw;
    color: #CCE6FF;
  }
`;

// 饼图内容包装器
const PieContentWrapper = styled.div`
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start; // 顶部对齐，减少与饼图的整体间距
  width: 100%;
  height: 100%;
`;

// 饼图标题
const PieChartTitle = styled.div`
  font-size: 0.53vw;
  color: #CCE6FF;
  margin-top: 1vw; // 与左侧“待发药”保持一致的上边距
  margin-bottom: 1vw;
  text-align: left;
  flex-shrink: 0;
  font-family: 'DingTalk JinBuTi', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  white-space: nowrap;
  line-height: 1.2;
`;

// 顶部文本（待发药）
const TopText = styled.div`
  font-size: 0.7vw;
  color: #7e9bcc;
  margin-top: 0.4vw; // 减小顶部间距
  text-align: center;
  flex-shrink: 0;
  
  span {
    font-size: 1vw;
    color: #fff;
    margin-left: 0.3vw;
    font-family: 'DingTalk JinBuTi', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  }
`;

// 增加一个CSS样式来强制设置字体大小
const PercentText = styled.div`
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 0.7vw !important;
  font-family: 'DingTalk JinBuTi', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  font-weight: bold;
  color: #fff;
  z-index: 10;
`;

interface MetricItem {
  title: string;
  value: number;
  change: string;
  changeType: 'up' | 'down' | 'zero';
  color: string;
}

const useMock = import.meta.env.VITE_USE_MOCK === 'true'; // 读取环境变量

const MedicineStatusChart: React.FC = () => {
  // 所有Hooks必须在组件顶层声明，不能放在条件语句或return之前，否则会导致Hooks顺序不一致，React报错
  const pieChartRef = useRef<ReactECharts>(null); // 饼图引用
  const circleChartRefs = useRef<Array<ReactECharts | null>>([null, null, null]); // 环形图引用
  const [data, setData] = useState<any>(null); // 接口返回的完整数据对象
  // 保留原有饼图结构和颜色，只替换value
  const [pieData, setPieData] = useState([
    { name: '心血管', value: 0, color: '#4D88FF' },
    { name: '儿科', value: 0, color: '#4DE1FF' },
    { name: '外科', value: 0, color: '#44E494' },
    { name: '内科', value: 0, color: '#FFE980' },
    { name: '皮肤科', value: 0, color: '#8FADCC' }
  ]);
  // 保留原有指标卡片结构和文案，只替换数值
  const [metrics, setMetrics] = useState<MetricItem[]>([
    {
      title: '已发人数（人）',
      value: 0,
      change: '0.0%',
      changeType: 'zero',
      color: '#4B83FF'
    },
    {
      title: '机发处方（张）',
      value: 0,
      change: '0.0%',
      changeType: 'zero',
      color: '#5CCCE4'
    },
    {
      title: '机发药品（盒）',
      value: 0,
      change: '0.0%',
      changeType: 'zero',
      color: '#67DD81'
    }
  ]);

  // 增加字体大小自适应逻辑
  const [circleFontSize, setCircleFontSize] = useState('1.2vw');

  // 自适应计算函数
  const calcAdaptiveParams = useCallback(() => {
    const container = document.getElementById('medicine-status-panel');
    if (container) {
      const width = container.offsetWidth;
      // 使用vw单位代替px，确保自适应
      setCircleFontSize(`${Math.max(2, Math.min(5, width * 1))}vw`);
    }
  }, []);

  // 监听窗口大小变化
  useEffect(() => {
    calcAdaptiveParams();
    window.addEventListener('resize', calcAdaptiveParams);
    return () => window.removeEventListener('resize', calcAdaptiveParams);
  }, [calcAdaptiveParams]);

  // 创建回调函数处理环形图引用
  const setCircleChartRef = useCallback((el: ReactECharts | null, index: number) => {
    if (circleChartRefs.current) {
      circleChartRefs.current[index] = el;
    }
  }, []);

  // 颜色列表，按顺序分配给topDepartments
  const pieColors = ['#4D88FF', '#4DE1FF', '#44E494', '#FFE980', '#8FADCC'];

  // 数据获取函数
  const fetchData = useCallback(() => {
    if (useMock) {
      setData(getMockDispensingData());
    } else {
      const dateTime = getDefaultDate();
      apiGet('/todayData/todayDispensingData', { params: { dateTime } })
        .then(res => {
          if (res.data && res.data.data) {
            setData(res.data.data);
          }
        })
        .catch(error => {
          console.error('获取发药状态数据失败:', error);
        });
    }
  }, [useMock]);

  // 初始加载数据
  useEffect(() => {
    fetchData();
  }, [fetchData]);

  // 使用全局刷新钩子，指定模块代码'18'
  useGlobalRefresh(fetchData, '18');

  useEffect(() => {
    // 确保data不为null再处理数据
    if (!data) return;
    
    // 替换饼图数据，只替换value，名称和颜色不变
    if (data.topDepartments && Array.isArray(data.topDepartments)) {
      setPieData(prev => prev.map((item, idx) => {
        // 查找接口返回的同名科室
        const found = data.topDepartments.find((dep: any) => dep.department === item.name);
        return {
          ...item,
          value: found ? found.prescriptionCount : 0
        };
      }));
    }
    
    // 替换指标卡片数据，只替换value、change等
    setMetrics([
      {
        title: '已发人数（人）',
        value: data?.taskStatistics?.totalDispensedTasks || 0,
        change: data?.taskStatistics?.growthRate > 0 ? `+${(data.taskStatistics.growthRate * 100).toFixed(1)}%` :
               data?.taskStatistics?.growthRate < 0 ? `${(data.taskStatistics.growthRate * 100).toFixed(1)}%` : '0.0%',
        changeType: data?.taskStatistics?.growthRate > 0 ? 'up' : data?.taskStatistics?.growthRate < 0 ? 'down' : 'zero',
        color: '#4B83FF'
      },
      {
        title: '已发处方（张）',
        value: data?.prescriptionStatistics?.totalPrescriptions || 0,
        change: data?.prescriptionStatistics?.growthRate > 0 ? `+${(data.prescriptionStatistics.growthRate * 100).toFixed(1)}%` :
               data?.prescriptionStatistics?.growthRate < 0 ? `${(data.prescriptionStatistics.growthRate * 100).toFixed(1)}%` : '0.0%',
        changeType: data?.prescriptionStatistics?.growthRate > 0 ? 'up' : data?.prescriptionStatistics?.growthRate < 0 ? 'down' : 'zero',
        color: '#5CCCE4'
      },
      {
        title: '已发药品（盒）',
        value: data?.drugDispensingStatistics?.totalBoxes || 0,
        change: data?.drugDispensingStatistics?.growthRate > 0 ? `+${(data.drugDispensingStatistics.growthRate * 100).toFixed(1)}%` :
               data?.drugDispensingStatistics?.growthRate < 0 ? `${(data.drugDispensingStatistics.growthRate * 100).toFixed(1)}%` : '0.0%',
        changeType: data?.drugDispensingStatistics?.growthRate > 0 ? 'up' : data?.drugDispensingStatistics?.growthRate < 0 ? 'down' : 'zero',
        color: '#67DD81'
      }
    ]);
  }, [data]);

  // 饼图配置，顺序和topDepartments一致
  const getPieOption = () => {
    return {
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)',
        textStyle: {
          fontSize: '0.7vw'
        }
      },
      legend: {
        show: false
      },
      series: [
        {
          type: 'pie',
          roseType: 'area',
          radius: ['15%', '60%'],
          center: ['50%', '40%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 0,
            borderColor: 'rgba(0, 12, 43, 0.5)',
            borderWidth: 0.1
          },
          label: {
            show: false
          },
          emphasis: {
            label: {
              show: false
            }
          },
          // 饼图数据安全处理
          data: (data && data.topDepartments && Array.isArray(data.topDepartments)) 
            ? data.topDepartments.map((item: any, idx: number) => ({
                value: item.prescriptionCount,
                name: item.department,
                itemStyle: { color: pieColors[idx % pieColors.length] }
              }))
            : []
        }
      ]
    };
  };

  // 环形进度图配置，percent为百分比，color为主色
  const getCircleOption = (percent: number, color: string) => {
    return {
      series: [
        {
          type: 'gauge',
          radius: '100%',
          startAngle: 90,
          endAngle: -270,
          pointer: {
            show: false
          },
          progress: {
            show: true,
            overlap: false,
            roundCap: true,
            clip: false,
            itemStyle: {
              // 渐变色，180度，从上到下
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#E6F2FF' },
                { offset: 1, color: '#66B3FF' }
              ])
            }
          },
          axisLine: {
            lineStyle: {
              width: 3,
              color: [[1, 'rgba(255, 255, 255, 0.1)']]
            }
          },
          splitLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            show: false
          },
          title: {
            show: false
          },
          detail: {
            show: false // 隐藏ECharts自带的文字
          },
          data: [{
            value: percent
          }]
        }
      ]
    };
  };

  // 确保字体大小变化时图表重新渲染
  useEffect(() => {
    circleChartRefs.current.forEach((chart, index) => {
      if (chart) {
        const instance = chart.getEchartsInstance();
        if (instance) {
          instance.setOption(getCircleOption(
            index === 0 ? Math.round((data?.taskStatistics?.currentDirectRate || 0) * 100) :
            index === 1 ? Math.round((data?.prescriptionStatistics?.machinePrescriptionRate || 0) * 100) :
            Math.round((data?.drugDispensingStatistics?.machineBoxRate || 0) * 100),
            metrics[index].color
          ));
        }
      }
    });
  }, [circleFontSize, data]);

  // 渲染指标卡片，文案不变，只用metrics的value/change
  const renderMetricCard = (item: MetricItem, index: number) => {
    // 百分比和箭头颜色
    let percentColor = '#FFB74D';
    if (item.changeType === 'down') percentColor = '#44E695';
    if (item.changeType === 'zero') percentColor = '#FF6B6B';
    // 环形图百分比
    let percent = 0;
    if (index === 0) percent = Math.round((data?.taskStatistics?.currentDirectRate || 0) * 100);
    if (index === 1) percent = Math.round((data?.prescriptionStatistics?.machinePrescriptionRate || 0) * 100);
    if (index === 2) percent = Math.round((data?.drugDispensingStatistics?.machineBoxRate || 0) * 100);
    return (
      <MetricCard key={index}>
        <CircleChart>
          {/* 添加绝对定位的大字体百分比 */}
          <PercentText>{percent}%</PercentText>
          <ReactECharts
            key={`circle-chart-${index}-${circleFontSize}`}
            ref={(el) => setCircleChartRef(el, index)}
            option={getCircleOption(percent, item.color)}
            style={{ height: '100%', width: '100%' }}
            opts={{ renderer: 'canvas' }}
          />
        </CircleChart>
        <MetricData>
          <div className="title">{item.title}</div>
          <div className="value">{item.value}</div>
          <div className="change">
            {index == 0?'直发率':index == 1?'机发率':'机发率'}较上月
            <span className="percent-arrow">
              <span className="percent" style={{color: percentColor}}>{item.change}</span>
              {/* 箭头图片，up为上，down为下，zero不显示 */}
              {item.changeType === 'up' && (
                <img className="arrow-img" src="/arrow_up.png" alt="up" />
              )}
              {item.changeType === 'down' && (
                <img className="arrow-img" src="/arrow_down.png" alt="down" />
              )}
            </span>
          </div>
        </MetricData>
      </MetricCard>
    );
  };

  // 组件渲染部分，数据未加载时显示加载状态
  if (!data) {
    return (
      <MedicineStatusPanel>
        <PanelHeader>发药状态一览</PanelHeader>
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: 'calc(100% - 1.6vw)' }}>
          <div style={{ color: '#7e9bcc', fontSize: '0.8vw' }}>数据加载中...</div>
        </div>
      </MedicineStatusPanel>
    );
  }

  return (
    <MedicineStatusPanel id="medicine-status-panel">
      <PanelHeader>发药状态一览</PanelHeader>
      <ContentLayout>
        <PieChartContainer>
          <ChartArea>
            <PieContentWrapper>
              <TopText>
                待发药:<span>{data?.pendingTaskCount ?? 0}</span>
              </TopText>
              <div style={{ height: '10vw', width: '10vw', flexShrink: 0 }}>
                <ReactECharts
                  ref={pieChartRef}
                  option={getPieOption()}
                  style={{ height: '100%', width: '100%' }}
                  opts={{ renderer: 'canvas' }}
                />
              </div>
            </PieContentWrapper>
          </ChartArea>
          <LegendArea>
            <PieChartTitle>待发药科室top5</PieChartTitle>
            <Legend>
              {/* 饼图图例，顺序与topDepartments一致，安全处理 */}
              {(data.topDepartments && Array.isArray(data.topDepartments)) 
                ? data.topDepartments.map((item: any, idx: number) => (
                    <LegendItem key={idx} color={pieColors[idx % pieColors.length]}>
                      <div className="color-block"></div>
                      <div className="item-text">{item.department}</div>
                    </LegendItem>
                  ))
                : null
              }
            </Legend>
          </LegendArea>
        </PieChartContainer>
        <MetricsLayout>
          {/* 三张指标卡片，文案顺序不变 */}
          {metrics.map((item, index) => renderMetricCard(item, index))}
        </MetricsLayout>
      </ContentLayout>
    </MedicineStatusPanel>
  );
};

export default MedicineStatusChart; 