import { MyPageContainer } from '@/common';
import { getTodayDate } from '@/common/utils/day';
import { mapKey } from '@/common/utils/mapConfig';
import { Apis } from '@/gen/Apis';
import { LeftOutlined } from '@ant-design/icons';
import { ProCard } from '@ant-design/pro-components';
import { useNavigate, useParams } from '@umijs/max';
import { Button, DatePicker, Space } from 'antd';
import dayjs from 'dayjs';
import * as L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import { useEffect, useRef } from 'react';
import './style.scss';
const dateFormat = 'YYYY/MM/DD';
export default function Index({ title = '员工轨迹' }) {
  const navigate = useNavigate();
  const { id } = useParams<{ id: string }>();
  const mapRef = useRef<HTMLDivElement>(null);
  const mapInstanceRef = useRef<L.Map | null>(null);
  // 初始化地图
  const initMap = () => {
    if (!mapRef.current) return;

    // 创建地图实例
    const map = L.map(mapRef.current, {
      center: [30.258134, 120.19382669582967], // 默认中心点（长江三角洲）
      zoom: 10,
      maxZoom: 18,
      zoomControl: false,
      attributionControl: false,
    });

    // 添加天地图底图层（矢量地图）
    L.tileLayer(
      `https://t{s}.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=${mapKey}`,
      {
        subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
        attribution: '天地图',
        minZoom: 1,
        maxZoom: 18,
      },
    ).addTo(map);

    // 添加天地图文字描述层（矢量注记）
    L.tileLayer(
      `https://t{s}.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=${mapKey}`,
      {
        subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
        attribution: '天地图',
        minZoom: 1,
        maxZoom: 18,
      },
    ).addTo(map);

    mapInstanceRef.current = map;
  };

  // 显示轨迹
  const showTrack = (data: any[]) => {
    if (!mapInstanceRef.current) return;

    const map = mapInstanceRef.current;

    // 首先清除所有旧的轨迹（无论是否有新数据）
    map.eachLayer((layer: L.Layer) => {
      if (layer instanceof L.Polyline || layer instanceof L.Marker) {
        map.removeLayer(layer);
      }
    });

    // 如果没有新的轨迹数据，直接返回
    if (!data || data.length === 0) return;

    // 过滤有效坐标并保留原始数据
    const validPoints = data.filter(
      (point) => point.latitude && point.longitude,
    );

    // 转换为Leaflet可识别的坐标格式
    const trackPoints: L.LatLngTuple[] = validPoints.map(
      (point) =>
        [
          parseFloat(point.latitude),
          parseFloat(point.longitude),
        ] as L.LatLngTuple,
    );

    // 如果过滤后没有有效坐标，返回
    if (trackPoints.length === 0) return;

    // 创建轨迹线
    const trackLine = L.polyline(trackPoints, {
      color: '#f00',
      weight: 4,
      opacity: 1,
    }).addTo(map);

    // 添加起点标记
    const startMarker = L.marker(trackPoints[0], {
      icon: L.divIcon({
        className: 'track-start-marker',
        html: "<img width='40' height='40' src='https://gc-prod-1385694945.cos.ap-shanghai.myqcloud.com/uploads/cs-test/01KH0R6TZSPBNF3X8ARGXE5R6C.png' />",
      }),
    }).addTo(map);

    // 为起点添加弹窗
    const startPoint = validPoints[0];
    startMarker.bindPopup(`
      <div style="padding: 10px;">
        <h4 style="margin: 0 0 10px 0; color: #333;">起点</h4>
        <p><strong>序号:</strong> 1</p>
        <p><strong>时间:</strong> ${startPoint.track_time || '未知'}</p>
        <p><strong>坐标:</strong> ${startPoint.latitude}, ${
      startPoint.longitude
    }</p>
      </div>
    `);

    // 添加终点标记
    const endMarker = L.marker(trackPoints[trackPoints.length - 1], {
      icon: L.divIcon({
        className: 'track-end-marker',
        html: "<img width='40' height='40' src='https://gc-prod-1385694945.cos.ap-shanghai.myqcloud.com/uploads/cs-test/01KH0STS12KMARBH8F9SJVCN1S.png' />",
      }),
    }).addTo(map);

    // 为终点添加弹窗
    const endPoint = validPoints[validPoints.length - 1];
    endMarker.bindPopup(`
      <div style="padding: 10px;">
        <h4 style="margin: 0 0 10px 0; color: #333;">终点</h4>
        <p><strong>序号:</strong> ${validPoints.length}</p>
        <p><strong>时间:</strong> ${endPoint.track_time || '未知'}</p>
        <p><strong>坐标:</strong> ${endPoint.latitude}, ${
      endPoint.longitude
    }</p>
      </div>
    `);

    // 为每个轨迹点添加序号标记和弹窗
    trackPoints.forEach((point, index) => {
      // 跳过起点和终点，只标记中间点
      if (index === 0 || index === trackPoints.length - 1) return;

      const currentPoint = validPoints[index];
      const marker = L.marker(point, {
        icon: L.divIcon({
          className: 'track-point-marker',
          html: `<div style="width: 24px; height: 24px; border-radius: 50%; background-color: #3498db; color: white; display: flex; align-items: center; justify-content: center; font-size: 12px; font-weight: bold; box-shadow: 0 2px 4px rgba(0,0,0,0.2);">${
            index + 1
          }</div>`,
          iconSize: [24, 24],
        }),
      }).addTo(map);

      // 为中间点添加弹窗
      marker.bindPopup(`
        <div style="padding: 10px;">
          <h4 style="margin: 0 0 10px 0; color: #333;">点位 ${index + 1}</h4>
          <p><strong>时间:</strong> ${currentPoint.track_time || '未知'}</p>
          <p><strong>坐标:</strong> ${currentPoint.latitude}, ${
        currentPoint.longitude
      }</p>
        </div>
      `);
    });

    // 自动调整地图视图以显示整个轨迹
    map.fitBounds(trackLine.getBounds());
  };

  const loadShow = (day: any) => {
    // showTrack([
    //   { latitude: 22.566729, longitude: 114.062952 },
    //   { latitude: 22.567982, longitude: 114.06278 },
    //   { latitude: 22.569394, longitude: 114.062694 },
    // ]);
    Apis.Attendance.AttendanceEmployeeTracks.Heatmap({
      company_employees_id: Number(id),
      date: day, // 转换为Date类型
    }).then((res) => {
      console.log(res);
      // 假设API返回的数据结构为{ data: [{ latitude, longitude, time }, ...] }
      showTrack(res?.data);
      // setTrackData(res.data || []);
    });
  };
  useEffect(() => {
    // 初始化地图
    initMap();
    // 加载轨迹数据
    loadShow(new Date(getTodayDate()));

    // 组件卸载时清理地图实例
    return () => {
      if (mapInstanceRef.current) {
        mapInstanceRef.current.remove();
        mapInstanceRef.current = null;
      }
    };
  }, [id]);

  // // 当轨迹数据变化时，显示轨迹
  // useEffect(() => {
  //   if (trackData.length > 0) {
  //     showTrack(trackData);
  //   }
  // }, [trackData]);

  return (
    <MyPageContainer
      enableTabs
      tabKey="attendance-employee-tracks"
      tabLabel={title}
      title={title}
    >
      <ProCard
        title={
          <Button
            type="link"
            size="small"
            icon={<LeftOutlined />}
            onClick={() => navigate(-1)}
          >
            员工轨迹底图
          </Button>
        }
        headerBordered
        extra={
          <DatePicker
            defaultValue={dayjs(getTodayDate(), dateFormat)}
            format={dateFormat}
            onChange={(e: any, dateString: any) => {
              loadShow(dateString);
            }}
          />
        }
      >
        <div
          ref={mapRef}
          style={{
            width: '100%',
            height: 'calc(100vh - 200px)',
            borderRadius: '8px',
            overflow: 'hidden',
            border: '1px solid #e8e8e8',
          }}
        />
        <Space
          style={{
            paddingTop: '15px',
            fontSize: '12px',
            display: 'flex',
            alignItems: 'center',
          }}
        >
          <div
            style={{
              fontSize: '12px',
              display: 'flex',
              alignItems: 'center',
            }}
          >
            <span>起点：</span>
            <img
              src="https://gc-prod-1385694945.cos.ap-shanghai.myqcloud.com/uploads/cs-test/01KH0R6TZSPBNF3X8ARGXE5R6C.png"
              width="18"
              height="18"
            />
          </div>
          <div
            style={{
              fontSize: '12px',
              display: 'flex',
              alignItems: 'center',
            }}
          >
            <span>终点：</span>
            <img
              src="https://gc-prod-1385694945.cos.ap-shanghai.myqcloud.com/uploads/cs-test/01KH0STS12KMARBH8F9SJVCN1S.png"
              width="18"
              height="18"
            />
          </div>
        </Space>
      </ProCard>
    </MyPageContainer>
  );
}
