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;
`;

// 表格容器 - 用于消耗药品Top8显示
const TableContainer = styled.div`
  width: 100%;
  flex: 1;
  overflow: hidden;
`;

// 表格样式
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: 35%;
      text-align: left;
      padding-left: 3.2vw;
    }
    
    &:nth-child(2) {
      width: 20%;
      text-align: left;
    }
    
    &:nth-child(3) {
      width: 45%;
      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;
    }
    
    &:nth-child(3) {
      text-align: left;
    }
  }
`;

// 排名号码样式
const RankNumber = styled.span<{ rank: string }>`
  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 => {
    const rankNum = parseInt(props.rank);
    if (rankNum <= 3) return '#FF4D6A';
    return '#CCE6FF';
  }};
`;

// 数据接口类型 - 处方品规数分布
interface PrescriptionSpecsAnalysisData {
  specificationCount: number;
  prescriptionCount: number;
  percent: number;
}

// 数据接口类型 - 消耗药品Top8
interface MedicineData {
  rank: string;
  drugName: string;
  drugSpec: string;
  firmName: string;
  amount: number;
}

const PrescriptionDistributionChart: React.FC = () => {
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<echarts.ECharts | null>(null);
  const [prescriptionData, setPrescriptionData] = useState<PrescriptionSpecsAnalysisData[]>([]);
  const [medicineData, setMedicineData] = useState<MedicineData[]>([]);
  const [loading, setLoading] = useState(true);
  const { defaultDateTime, selectedMonth } = useDefaultDate();
  
  // 获取刷新配置，模块code为'35'
  const { defaultFlag } = useRefreshConfig('35');

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

  // 获取消耗药品Top8数据
  const fetchMedicineData = async () => {
    try {
      // 使用选中月份获取时间范围，支持月份选择功能
      const { startTime, endTime } = getSelectedMonthRange(defaultDateTime, selectedMonth);
      
      const response = await apiGet('/stageStats/drugsConsumptionTop', {
        params: { startTime, endTime }
      });
      
      if (response.data && response.data.data && Array.isArray(response.data.data)) {
        const limitedData = response.data.data.slice(0, 8);
        setMedicineData(limitedData);
      } else {
        console.warn('消耗药品Top8 - 接口返回格式不符合预期:', response.data);
        setMedicineData([]);
      }
    } catch (error) {
      console.error('获取消耗药品Top8数据失败:', error);
      setMedicineData([]);
    }
  };

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

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

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

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

    const categories = prescriptionData.map(item => {
      if (item.specificationCount >= 8) {
        return '>7品';
      }
      return `${item.specificationCount}品`;
    });

    const percentages = prescriptionData.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.6vw',
          margin: 8
        },
        axisTick: {
          show: false
        }
      },
      yAxis: {
        type: 'value',
        min: 0,
        max: 45,
        interval: 5,
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: '#CCE6FF',
          fontSize: '0.55vw',
          formatter: '{value}%'
        },
        splitLine: {
          lineStyle: {
            color: '#1F324D',
            type: 'solid'
          }
        }
      },
      series: [{
        type: 'bar',
        data: percentages,
        barWidth: '40%',
        itemStyle: {
          borderRadius: [3, 3, 0, 0],
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#66B3FF' },
            { offset: 1, color: 'rgba(102,179,255,0)' }
          ])
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#66B3FF' },
              { offset: 1, color: 'rgba(102,179,255,0.2)' }
            ])
          }
        },
        label: {
          show: true,
          position: 'top',
          color: '#CCE6FF',
          fontSize: '0.6vw',
          formatter: (params: any) => `${params.value.toFixed(2)}%`
        }
      }],
      tooltip: {
        trigger: 'axis',
        backgroundColor: 'rgba(0, 20, 60, 0.9)',
        borderColor: '#4D88FF',
        borderWidth: 1,
        textStyle: {
          color: '#FFFFFF',
          fontSize: '0.7vw'
        },
        formatter: (params: any) => {
          const dataItem = prescriptionData[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 && prescriptionData.length > 0) {
      initChart();
    }
  }, [prescriptionData, 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, '35');

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

  // 渲染消耗药品Top8内容
  const renderMedicineTable = () => (
    <>
      <PanelHeader>消耗药品Top8</PanelHeader>
      <TableContainer>
        <Table>
          <TableHeader>
            <tr>
              <th>药品名称</th>
              <th>规格</th>
              <th>厂家</th>
            </tr>
          </TableHeader>
          <TableBody>
            {medicineData.length > 0 ? (
              medicineData.map((item, index) => (
                <tr key={index}>
                  <td>
                    <RankNumber rank={item.rank || (index + 1).toString()}>
                      {item.rank || (index + 1)}
                    </RankNumber>
                    {item.drugName}
                  </td>
                  <td>{item.drugSpec}</td>
                  <td>{item.firmName}</td>
                </tr>
              ))
            ) : (
              <tr>
                <td colSpan={3} style={{ textAlign: 'center', padding: '2vw' }}>
                  暂无数据
                </td>
              </tr>
            )}
          </TableBody>
        </Table>
      </TableContainer>
    </>
  );



  return (
    <ChartWrapper>
      {defaultFlag ? renderPrescriptionChart() : renderMedicineTable()}
    </ChartWrapper>
  );
};

export default PrescriptionDistributionChart; 