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

// 组件容器样式 - 确保完全填充Grid单元格
const ChartWrapper = styled.div`
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;

  box-sizing: border-box;
  display: flex;
  flex-direction: column;
`;

// 组件标题 - 使用与其他模块相同的样式
const PanelHeader = styled.div`
  position: relative;
  width: 95%;
  height: 1.6vw;
  min-height: 1.6vw;
  max-height: 1.6vw;
  padding-left: 5.5%;
  text-align: left;
  line-height: 1.6vw;
  font-size: 0.8vw;
  color: #E6F2FF;
  font-family: 'DingTalk JinBuTi', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  background: url('/component_header_bg.png') no-repeat;
  background-size: 100% 100%;
  flex-shrink: 0;
`;

// 图表容器 - 占据剩余空间
const ChartContainer = styled.div`
  width: 100%;
  flex: 1;
  padding: 1vw 1.5vw 1vw 1vw;
  box-sizing: border-box;
  overflow: hidden;
`;

// 图表项容器
const ChartItem = styled.div`
  display: flex;
  align-items: center;
  width: 100%;
  height: 8.5%;
  margin-bottom: 0.8%;
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif !important;
  
  &:last-child {
    margin-bottom: 0;
  }
`;

// 科室名称
const DepartmentName = styled.div`
  width: 6vw;
  font-size: 0.65vw;
  color: #FFFFFF;
  text-align: left;
  white-space: nowrap;
  overflow: hidden;
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif !important;
  text-overflow: ellipsis;
  margin-right: 0.8vw;
`;

// 进度条容器
const ProgressBarContainer = styled.div`
  flex: 1;
  height: 0.3vw;
  border-radius: 0.05vw;
  position: relative;
  margin-right: 0.8vw;
`;

// 进度条
const ProgressBar = styled.div<{ percentage: number }>`
  height: 100%;
  width: ${props => props.percentage}%;
  background: linear-gradient(90deg, #65CCFF 0%, #CBEEFF 100%);
  border-radius: 0.1vw;
  transition: width 0.8s ease-in-out;
`;

// 数值显示
const ValueDisplay = styled.div`
  width: 2.5vw;
  font-size: 0.65vw;
  color: #FFFFFF;
  text-align: right;
  font-weight: normal;
`;

// 数据类型定义
interface DepartmentData {
  department: string;
  prescriptionCount: number;
}

const DepartmentPrescriptionTop10Chart: React.FC = () => {
  const [data, setData] = useState<DepartmentData[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const { defaultDateTime, selectedMonth } = useDefaultDate();

  // 获取数据
  const fetchData = async () => {
    try {
      setLoading(true);
      
      // 使用选中月份获取时间范围，支持月份选择功能
      const { startTime, endTime } = getSelectedMonthRange(defaultDateTime, selectedMonth);
      
      const response = await apiGet('/stageStats/deptPrescriptionTop', {
        params: {
          startTime,
          endTime
        }
      });
      
      if (response.data && response.data.data && Array.isArray(response.data.data)) {
        // 最多只取前10条数据
        const limitedData = response.data.data.slice(0, 10);
        setData(limitedData);
      } else {
        console.warn('科室处方量Top10 - 接口返回格式不符合预期:', response.data);
        // 设置为空数组，不使用模拟数据
        setData([]);
      }
    } catch (error) {
      console.error('获取科室处方量Top10数据失败:', error);
      // 设置为空数组，不使用模拟数据
      setData([]);
    } finally {
      setLoading(false);
    }
  };

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

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

  // 计算百分比
  const maxValue = data.length > 0 ? Math.max(...data.map(item => item.prescriptionCount)) : 0;
  const getPercentage = (value: number) => {
    return maxValue > 0 ? (value / maxValue) * 100 : 0;
  };

  return (
    <ChartWrapper>
      <PanelHeader>科室处方量Top10</PanelHeader>
      <ChartContainer>
        {loading ? (
          <div style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '100%',
            color: '#CCE6FF',
            fontSize: '0.8vw'
          }}>
            数据加载中...
          </div>
        ) : (
          <>
            {data.map((item, index) => (
              <ChartItem key={index}>
                <DepartmentName>{item.department}</DepartmentName>
                <ProgressBarContainer>
                  <ProgressBar percentage={getPercentage(item.prescriptionCount)} />
                </ProgressBarContainer>
                <ValueDisplay>{item.prescriptionCount}</ValueDisplay>
              </ChartItem>
            ))}
          </>
        )}
      </ChartContainer>
    </ChartWrapper>
  );
};

export default DepartmentPrescriptionTop10Chart; 