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 { apiGet } from '../../utils/request'; // 引入统一带前缀的apiGet方法
import { getDefaultDate } from '../../App'; // 导入获取默认日期的函数
import useGlobalRefresh from '../../hooks/useGlobalRefresh'; // 导入全局刷新钩子

// 面板容器
const WindowPanel = 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 MainLayout = styled.div`
  display: flex;
  height: calc(100% - 1.6vw);
  width: 100%;
`;

// 左侧柱状图区域
const ChartArea = styled.div`
  flex: 7;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
`;

// 右侧统计卡片区域
const StatArea = styled.div`
  flex: 3;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
`;

// 统计卡片主容器，左右结构
const StatCard = styled.div`
  width: 95%;
  height: 90%;
  margin-left: 2%;
  background: none;
  border: none;
  display: flex;
  flex-direction: row;
  align-items: stretch;
  justify-content: center;
`;

// 左侧统计区，透明，仅负责居中
const StatLeft = styled.div`
  width:35%;
  min-width: 70px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
`;

// 白色描边卡片，直接用背景图，不再设置border、圆角
const StatLeftCard = styled.div`
  width: 95%;
  height: 98%;
  background: url('/yujingdizuo_bg.png') no-repeat;
  background-size: 100% 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 1vw 0.5vw;
  box-sizing: border-box;
`;

// 条纹区纯色背景，flex纵向堆叠，gap分隔条块
const StatLeftBar = styled.div`
  width: 98%;
  height: 5vw;
  min-height: 70px;
  background: none; // 父容器不再用渐变
  border-radius: 0.1vw;
  margin: 0.5vw 0 0 0;
  position: relative;
  /* overflow: hidden; */
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  gap: 0.13vw; // 条块间距自适应
`;

// 条纹横线，绝对定位
const StatBarLine = styled.div`
  width: 100%;
  height: 2px;
  background: rgba(255,255,255,0.4);
  position: absolute;
  left: 0;
`;

const StatLeftNum = styled.div`
  color: #fff;
  font-size: 1vw;
  /* font-weight: bold; */
  font-family: 'DingTalk JinBuTi', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  margin-bottom: 0.5vw;
`;

const StatLeftLabel = styled.div`
  position: relative;
  top:0.6vw;
  color: #fff;
  font-size: 0.7vw;
  margin-top: 0.2vw;
  text-align: center;
`;
const StatLeftSub = styled.div`
  position: relative;
  color: #CCE6FF;
  font-size: 0.7vw;
  top:0.5vw;
  text-align: center;
`;

// 右侧上下分块容器，整体加背景图，右上右下圆角
const StatRight = styled.div`
  width: 45%;
  margin-left:1%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;
  background: url('/chuangkoushudizuo_bg.png') no-repeat;
  background-size: 100% 100%;
`;

// 右侧分块，不加背景图，仅做分块色块和内容排版
const StatRightBlock = styled.div<{top?: boolean, bottom?: boolean}>`
  flex: 1;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  margin-bottom: ${props => props.top ? '0.2vw' : '0'};
  margin-top: ${props => props.bottom ? '0.2vw' : '0'};
`;

// 优化数字样式，大号，居中
const StatRightNum = styled.div`
  color: #fff;
  font-size: 1.8vw;
  /* font-weight: bold; */
  text-align: center;
  line-height: 2.7vw;
  margin-top: 0.5vw;
  font-family: 'DingTalk JinBuTi', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
`;

// 优化说明文字样式，小号，数字下方，居中
const StatRightLabel = styled.div`
  color: #CCE6FF;
  font-size: 0.6vw;
  text-align: center;
  margin-top: 0.2vw;
`;

// 优化圆点样式
const StatDot = styled.span<{color: string}>`
  display: inline-block;
  width: 0.4vw;
  height: 0.4vw;
  border-radius: 50%;
  background: ${props => props.color};
  margin-right: 0.1vw;
`;

const chartData = {
  xAxis: ['窗口1', '窗口2', '窗口3', '窗口4', '窗口5', '窗口6', '窗口7', '窗口8'],
  wait: [30, 120, 60, 40, 80, 200, 50, 40],
  finish: [10, 80, 30, 20, 40, 150, 20, 30]
};

