import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import { apiGet } from '../../utils/request';
import { useDefaultDate, getSelectedMonthRange } from '../../App';
import useGlobalRefresh from '../../hooks/useGlobalRefresh';

// 组件容器样式
const ChartWrapper = styled.div`
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  border: 1px solid #2980B9;
`;

// 内容容器
const ContentContainer = styled.div`
  position: relative;
  width: 100%;
  height: 100%;
  background: url('/lanseshuangbiaopan.png') no-repeat center center;
  background-size: 90% auto;
  display: flex;
  align-items: center;
  justify-content: center;
`;

// 双仪表盘容器
const DualGaugeContainer = styled.div`
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 1vw 0vw;
`;

// 单个仪表盘容器
const GaugeContainer = styled.div`
  position: relative;
  width: 40%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-top: 1vw;
`;

// 主要数值显示
const MainValue = styled.div`
  font-size: 1.5vw;
  color: #FFFFFF;
  font-family: 'DingTalk JinBuTi', 'PingFang SC', sans-serif;
  text-align: center;
  margin-bottom: 0.5vw;
  text-shadow: 0 0 0.5vw rgba(255, 255, 255, 0.3);
`;

// 描述文字
const Description = styled.div`
  font-size: 0.8vw;
  color: #CCE6FF;
  text-align: center;
  font-family: 'Source Han Sans SC', 'PingFang SC', sans-serif;
`;

// 数据接口类型 - 根据新接口字段定义
interface PatientDrugPickupData {
  fifteenMinuteCount: number;        // 15分钟取药数量
  totalCount: number;                // 总取药数量
  fifteenMinutePickupRatio: number;  // 15分钟取药比例
  averagePickupTime: number;         // 平均取药时间（单位：分钟）
}

// 获取月份的开始和结束时间，优先使用默认时间
const getMonthRange = (defaultDateTime: string) => {
  // 如果有默认时间，优先使用默认时间；否则使用当前时间
  const baseDate = defaultDateTime ? new Date(defaultDateTime) : new Date();
  const year = baseDate.getFullYear();
  const month = baseDate.getMonth(); // 0-11
  
  // 当月第一天
  const startDate = new Date(year, month, 1);
  // 当月最后一天
  const endDate = new Date(year, month + 1, 0);
  
  // 格式化为 YYYY-MM-DD
  const formatDate = (date: Date) => {
    const y = date.getFullYear();
    const m = String(date.getMonth() + 1).padStart(2, '0');
    const d = String(date.getDate()).padStart(2, '0');
    return `${y}-${m}-${d}`;
  };
  
  return {
    startTime: formatDate(startDate),
    endTime: formatDate(endDate)
  };
};

const DualGaugeChart: React.FC = () => {
  const [data, setData] = useState<PatientDrugPickupData>({ 
    fifteenMinuteCount: 0, 
    totalCount: 0, 
    fifteenMinutePickupRatio: 0, 
    averagePickupTime: 0 
  });
  const [loading, setLoading] = useState(true);
  const { defaultDateTime, selectedMonth } = useDefaultDate();

  // 获取数据
  const fetchData = async () => {
    try {
      setLoading(true);
      
      // 使用选中月份获取时间范围，支持月份选择功能
      const { startTime, endTime } = getSelectedMonthRange(defaultDateTime, selectedMonth);
      
      const response = await apiGet('/stageStats/ptDrugPickupTime', {
        params: {
          startTime,
          endTime
        }
      });
      
      if (response.data && response.data.data) {
        setData(response.data.data);
      } else {
        console.warn('取药效率监控 - 接口返回格式不符合预期:', response.data);
        // 设置为默认值，不使用模拟数据
        setData({ fifteenMinuteCount: 0, totalCount: 0, fifteenMinutePickupRatio: 0, averagePickupTime: 0 });
      }
    } catch (error) {
      console.error('获取取药效率监控数据失败:', error);
      // 设置为默认值，不使用模拟数据
      setData({ fifteenMinuteCount: 0, totalCount: 0, fifteenMinutePickupRatio: 0, averagePickupTime: 0 });
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时和依赖变化时获取数据
  useEffect(() => {
    fetchData();
  }, [defaultDateTime, selectedMonth]);

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

  return (
    <ChartWrapper>
      <ContentContainer>
        <DualGaugeContainer>
          {/* 左侧仪表盘 - 15分钟取药比例 */}
          <GaugeContainer>
            <MainValue>
              {loading ? '--' : `${(data.fifteenMinutePickupRatio * 100).toFixed(2)}%`}
            </MainValue>
            <Description>15分钟取药比例</Description>
          </GaugeContainer>
          
          {/* 右侧仪表盘 - 平均取药时间 */}
          <GaugeContainer>
            <MainValue>
              {loading ? '--' : `${data.averagePickupTime.toFixed(1)}分钟`}
            </MainValue>
            <Description>平均取药时间</Description>
          </GaugeContainer>
        </DualGaugeContainer>
      </ContentContainer>
    </ChartWrapper>
  );
};

export default DualGaugeChart; 