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

// 组件容器样式
const ChartWrapper = styled.div`
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  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`
  position: relative;
  width: 100%;
  flex: 1;
  padding: 0.5vw;
  overflow: hidden;
`;

// 表格容器 - 用于科室处方量Top10显示
const TableContainer = styled.div`
  width: 100%;
  flex: 1;
  overflow: hidden;
`;

// 科室图表容器 - 用于横向进度条样式
const DepartmentChartContainer = styled.div`
  width: 100%;
  flex: 1;
  padding: 1vw 1.5vw 1vw 1vw;
  box-sizing: border-box;
  overflow: hidden;
`;

// 科室图表项容器
const DepartmentChartItem = 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;
`;

// 表格样式
const Table = styled.table`
  width: 100%;
  height: 100%;
  border-collapse: collapse;
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif !important;
`;

// 表头样式
const TableHeader = styled.thead`
  tr {
    background:#051833;
  }
  
  th {
    padding: 0.3vw 1.2vw;
    font-size: 0.7vw;
    font-weight: normal;
    color: #CCE6FF;
    white-space: nowrap;
    font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif !important;
    
    &:first-child {
      width: 60%;
      text-align: left;
      padding-left: 3.2vw;
    }
    
    &:nth-child(2) {
      width: 40%;
      text-align: left;
    }
  }
`;

// 表体样式
const TableBody = styled.tbody`
  tr {
    &:nth-child(odd) {
      background: #162840;
    }
    
    &:nth-child(even) {
      background: #051833;
    }
    
    &:hover {
      background: rgba(6, 30, 93, 0.6);
    }
  }
  
  td {
    padding: 0.2vw 1.2vw;
    font-size: 0.65vw;
    color: #FFFFFF;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif !important;
    
    &:first-child {
      text-align: left;
      color: #FFFFFF;
    }
    
    &:nth-child(2) {
      text-align: left;
    }
  }
`;

// 排名号码样式
const RankNumber = styled.span<{ rank: number }>`
  display: inline-block;
  min-width: 1.5vw;
  text-align: center;
  font-size: 0.7vw;
  font-weight: bold;
  margin-right: 0.5vw;
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif !important;
  color: ${props => {
    if (props.rank <= 3) return '#FF4D6A';
    return '#CCE6FF';
  }};
`;

// 数据接口类型 - 处方盒数分布
interface PrescriptionBoxAnalysisData {
  drugCount: number;
  prescriptionCount: number;
  percent: number;
}

// 数据接口类型 - 科室处方量Top10
interface DepartmentData {
  department: string;
  prescriptionCount: number;
}