// 计算条块渐变色（线性插值）
function getGradientColor(startColor: string, endColor: string, percent: number) {
  const start = [
    parseInt(startColor.slice(1, 3), 16),
    parseInt(startColor.slice(3, 5), 16),
    parseInt(startColor.slice(5, 7), 16)
  ];
  const end = [
    parseInt(endColor.slice(1, 3), 16),
    parseInt(endColor.slice(3, 5), 16),
    parseInt(endColor.slice(5, 7), 16)
  ];
  const r = Math.round(start[0] + (end[0] - start[0]) * percent);
  const g = Math.round(start[1] + (end[1] - start[1]) * percent);
  const b = Math.round(start[2] + (end[2] - start[2]) * percent);
  return `rgb(${r},${g},${b})`;
}

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

// 定义窗口状态项类型（放在组件外部）
interface WindowStatusItem {
  windowtransferdesc: string;
  dispensingwindow: number;
  windowsstatus: number;
  dispensingtype: number;
  pendingPreparationCount: number;
  pendingDispensingCount: number;
}

const WindowMonitorChart: React.FC = () => {
  const chartRef = useRef<ReactECharts>(null);
  // 柱形图圆角和字体自适应
  const [barRadius, setBarRadius] = useState(6); // 默认6
  const [barFontSize, setBarFontSize] = useState(12); // 默认12（用于柱顶标签、图例等）
  const [axisFontSize, setAxisFontSize] = useState(12); // 坐标轴字号
  const [dotFontSize, setDotFontSize] = useState(14); // x轴状态圆点字号（与坐标轴分离）

  // 动态计算圆角和字体大小
  const calcBarRadius = () => {
    const container = document.getElementById('window-monitor-panel');
    if (container) {
      const width = container.offsetWidth;
      const radius = Math.max(2, Math.min(16, Math.floor(width * 0.006)));
      setBarRadius(radius);
      // 自适应字体大小：柱顶/图例用（保持原范围）
      const fontSize = Math.max(10, Math.min(18, Math.floor(width * 0.012)));
      setBarFontSize(fontSize);
      // 自适应坐标轴字体大小：略小一些
      const axisSize = Math.max(10, Math.min(20, Math.floor(width * 0.013)));
      setAxisFontSize(axisSize);
      // 自适应圆点字号：略微调小整体尺寸
      const dotSize = Math.max(axisSize + 6, Math.min(40, Math.floor(width * 0.023)));
      setDotFontSize(dotSize);
    }
  };

  useEffect(() => {
    calcBarRadius();
    window.addEventListener('resize', calcBarRadius);
    setTimeout(calcBarRadius, 200);
    return () => window.removeEventListener('resize', calcBarRadius);
  }, []);

  // 组件state，初始为空，后续用mock或接口数据填充
  const [windowData, setWindowData] = useState<{
    pendingPreparationCount: number;
    onlineWindowCount: number;
    advisedWindowCount: number;
    windowsstatusList: WindowStatusItem[];
  }>({
    pendingPreparationCount: 0,
    onlineWindowCount: 0,
    advisedWindowCount: 0,
    windowsstatusList: []
  });

  // 获取数据函数
  const fetchData = useCallback(() => {
    if (useMock) {
      // mock模式下用本地mock数据
      setWindowData({
        pendingPreparationCount: 0,
        onlineWindowCount: 4,
        advisedWindowCount: 4,
        windowsstatusList: [
          { windowtransferdesc: '03', dispensingwindow: 1, windowsstatus: 1, dispensingtype: 1, pendingPreparationCount: 0, pendingDispensingCount: 0 },
          { windowtransferdesc: '1', dispensingwindow: 2, windowsstatus: 1, dispensingtype: 1, pendingPreparationCount: 0, pendingDispensingCount: 0 },
          { windowtransferdesc: '2', dispensingwindow: 3, windowsstatus: 1, dispensingtype: 1, pendingPreparationCount: 0, pendingDispensingCount: 0 },
          { windowtransferdesc: '2H', dispensingwindow: 4, windowsstatus: 1, dispensingtype: 1, pendingPreparationCount: 0, pendingDispensingCount: 0 }
        ]
      });
      // 如需定时模拟更新，可加定时器
    } else {
      // 正式环境下用接口数据 
      const dateTime = getDefaultDate();
      apiGet('/todayData/windowMonitor', { params: { dateTime } })
        .then(res => {
          if (res.data && res.data.data) {
            setWindowData(res.data.data || {
              pendingPreparationCount: 0,
              onlineWindowCount: 0,
              advisedWindowCount: 0,
              windowsstatusList: []
            });
          }
        })
        .catch(error => {
          console.error('获取窗口监控数据失败:', error);
        });
    }
  }, [useMock]);

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

  // 右侧统计数据
  const totalWait = windowData.pendingPreparationCount;
  const online = windowData.onlineWindowCount;
  const suggest = windowData.advisedWindowCount;

  // 条行堆叠总数始终为15
  const totalBars = 16;
  // 条块间距百分比
  const barGapPercent = 8;
  // 每条色块的高度百分比
  const barHeightPercent = (100 - (totalBars - 1) * barGapPercent) / totalBars;
  // 高亮色块数量，35人=15条，25人=11条，15人=7条
  const highlightCount = Math.min(totalBars, Math.ceil(totalWait / (35/15)));
  // 渐变色定义，纵向渐变（底部浅，顶部深）
  const greenBar = 'linear-gradient(180deg, #A0FFE6 0%, #44E6CB 100%)'; // 绿色纵向渐变
  const yellowBar = 'linear-gradient(180deg, #FFF6A0 0%, #FFD666 100%)'; // 黄色纵向渐变
  const redBar = 'linear-gradient(180deg, #FF9A9E 0%, #FF6B6B 100%)';   // 红色纵向渐变
  const grayBar = 'linear-gradient(180deg, rgba(200,200,200,0.08) 0%, rgba(255,255,255,0.15) 100%)'; // 灰色纵向渐变
  // 颜色分档
  let barGradient = greenBar;
  if (totalWait > 30) barGradient = redBar;
  else if (totalWait >= 15) barGradient = yellowBar;

  // x轴状态点颜色，前6个在线，后2个离线
  const xAxisStatus = ['online','online','online','online','online','online','offline','offline'] as const;
  const xAxisStatusColor: { [key: string]: string } = {
    online: '#44E695',
    offline: '#FF3456',
    2: '#2D4F72' // 新增状态2，颜色为#2D4F72
  };

  const xAxisData = windowData.windowsstatusList.map(item => item.windowtransferdesc);

  // 柱状图option，圆角和字体自适应
  const getBarOption = () => ({
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      textStyle: { fontSize: barFontSize }, // tooltip字体自适应
      formatter: function(params: any) {
        // 获取当前窗口信息
        const index = params[0].dataIndex;
        const windowInfo = windowData.windowsstatusList[index];
        if (!windowInfo) return '';
        
        let statusText = '未知';
        let statusColor = '#999999';
        if (windowInfo.windowsstatus === 0) {
          statusText = '离线';
          statusColor = '#FF3456';
        } else if (windowInfo.windowsstatus === 1) {
          statusText = '在线';
          statusColor = '#44E695';
        } else if (windowInfo.windowsstatus === 2) {
          statusText = '待机';
          statusColor = '#2D4F72';
        }
        
        return `
          <div style="font-size:${barFontSize}px;padding:3px 6px;">
            <div style="margin-bottom:5px;font-weight:bold;">${windowInfo.windowtransferdesc}</div>
            <div>
              <span style="display:inline-block;width:8px;height:8px;border-radius:4px;background:${statusColor};margin-right:5px;"></span>
              <span>状态: ${statusText}</span>
            </div>
            <div style={{color: '#CCE6FF'}}>待配人数: ${params[0].value || 0}</div>
            <div style={{color: '#CCE6FF'}}>待发人数: ${params.length > 1 ? params[1].value || 0 : 0}</div>
          </div>
        `;
      }
    },
    legend: {
      data: ['待配人数', '待发人数'],
      left: 5,
      top: 10,
      textStyle: { color: '#CCE6FF', fontSize: barFontSize * 1.2 }, // 图例字体增大
      itemWidth: 14, // 调整图例色块宽度
      itemHeight: 10, // 调整图例色块高度
      itemGap: 20, // 增加图例项之间的间距
      show: true // 确保图例显示
    },
    grid: {
      left: '2%', right: '3%', bottom: '5%', top: '18%', containLabel: true
    },
    // x轴用窗口名称
    xAxis: {
      type: 'category',
      data: xAxisData,
      axisLine: { lineStyle: { color: 'rgba(255,,255,0.3)' } },
      axisLabel: {
        color: '#CCE6FF',
        fontSize: axisFontSize,
        align: 'center',
        interval: 0,
        rotate: 0,
        formatter: function(value: string) {
          // 找到当前窗口对象
          const item = windowData.windowsstatusList.find(i => i.windowtransferdesc === value);
          if (!item) return value;
          
          // 使用正确的属性名
          const windowObj = item as any;
          const status = windowObj.windowstatus;
          
          // 根据状态返回不同rich文本样式
          if (status === 0) return '{dotRed|●} ' + value;
          if (status === 1) return '{dotGreen|●} ' + value;
          if (status === 2) return '{dotBlue|●} ' + value;
          return '{dotGray|●} ' + value;
        },
        rich: {
          dotRed: { color: '#FF3456', fontSize: dotFontSize, padding: [0, Math.floor(dotFontSize * 0.2), 0, 0], fontFamily: 'DingTalk JinBuTi, PingFang SC, Microsoft YaHei, Arial, sans-serif' },
          dotGreen: { color: '#44E695', fontSize: dotFontSize, padding: [0, Math.floor(dotFontSize * 0.2), 0, 0], fontFamily: 'DingTalk JinBuTi, PingFang SC, Microsoft YaHei, Arial, sans-serif' },
          dotBlue: { color: '#2D4F72', fontSize: dotFontSize, padding: [0, Math.floor(dotFontSize * 0.2), 0, 0], fontFamily: 'DingTalk JinBuTi, PingFang SC, Microsoft YaHei, Arial, sans-serif' },
          dotGray: { color: '#999999', fontSize: dotFontSize, padding: [0, Math.floor(dotFontSize * 0.2), 0, 0], fontFamily: 'DingTalk JinBuTi, PingFang SC, Microsoft YaHei, Arial, sans-serif' }
        }
      },
      axisTick: { alignWithLabel: true }
    },
    yAxis: {
      type: 'value',
      max: function() {
        // 取所有待取人数和待发人数的最大值
        const maxValue = Math.max(
          ...windowData.windowsstatusList.map(item => item.pendingPreparationCount || 0),
          ...windowData.windowsstatusList.map(item => item.pendingDispensingCount || 0)
        );
        
        if (maxValue === 0) return 8; // 避免全为0时y轴异常
        
        // 更智能地计算最大值，避免产生不均匀刻度
        if (maxValue <= 6) return 6;  // 如果数据最大值不超过6，直接用6
        if (maxValue <= 8) return 8;  // 如果数据最大值不超过8，直接用8
        if (maxValue <= 10) return 10; // 数据在8-10之间，直接用10
        
        // 将最大值调整为2的倍数，保证刻度均匀
        return Math.ceil(maxValue * 1.2 / 2) * 2;
      },
      min: 0, // 确保从0开始
      minInterval: 2, // 确保刻度间隔至少为2
      interval: 2, // 固定间隔为2
      splitNumber: 4, // 减少分割数量
      axisLine: { show: false },
      axisTick: { show: false },
      splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)', type: 'dashed' } },
      axisLabel: { 
        color: '#CCE6FF', 
        fontSize: axisFontSize
      }
    },
    // series用窗口的待取人数和待发人数
    series: [
      {
        name: '待配人数',
        type: 'bar',
        barWidth: 18,
        itemStyle: {
          // 蓝色渐变
          color: {
            type: 'linear', x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              { offset: 0, color: '#80BFFF' },
              { offset: 1, color: 'rgba(128,191,255,0)' }
            ]
          },
          borderRadius: [barRadius, barRadius, 0, 0] // 圆角自适应
        },
        label: {
          show: true,
          position: 'top',
          color: '#CCE6FF',
          fontSize: barFontSize,
          fontFamily: 'DingTalk JinBuTi',
          formatter: function(params: any) {
            return params.value > 0 ? params.value : '';
          }
        },
        data: windowData.windowsstatusList.map(item => item.pendingPreparationCount)
      },
      {
        name: '待发人数',
        type: 'bar',
        barWidth: 18,
        itemStyle: {
          // 黄色渐变
          color: {
            type: 'linear', x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              { offset: 0, color: '#FFEA81' },
              { offset: 1, color: 'rgba(255,234,128,0)' }
            ]
          },
          borderRadius: [barRadius, barRadius, 0, 0] // 圆角自适应
        },
        label: {
          show: true,
          position: 'top',
          color: '#CCE6FF',
          fontSize: barFontSize,
          fontFamily: 'DingTalk JinBuTi',
          formatter: function(params: any) {
            return params.value > 0 ? params.value : '';
          }
        },
        data: windowData.windowsstatusList.map(item => item.pendingDispensingCount)
      }
    ]
  });

  return (
    <WindowPanel id="window-monitor-panel">
      <PanelHeader>窗口监控</PanelHeader>
      <MainLayout>
        <ChartArea>
          <ReactECharts
            ref={chartRef}
            option={getBarOption()}
            style={{ width: '100%', height: '100%' }}
            opts={{ renderer: 'canvas' }}
          />
        </ChartArea>
        <StatArea>
          <StatCard>
            <StatLeft>
              <StatLeftCard>
                <StatLeftNum>{totalWait}人</StatLeftNum>
                <StatLeftBar>
                  {[...Array(totalBars)].map((_, i) => {
                    const percent = 1 - i / (totalBars - 1); // 下浅上深
                    const color = i < highlightCount
                      ? getGradientColor('#FFE6A0', '#FF6B6B', percent)
                      : '#1F3759';
                    return (
                      <div
                        key={i}
                        style={{
                          flex: 1,
                          marginBottom: i !== totalBars - 1 ? '0.05vw' : 0,
                          background: color,
                          // borderRadius:
                          //   i === 0
                          //     ? '0 0 0.3vw 0.3vw'
                          //     : i === totalBars - 1
                          //     ? '0.3vw 0.3vw 0 0'
                          //     : 0
                        }}
                      />
                    );
                  })}
                </StatLeftBar>
                <StatLeftLabel>待配预警</StatLeftLabel>
                <StatLeftSub>&gt;10分钟</StatLeftSub>
              </StatLeftCard>
            </StatLeft>
            <StatRight>
              <StatRightBlock top style={{flexDirection:'column',justifyContent:'center',alignItems:'flex-start',paddingLeft:'1vw'}}>
                <div style={{display:'flex',alignItems:'center',justifyContent:'center',marginTop:'0.5vw'}}>
                  <StatDot color="#44E6CB" />
                  <StatRightLabel style={{marginTop:0,marginLeft:'0.3vw'}}>
                    在线窗口数
                  </StatRightLabel>
                </div>
                <StatRightNum>{online}</StatRightNum>
              </StatRightBlock>
              <StatRightBlock bottom style={{flexDirection:'column',justifyContent:'center',alignItems:'flex-start',paddingLeft:'1vw'}}>
                <div style={{display:'flex',alignItems:'center',justifyContent:'center',marginTop:'0.5vw'}}>
                  <StatDot color="#7FBEFF" />
                  <StatRightLabel style={{marginTop:0,marginLeft:'0.3vw'}}>
                    建议开窗数
                  </StatRightLabel>
                </div>
                <StatRightNum>{suggest}</StatRightNum>
              </StatRightBlock>
            </StatRight>
          </StatCard>
        </StatArea>
      </MainLayout>
    </WindowPanel>
  );
};

export default WindowMonitorChart; 