import arrowRightIcon from '@/assets/images/arrow-right.png';
import locationIcon from '@/assets/images/location.png';
import pipeMapCenter1 from '@/assets/images/pipe-map-center-1.png';
import pipeMapCenter2 from '@/assets/images/pipe-map-center-2.png';
import pipeMapDetail from '@/assets/images/pipe-map-detail.png';
import CooglMap from '@/components/CooglMap';
import { useGlobalModalServices } from '@/pages/GlobalModalServices/provider';
import services from '@/services';
import { Tree } from 'antd';
import type { DataNode } from 'antd/es/tree';
import React, { useEffect, useRef, useState } from 'react';
import styles from './index.less';

// 添加类型定义
interface PipelineType {
  type: string;
  name: string;
  items: any[];
  expanded: boolean;
  count?: number; // 添加数量属性
}

const Map: React.FC = () => {
  const { dispatch } = useGlobalModalServices();
  const [isListVisible, setIsListVisible] = useState(true);
  const [selectedLayers, setSelectedLayers] = useState<string[]>([
    'pipeline',
    'monitor',
  ]);
  const [pipelineData, setPipelineData] = useState<any[]>([]);
  const [pipelineCoords, setPipelineCoords] = useState<any[]>([]);
  const mapRef = useRef<any>();
  // const [currentLocationMarker, setCurrentLocationMarker] = useState<any>(null);
  const [selectedPipeline, setSelectedPipeline] = useState<any>(null);
  const [activeTab, setActiveTab] = useState<string>('pipeline');
  const [activeType, setActiveType] = useState<string>('');

  // 修改默认展开状态为空数组（都收起）
  const [expandedTypes, setExpandedTypes] = useState<string[]>([]);

  // 修改状态结构，记录每个类型的显示状态
  // const [selectedSubLayers, setSelectedSubLayers] = useState<Record<string, boolean>>({
  //   '干线': true,
  //   '支线': true,
  //   '小型': true,
  //   '缆线': true
  // });

  // 修改为使用 Tree 的选中状态管理
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([
    'pipeline',
    'monitor',
    'pipeline-干线',
    'pipeline-支线',
    'pipeline-小型',
    'pipeline-缆线',
  ]);

  // 将管廊数据按类型分组
  const groupedPipelines = pipelineData.reduce((acc: any, cur: any) => {
    const type = cur.lx || '其他';
    if (!acc[type]) {
      acc[type] = [];
    }
    acc[type].push({
      id: cur.id,
      name: cur.mc,
      ...cur,
    });
    return acc;
  }, {});

  // 修改 pipelineTypes 的定义，添加数量显示
  const pipelineTypes: PipelineType[] = [
    {
      type: '干线',
      name: '干线',
      items: groupedPipelines['干线'] || [],
      expanded: expandedTypes.includes('干线'),
      count: groupedPipelines['干线']?.length || 0,
    },
    {
      type: '支线',
      name: '支线',
      items: groupedPipelines['支线'] || [],
      expanded: expandedTypes.includes('支线'),
      count: groupedPipelines['支线']?.length || 0,
    },
    {
      type: '小型',
      name: '小型',
      items: groupedPipelines['小型'] || [],
      expanded: expandedTypes.includes('小型'),
      count: groupedPipelines['小型']?.length || 0,
    },
    {
      type: '缆线',
      name: '缆线',
      items: groupedPipelines['缆线'] || [],
      expanded: expandedTypes.includes('缆线'),
      count: groupedPipelines['缆线']?.length || 0,
    },
  ];

  // 构建 Tree 的数据结构
  const treeData: DataNode[] = [
    {
      title: '管廊',
      key: 'pipeline',
      children: pipelineTypes.map((type) => ({
        title: (
          <div className={styles.subLayer}>
            <span
              className={styles.dot}
              style={{
                background:
                  type.type === '干线'
                    ? '#AD6BFF'
                    : type.type === '支线'
                    ? '#FDFFC6'
                    : type.type === '小型'
                    ? '#6FDCFF'
                    : '#4874FF',
              }}
            />
            <span>{type.name}</span>
          </div>
        ),
        key: `pipeline-${type.type}`,
      })),
    },
    {
      title: '监控中心',
      key: 'monitor',
      children: [
        {
          title: (
            <div className={styles.subLayer}>
              <img src={pipeMapCenter1} className={styles.subLayerImg} alt="" />
              <span>总控中心</span>
            </div>
          ),
          key: 'monitor-总控',
        },
        {
          title: (
            <div className={styles.subLayer}>
              <img src={pipeMapCenter2} className={styles.subLayerImg} alt="" />
              <span>分控中心</span>
            </div>
          ),
          key: 'monitor-分控',
        },
      ],
    },
  ];

  // 获取管廊基本信息
  const getPipelineData = async (lx?: string) => {
    try {
      const res = await services.DataBase.getSjdzInfoData({
        typeCode: 'hyzm-gl-gldxlb',
        params: {
          startTime: '',
          endTime: '',
          glId: '',
          pageSize: '1000',
          pageNo: '0',
          lx: lx || '',
        },
      });
      if (res.code === 200) {
        console.log('==>获取管廊基本信息');
        const records = res.data?.data?.records || [];
        // console.log('==>records', records);
        setPipelineData(records);
      }
    } catch (error) {
      console.error('获取管廊数据失败:', error);
    }
  };

  // 获取管廊坐标信息
  const getPipelineCoords = async () => {
    try {
      const res = await services.DataBase.getWgjzInfoData({
        typeCode: 'wg-hdwg',
        data: {
          industryCode: '0402',
          gridType: '05',
        },
      });
      if (res.code === 0) {
        console.log('==>获取管廊坐标');
        const records = res.data?.responsibilityGrid || [];
        // 处理坐标数据
        const processedCoords = records
          .map((coord: any) => {
            try {
              const coordsObj = JSON.parse(coord.gridRange);
              if (coordsObj?.coordinates?.[0]?.length >= 2) {
                // 确保坐标格式正确：[[lng, lat], [lng, lat], ...]
                const formattedCoords = coordsObj.coordinates
                  .map((point: any) => [Number(point[0]), Number(point[1])])
                  .filter(
                    (point: number[]) => !isNaN(point[0]) && !isNaN(point[1]),
                  );

                return {
                  ...coord,
                  processedCoordinates: formattedCoords,
                };
              }
              return null;
            } catch (error) {
              console.error('解析坐标数据失败:', error);
              return null;
            }
          })
          .filter(Boolean);

        setPipelineCoords(processedCoords);
      }
    } catch (error) {
      console.error('获取管廊坐标失败:', error);
    }
  };

  useEffect(() => {
    getPipelineData();
    getPipelineCoords();
  }, []);

  // 绘制管廊路线
  const drawPipelines = () => {
    if (!mapRef.current || !pipelineCoords?.length) return;

    // 清除已有的路线
    mapRef.current.clearOverlays?.();

    pipelineCoords.forEach((item: any) => {
      if (!item.processedCoordinates?.length) return;

      return drawPipelinesFromCoord(item);
    });
  };

  // 绘制管廊路线
  const drawPipelinesFromCoord = (item: any) => {
    // 找到对应的管廊基本信息
    const pipelineInfo = pipelineData.find((p) => p.mc === item.gridName);
    const type = pipelineInfo?.lx;

    // 只渲染有类型且类型被选中的线路
    if (!type || !checkedKeys.includes(`pipeline-${type}`)) {
      return null;
    }

    return (
      <CooglMap.Polyline
        key={item.id}
        points={item.processedCoordinates}
        lineColor={
          type === '干线'
            ? '#AD6BFF'
            : type === '支线'
            ? '#FDFFC6'
            : type === '小型'
            ? '#6FDCFF'
            : '#4874FF'
        }
        width={3}
        onClick={() => handlePipelineClick(item)}
      />
    );
  };

  // 监听选中图层变化时重新绘制
  useEffect(() => {
    if (selectedLayers.includes('pipeline')) {
      drawPipelines();
    } else {
      mapRef.current?.clearOverlays?.();
    }
  }, [selectedLayers, pipelineCoords]);

  // 处理定位点击
  const handleLocationClick = (item: any) => {
    try {
      // 找到对应的坐标数据
      const coordData = pipelineCoords.find(
        (coord) => coord.gridName === item.mc,
      );
      if (!coordData?.processedCoordinates?.length) {
        console.warn('未找到对应的坐标数据');
        return;
      }

      // 获取线路的中点作为定位点
      const midIndex = Math.floor(coordData.processedCoordinates.length / 2);
      const locationPoint = coordData.processedCoordinates[midIndex];

      if (!locationPoint) {
        console.warn('无法获取定位点坐标');
        return;
      }

      // 使用 flyTo 进行定位
      mapRef.current?.flyTo({
        destination: {
          x: Number(locationPoint[0]),
          y: Number(locationPoint[1]),
          z: 2000,
        },
      });

      // 显示管廊信息
      setSelectedPipeline({
        ...item,
        position: locationPoint,
        coordData,
      });
    } catch (error) {
      console.error('定位失败:', error);
    }
  };

  // 处理详情点击
  const handleDetailClick = (item: any) => {
    const coordData = pipelineCoords.find(
      (coord) => coord.gridName === item.mc,
    );
    if (!coordData?.processedCoordinates?.length) {
      console.warn('未找到对应的坐标数据');
      return;
    }

    dispatch.push(
      'PipeGalleryDetail',
      {
        title: `${item.name}综合管廊`,
        props: {
          metaData: item,
          coordData: coordData,
        },
      },
      1,
    );
  };

  // 处理管廊点击
  const handlePipelineClick = (item: any) => {
    console.log('处理管廊点击', item);
    // TODO: 打开详情弹窗
    setSelectedPipeline(item);
  };

  // 处理类型展开/收起
  const toggleTypeExpand = (type: string) => {
    setExpandedTypes((prev) =>
      prev.includes(type) ? prev.filter((t) => t !== type) : [...prev, type],
    );
  };

  // 自定义 Tab 组件
  const TabHeader = () => (
    <div className={styles.tabHeader}>
      <div
        className={`${styles.tabItem} ${
          activeTab === 'pipeline' ? styles.active : ''
        }`}
        onClick={() => setActiveTab('pipeline')}
      >
        管廊列表
      </div>
      <div
        className={`${styles.tabItem} ${
          activeTab === 'monitor' ? styles.active : ''
        }`}
        onClick={() => setActiveTab('monitor')}
      >
        监控中心
      </div>
    </div>
  );

  // 处理列表项点击
  const handleItemClick = (type: string, item: any) => {
    setActiveType(type);
    handleLocationClick(item);
  };

  // 处理 Tree 选中变化
  const onCheck = (checked: any) => {
    // console.log('==>checked', checked);

    // 如果取消选中管廊总图层，同时取消所有子图层
    if (selectedLayers.includes('pipeline') && !checked.includes('pipeline')) {
      const newChecked = checked.filter(
        (key: string) => !key.startsWith('pipeline'),
      );
      setCheckedKeys(newChecked);
      setSelectedLayers(newChecked);
      return;
    }

    // 如果选中管廊总图层，同时选中所有子图层
    if (!selectedLayers.includes('pipeline') && checked.includes('pipeline')) {
      const allPipelineKeys = pipelineTypes.map(
        (type) => `pipeline-${type.type}`,
      );
      setCheckedKeys([...checked, ...allPipelineKeys]);
      setSelectedLayers(checked.filter((key: string) => !key.includes('-')));
      return;
    }

    // 正常更新选中状态
    setCheckedKeys(checked);
    setSelectedLayers(checked.filter((key: string) => !key.includes('-')));
  };

  // 过滤需要显示的管廊数据
  const filteredPipelineCoords = pipelineCoords.filter((item) => {
    // 首先检查是否选中了管廊图层
    if (!selectedLayers.includes('pipeline')) return false;

    // 找到对应的管廊基本信息来获取类型
    const pipelineInfo = pipelineData.find((p) => p.mc === item.gridName);
    const type = pipelineInfo?.lx;

    // 检查该类型是否被选中
    const typeKey = `pipeline-${type}`;
    // 只有当类型存在且该类型被选中时才显示
    return type && checkedKeys.includes(typeKey);
  });

  return (
    <div className={styles.container}>
      <CooglMap.MapView
        ref={mapRef}
        center={{ x: 103.96, y: 30.658842 }}
        zoom={8}
        mode="3D"
      >
        {/* 左上角标题 */}
        <div className={styles.mapTitle}>管廊分布</div>

        {/* 管廊路线图层 */}
        {filteredPipelineCoords.map((item: any) => {
          return drawPipelinesFromCoord(item);
        })}

        {/* 监控中心图层 */}
        {selectedLayers.includes('monitor') && (
          <>
            {/* {checkedKeys.includes('monitor-总控') && (
              <CooglMap.Marker
                key="monitor-总控"
                position={[104.06, 30.67]}
                icon={pipeMapCenter1}
                width={20}
                height={20}
              />
            )}
            {checkedKeys.includes('monitor-分控') && (
              <CooglMap.Marker
                key="monitor-分控"
                position={[104.08, 30.65]}
                icon={pipeMapCenter2}
                width={20}
                height={20}
              />
            )} */}
          </>
        )}

        {/* 选中管廊的信息展示 */}
        {selectedPipeline && (
          // drawPipelinesDetail()
          <CooglMap.CustomOverlay
            position={[
              Number(selectedPipeline.position[0]),
              Number(selectedPipeline.position[1]),
            ]}
            offset={{
              top: -20,
            }}
            onClose={() => {
              setSelectedPipeline(null);
            }}
            onDetail={() => {
              handleDetailClick(selectedPipeline);
            }}
          >
            <div className={styles.pipelineInfo}>
              <div className={styles.infoHeader}>
                <span className={styles.title}>{selectedPipeline.mc}</span>
                <span className={styles.closeBtn} data-event-key="close">
                  ×
                </span>
              </div>
              <div className={styles.infoContent}>
                <div className={styles.infoItem}>
                  <span className={styles.label}>所属区域：</span>
                  <span className={styles.value}>
                    {selectedPipeline.region_name || '-'}
                  </span>
                </div>
                <div className={styles.infoItem}>
                  <span className={styles.label}>管理长度：</span>
                  <span className={styles.value}>
                    {selectedPipeline.cd || '-'}千米
                  </span>
                </div>
                <div className={styles.infoItem}>
                  <span className={styles.label}>运营管理单位：</span>
                  <span className={styles.value}>
                    {selectedPipeline.gldw || '-'}
                  </span>
                </div>
              </div>
              <div className={styles.infoFooter}>
                <button className={styles.detailBtn} data-event-key="detail">
                  查看详情
                </button>
              </div>
            </div>
          </CooglMap.CustomOverlay>
        )}

        {/* 图层控制 */}
        <div className={styles.layerControl}>
          <div className={styles.title}>图层图例</div>
          <Tree
            checkable
            checkStrictly
            checkedKeys={checkedKeys}
            onCheck={(checked: any) => onCheck(checked.checked)}
            // onCheck={checked => onCheck(checked.checked)}
            treeData={treeData}
            defaultExpandAll
            // showLine={false}  // 添加此属性，隐藏展开/折叠按钮
            // switcherIcon={<div></div>} // 添加此属性，隐藏展开/折叠按钮 -- 自定义树节点的展开/折叠图标（带有默认 rotate 角度样式）
          />
        </div>

        {/* 右侧列表 */}
        <div
          className={`${styles.listContainer} ${
            !isListVisible && styles.collapsed
          }`}
        >
          {/* 收起按钮 */}
          <div
            className={styles.collapseBtn}
            onClick={() => setIsListVisible(!isListVisible)}
          >
            <div className={styles.text}>
              <span>{isListVisible ? '收' : '展'}</span>
              <span>{isListVisible ? '起' : '开'}</span>
              <img
                className={`${styles.arrowIcon} ${
                  !isListVisible && styles.reverse
                }`}
                src={arrowRightIcon}
                alt=""
              />
            </div>
          </div>

          <div className={styles.listContent}>
            <TabHeader />

            {/* 管廊列表内容 */}
            {activeTab === 'pipeline' && (
              <div className={styles.pipelineList}>
                {pipelineTypes.map((type) => (
                  <div key={type.type}>
                    <div
                      className={`${styles.typeGroup} ${
                        activeType === type.type ? styles.active : ''
                      }`}
                    >
                      <div className={styles.typeHeader}>
                        <div className={styles.typeTitle}>
                          <span>{type.name}</span>
                          <span className={styles.count}>({type.count})</span>
                        </div>
                        <span
                          className={`${styles.expandIcon} ${
                            type.expanded ? styles.expanded : ''
                          }`}
                          onClick={() => toggleTypeExpand(type.type)}
                        />
                      </div>
                    </div>

                    {/* 二级菜单 */}
                    {type.expanded && (
                      <div className={styles.itemList}>
                        {type.items?.map((item: any) => (
                          <div
                            key={item.id}
                            className={`${styles.listItem} ${
                              activeType === type.type ? styles.active : ''
                            }`}
                            onClick={() => handleItemClick(type.type, item)}
                          >
                            <span className={styles.itemName}>{item.mc}</span>
                            <div className={styles.itemActions}>
                              <img
                                src={locationIcon}
                                alt="定位"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  setActiveType(type.type);
                                  handleLocationClick(item);
                                }}
                              />
                              <img
                                src={pipeMapDetail}
                                alt="详情"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  handleDetailClick(item);
                                }}
                              />
                            </div>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                ))}
              </div>
            )}

            {/* 监控中心列表内容 */}
            {activeTab === 'monitor' && (
              <div className={styles.monitorList}>
                {/* TODO: 实现监控中心列表 */}
              </div>
            )}
          </div>
        </div>
      </CooglMap.MapView>
    </div>
  );
};

export default Map;
