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

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

// 面板容器
const ForecastPanel = 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 CardsLayout = styled.div`
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: calc(100% - 1.6vw);
  /* padding: 1vw 2vw; */
`;

// 单个卡片
const Card = styled.div`
  width: 32%;
  height: 13vw;
  min-width: 180px;
  min-height: 180px;
  border-radius: 0.5vw;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  position: relative;
`;

// 环形进度条区域
const CircleArea = styled.div`
  width: 5vw;
  height: 5vw;
  min-width: 70px;
  min-height: 70px;
  margin-right: 0.5vw;
  margin-bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
`;

// 右侧内容区域，设置背景图
const CardRight = styled.div`
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
  width: 70%;
  height: 42%;
  background: url('/jinriyucezongliang_bg.png') no-repeat;
  background-size: contain;
  background-position: 0 2vw;
  border-radius: 0.5vw;
  padding-left: 1.5vw;
`;

// 标题和数值
const CardTitle = styled.div`
  color: #CCE6FF;
  font-size: 0.6vw;
  margin-bottom: 0.3vw;
  margin-top: 0.2vw;
`;
const CardValue = styled.div`
  color: #fff;
  font-size: 1.5vw;
  /* font-weight: bold; */
  margin-bottom: 0.2vw;
  font-family: 'DingTalk JinBuTi', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
`;

// 百分比文本，绝对居中
const PercentText = styled.div<{color: string}>`
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: ${props => props.color};
  font-size: 1vw;
  /* font-weight: bold; */
  font-family: 'DingTalk JinBuTi', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
`;

// 获取环形进度条option，percent为百分比，color为主色
const getCircleOption = (percent: number, color: string) => ({
  series: [
    {
      type: 'gauge',
      radius: '100%',
      startAngle: 90,
      endAngle: -270,
      pointer: { show: false },
      progress: {
        show: true,
        overlap: false,
        roundCap: true,
        clip: false,
        itemStyle: { color }
      },
      axisLine: {
        lineStyle: {
          width: 6,
          color: [
            [percent / 100, color], // 达成部分
            [1, '#26334D'] // 未达成部分
          ]
        }
      },
      splitLine: { show: false },
      axisTick: { show: false },
      axisLabel: { show: false },
      title: { show: false },
      detail: { show: false },
      data: [{ value: percent }]
    }
  ]
});

const TodayForecastTotalChart: React.FC = () => {
  // 自适应：监听窗口变化，强制刷新echarts
  const chartRefs = [useRef<ReactECharts>(null), useRef<ReactECharts>(null), useRef<ReactECharts>(null)];
  // 卡片数据，初始为0，后续用接口数据替换
  const [cardData, setCardData] = useState([
    {
      title: '预测人数（人）',
      value: 0,
      percent: 0,
      color: '#7FBEFF',
      percentColor: '#7FBEFF',
      bg: '/jinriyucezongliang_bg.png'
    },
    {
      title: '预测处方（张）',
      value: 0,
      percent: 0,
      color: '#44E6CB',
      percentColor: '#44E6CB',
      bg: '/jinriyucezongliang_bg.png'
    },
    {
      title: '预测药盒（盒）',
      value: 0,
      percent: 0,
      color: '#FFEA80',
      percentColor: '#FFEA80',
      bg: '/jinriyucezongliang_bg.png'
    }
  ]);

  // 获取数据函数
  const fetchData = useCallback(() => {
    if (useMock) {
      // 使用模拟数据
      setCardData([
        {
          title: '预测人数（人）',
          value: 0,
          percent: 0,
          color: '#7FBEFF',
          percentColor: '#7FBEFF',
          bg: '/jinriyucezongliang_bg.png'
        },
        {
          title: '预测处方（张）',
          value: 0,
          percent: 0,
          color: '#44E6CB',
          percentColor: '#44E6CB',
          bg: '/jinriyucezongliang_bg.png'
        },
        {
          title: '预测药盒（盒）',
          value: 0,
          percent: 0,
          color: '#FFEA80',
          percentColor: '#FFEA80',
          bg: '/jinriyucezongliang_bg.png'
        }
      ]);
    } else {
      // 使用实际API
      const dateTime = getDefaultDate();
      apiGet('/todayData/todayDispensingForecast', { params: { dateTime } })
        .then(res => {
          if (res.data && res.data.data) {
            const d = res.data.data;
            setCardData([
              {
                title: '预测人数（人）',
                value: d?.taskForecast?.forecastCount ?? 0,
                percent: d?.taskForecast?.rate ? Math.round(d.taskForecast.rate * 1000) / 10 : 0,
                color: '#7FBEFF',
                percentColor: '#fff',
                bg: '/jinriyucezongliang_bg.png'
              },
              {
                title: '预测处方（张）',
                value: d?.prescriptionForecast?.forecastCount ?? 0,
                percent: d?.prescriptionForecast?.rate ? Math.round(d.prescriptionForecast.rate * 1000) / 10 : 0,
                color: '#44E6CB',
                percentColor: '#fff',
                bg: '/jinriyucezongliang_bg.png'
              },
              {
                title: '预测药盒（盒）',
                value: d?.drugBoxForecast?.forecastCount ?? 0,
                percent: d?.drugBoxForecast?.rate ? Math.round(d.drugBoxForecast.rate * 1000) / 10 : 0,
                color: '#FFEA80',
                percentColor: '#fff',
                bg: '/jinriyucezongliang_bg.png'
              }
            ]);
          }
        })
        .catch(error => {
          console.error('获取今日预测总量数据失败:', error);
        });
    }
  }, [useMock]);

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

  useEffect(() => {
    const handleResize = () => {
      chartRefs.forEach(ref => {
        if (ref.current) ref.current.getEchartsInstance().resize();
      });
    };
    window.addEventListener('resize', handleResize);
    setTimeout(handleResize, 200);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return (
    <ForecastPanel>
      <PanelHeader>今日预测总量</PanelHeader>
      <CardsLayout>
        {cardData.map((item, idx) => (
          <Card key={idx}>
            <CircleArea>
              <ReactECharts
                ref={chartRefs[idx]}
                option={getCircleOption(item.percent, item.color)}
                style={{ width: '100%', height: '100%' }}
                opts={{ renderer: 'canvas' }}
              />
              <PercentText color={item.percentColor}>{item.percent}%</PercentText>
            </CircleArea>
            <CardRight>
              <CardTitle>{item.title}</CardTitle>
              <CardValue>{item.value}</CardValue>
            </CardRight>
          </Card>
        ))}
      </CardsLayout>
    </ForecastPanel>
  );
};

export default TodayForecastTotalChart; 