const PrescriptionBoxDistributionChart: React.FC = () => {
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<echarts.ECharts | null>(null);
  const [boxData, setBoxData] = useState<PrescriptionBoxAnalysisData[]>([]);
  const [departmentData, setDepartmentData] = useState<DepartmentData[]>([]);
  const [loading, setLoading] = useState(true);
  const { defaultDateTime, selectedMonth } = useDefaultDate();
  
  // 获取刷新配置，模块code为'36'
  const { defaultFlag } = useRefreshConfig('36');

  // 获取处方盒数分布数据
  const fetchBoxData = async () => {
    try {
      // 使用选中月份获取时间范围，支持月份选择功能
      const { startTime, endTime } = getSelectedMonthRange(defaultDateTime, selectedMonth);
      
      const response = await apiGet('/stageStats/prescriptionBoxAnalysis', {
        params: { startTime, endTime }
      });
      
      if (response.data && response.data.data && Array.isArray(response.data.data)) {
        setBoxData(response.data.data);
      } else {
        console.warn('处方盒数分布 - 接口返回格式不符合预期:', response.data);
        setBoxData([]);
      }
    } catch (error) {
      console.error('获取处方盒数分布数据失败:', error);
      setBoxData([]);
    }
  };

  // 获取科室处方量Top10数据
  const fetchDepartmentData = async () => {
    try {
      // 使用选中月份获取时间范围，支持月份选择功能
      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)) {
        const limitedData = response.data.data.slice(0, 10);
        setDepartmentData(limitedData);
      } else {
        console.warn('科室处方量Top10 - 接口返回格式不符合预期:', response.data);
        setDepartmentData([]);
      }
    } catch (error) {
      console.error('获取科室处方量Top10数据失败:', error);
      setDepartmentData([]);
    }
  };

  // 获取数据
  const fetchData = async () => {
    try {
      setLoading(true);
      if (defaultFlag) {
        await fetchBoxData();
      } else {
        await fetchDepartmentData();
      }
    } finally {
      setLoading(false);
    }
  };

  // 初始化图表
  const initChart = () => {
    if (!chartRef.current || boxData.length === 0) return;

    if (chartInstance.current) {
      chartInstance.current.dispose();
    }

    chartInstance.current = echarts.init(chartRef.current);

    const categories = boxData.map(item => {
      if (item.drugCount >= 15) {
        return '>14';
      }
      return `${item.drugCount}`;
    });

    const percentages = boxData.map(item => parseFloat((item.percent * 100).toFixed(2)));

    const option = {
      grid: {
        left: '0%',
        right: '0%',
        top: '5%',
        bottom: '0%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: categories,
        axisLine: {
          lineStyle: {
            color: '#1F324D'
          }
        },
        axisLabel: {
          color: '#CCE6FF',
          fontSize: '0.55vw',
          margin: 8
        },
        axisTick: {
          show: false
        }
      },
      yAxis: {
        type: 'value',
        min: 0,
        max: 18,
        interval: 2,
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: '#CCE6FF',
          fontSize: '0.55vw',
          formatter: '{value}%'
        },
        splitLine: {
          lineStyle: {
            color: '#1F324D',
            type: 'solid'
          }
        }
      },
      series: [
        {
          name: '处方盒数分布',
          type: 'bar',
          data: percentages,
          barWidth: '25%',
          itemStyle: {
            borderRadius: [2, 2, 0, 0],
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#99FFAA' },
              { offset: 1, color: 'rgba(153,255,170,0)' }
            ]),
          },
          emphasis: {
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#99FFAA' },
                { offset: 1, color: 'rgba(153,255,170,0.2)' }
              ])
            }
          },
          label: {
            show: false
          }
        }
      ],
      tooltip: {
        trigger: 'axis',
        backgroundColor: 'rgba(15, 35, 85, 0.95)',
        borderColor: 'rgba(0, 212, 255, 0.6)',
        borderWidth: 1,
        textStyle: {
          color: '#FFFFFF',
          fontFamily: 'DingTalk JinBuTi',
          fontSize: '0.6vw'
        },
        formatter: (params: any) => {
          const dataItem = boxData[params[0].dataIndex];
          if (!dataItem) return '';
          
          return `
            <div style="padding: 0.5vw;">
              <div style="font-size: 0.7vw; color: #CCE6FF; margin-bottom: 0.3vw;">
                ${params[0].name}
              </div>
              <div style="font-size: 0.65vw; color: #FFFFFF;">
                处方数量：${dataItem.prescriptionCount}张<br/>
                占比：${(dataItem.percent * 100).toFixed(1)}%
              </div>
            </div>`;
        }
      }
    };

    chartInstance.current.setOption(option);
  };

  // 监听数据变化，重新渲染图表
  useEffect(() => {
    if (defaultFlag && boxData.length > 0) {
      initChart();
    }
  }, [boxData, defaultFlag]);

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

  // 监听窗口大小变化，确保图表自适应
  useEffect(() => {
    const handleResize = () => {
      if (chartInstance.current) {
        chartInstance.current.resize();
      }
    };

    window.addEventListener('resize', handleResize);
    
    const resizeObserver = new ResizeObserver(() => {
      if (chartInstance.current) {
        chartInstance.current.resize();
      }
    });
    
    if (chartRef.current) {
      resizeObserver.observe(chartRef.current);
    }

    return () => {
      window.removeEventListener('resize', handleResize);
      resizeObserver.disconnect();
      if (chartInstance.current) {
        chartInstance.current.dispose();
      }
    };
  }, []);

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

  // 渲染处方盒数分布内容
  const renderBoxChart = () => (
    <>
      <PanelHeader>处方盒数分布</PanelHeader>
      <ChartContainer>
        <div 
          ref={chartRef} 
          style={{ 
            width: '100%', 
            height: '100%',
            opacity: loading ? 0.5 : 1,
            transition: 'opacity 0.3s ease'
          }} 
        />
      </ChartContainer>
    </>
  );

  // 渲染科室处方量Top10内容（横向进度条样式）
  const renderDepartmentChart = () => {
    // 计算百分比
    const maxValue = departmentData.length > 0 ? Math.max(...departmentData.map(item => item.prescriptionCount)) : 0;
    const getPercentage = (value: number) => {
      return maxValue > 0 ? (value / maxValue) * 100 : 0;
    };

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



  return (
    <ChartWrapper>
      {defaultFlag ? renderBoxChart() : renderDepartmentChart()}
    </ChartWrapper>
  );
};

export default PrescriptionBoxDistributionChart; 