import React, { useState, useEffect, useRef } from 'react';
import { Modal, message } from 'antd';
import { Clock } from 'lucide-react';
import { slotApi, LockCabinetSlotVO, SlotPageParam } from '../../api/lockCabinet/slots';
import { systemAttributeApi } from '../../api/systemAttribute';
import { dateFormatter } from '../../utils/formatTime';

interface MapDataProps {
  cabinetId: string;
}

export default function MapData({ cabinetId }: MapDataProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [slotData, setSlotData] = useState<LockCabinetSlotVO[]>([]);
  const [updateTime, setUpdateTime] = useState<string | null>(null);
  const [dialogVisible, setDialogVisible] = useState(false);
  const [errorInfo, setErrorInfo] = useState('');
  const [cachedImages, setCachedImages] = useState<Record<string, HTMLImageElement>>({});
  const [cachedResults, setCachedResults] = useState<Record<string, string>>({});

  // 获取数据
  const getData = async () => {
    if (!cabinetId) return;

    const params: SlotPageParam = {
      pageNo: 1,
      pageSize: -1,
      cabinetId: Number(cabinetId),
    };

    try {
      const response = await slotApi.getIsLockCabinetSlotsPage(params);
      const slots = response.list || [];
      setSlotData(slots);
      if (slots.length > 0 && slots[0].createTime) {
        setUpdateTime(dateFormatter(slots[0].createTime));
      }

      // 获取图标配置
      const icons = [
        'icon.locker.normal',
        'icon.locker.out',
        'icon.padlock.normal',
        'icon.padlock.out',
        'icon.locker.exception'
      ];

      const results: Record<string, string> = {};
      for (const key of icons) {
        try {
          const attr = await systemAttributeApi.getIsSystemAttributeByKey(key);
          results[key] = attr.sysAttrValue || '';
        } catch (error) {
          console.error(`获取图标配置失败: ${key}`, error);
        }
      }
      setCachedResults(results);

      // 预加载图片
      await preloadImages(results);
    } catch (error: any) {
      console.error('获取数据失败:', error);
      message.error(error.message || '获取数据失败');
    }
  };

  // 预加载图片
  const preloadImages = async (results: Record<string, string>) => {
    const urls = Object.values(results).filter(url => url);
    const images: Record<string, HTMLImageElement> = {};

    for (const url of urls) {
      if (cachedImages[url]) {
        images[url] = cachedImages[url];
      } else {
        try {
          const img = await loadImage(url);
          images[url] = img;
        } catch (error) {
          console.error(`加载图片失败: ${url}`, error);
        }
      }
    }

    setCachedImages(prev => ({ ...prev, ...images }));
  };

  // 加载图片
  const loadImage = (url: string): Promise<HTMLImageElement> => {
    return new Promise((resolve, reject) => {
      const img = new Image();
      img.crossOrigin = 'Anonymous';
      img.src = url;
      img.onload = () => resolve(img);
      img.onerror = reject;
    });
  };

  // 绘制图形
  const drawCanvas = () => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    // 清空画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 按行分组
    const grouped: Record<number, LockCabinetSlotVO[]> = {};
    slotData.forEach(slot => {
      const row = slot.row || 0;
      if (!grouped[row]) grouped[row] = [];
      grouped[row].push(slot);
    });

    const rows = Object.keys(grouped).map(Number).sort((a, b) => a - b);
    const startY = 20;
    const rowHeight = 120;
    const rowGap = 20;
    const boxWidth = 860;
    const centerX = canvas.width / 2;
    const boxStartX = centerX - boxWidth / 2;

    rows.forEach((rowKey, rowIndex) => {
      const rowSlots = grouped[rowKey];

      // 绘制行容器
      ctx.strokeStyle = 'black';
      ctx.lineWidth = 2;
      ctx.strokeRect(
        boxStartX,
        startY + rowIndex * (rowHeight + rowGap),
        boxWidth,
        rowHeight
      );

      // 绘制仓位
      rowSlots.forEach((slot, slotIndex) => {
        const { slotType, isOccupied, status } = slot;
        let baseKey = '';

        if (slotType === '0') {
          baseKey = isOccupied === '1' ? 'icon.locker.normal' : 'icon.locker.out';
        } else {
          baseKey = isOccupied === '1' ? 'icon.padlock.normal' : 'icon.padlock.out';
        }

        const baseUrl = cachedResults[baseKey];
        const baseImg = baseUrl ? cachedImages[baseUrl] : null;

        const width = slotType === '0' ? 110 : 40;
        const height = 90;
        const padding = 20;
        const totalSlots = rowSlots.length;
        const spacing = totalSlots > 1
          ? (boxWidth - 2 * padding - totalSlots * width) / (totalSlots - 1)
          : 0;

        const x = boxStartX + padding + slotIndex * (width + spacing);
        const y = startY + rowIndex * (rowHeight + rowGap) + (rowHeight - height) / 2;

        // 绘制仓位图标
        if (baseImg) {
          ctx.drawImage(baseImg, x, y, width, height);
        } else {
          // 如果没有图片，绘制占位矩形
          ctx.fillStyle = '#f0f0f0';
          ctx.fillRect(x, y, width, height);
          ctx.strokeStyle = '#ccc';
          ctx.lineWidth = 1;
          ctx.strokeRect(x, y, width, height);
        }

        // 绘制异常图标
        if (status === '1') {
          const exUrl = cachedResults['icon.locker.exception'];
          const exImg = exUrl ? cachedImages[exUrl] : null;
          if (exImg) {
            const exWidth = 30;
            const exHeight = 30;
            ctx.drawImage(
              exImg,
              x + (width - exWidth) / 2,
              y + (height - exHeight) / 2,
              exWidth,
              exHeight
            );
          }
        }

        // 添加点击事件处理
        canvas.addEventListener('click', (e) => {
          const rect = canvas.getBoundingClientRect();
          const clickX = e.clientX - rect.left;
          const clickY = e.clientY - rect.top;

          if (clickX >= x && clickX <= x + width && clickY >= y && clickY <= y + height) {
            if (status === '1') {
              setErrorInfo(slot.remark || '未知异常');
              setDialogVisible(true);
            } else {
              console.log('点击仓位:', slot);
            }
          }
        });
      });
    });
  };

  useEffect(() => {
    if (cabinetId) {
      getData();
    }
  }, [cabinetId]);

  useEffect(() => {
    if (slotData.length > 0 && Object.keys(cachedImages).length > 0) {
      drawCanvas();
    }
  }, [slotData, cachedImages, cachedResults]);

  return (
    <div className="space-y-4">
      {/* 时间卡片 */}
      {updateTime && (
        <div className="inline-flex items-center gap-3 px-5 py-3 bg-gradient-to-r from-gray-50 to-gray-100 rounded-lg shadow-sm">
          <Clock className="w-5 h-5 text-blue-500" />
          <div>
            <div className="text-xs text-gray-500">最后更新</div>
            <div className="text-base font-bold text-gray-800">{updateTime}</div>
          </div>
        </div>
      )}

      {/* 画布容器 */}
      <div className="bg-white rounded-lg shadow-sm p-4 overflow-auto">
        <canvas
          ref={canvasRef}
          width={900}
          height={1000}
          className="border border-gray-200"
        />
      </div>

      {/* 异常信息对话框 */}
      <Modal
        title="异常信息"
        open={dialogVisible}
        onCancel={() => setDialogVisible(false)}
        footer={[
          <button
            key="close"
            onClick={() => setDialogVisible(false)}
            className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
          >
            关闭
          </button>
        ]}
      >
        <div className="text-center font-bold">{errorInfo}</div>
      </Modal>
    </div>
  );
}

