import AreaBarList, { AreaBarItem } from '@/components/V2504/AreaBarList';
import ModuleTitleWithTabs from '@/pages/Home_v_2504/components/common/ModuleTitleWithTabs';
import {
  useDataType,
  useMapState,
} from '@/pages/Home_v_2504/components/MapStateContext';
import { formatDateTime } from '@/pages/Home_v_2504/hooks/useApiControl';
import useLatestValue from '@/pages/Home_v_2504/hooks/useLatestValue';
import services from '@/services';
import { useRequest } from 'ahooks';
import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from 'react';
import styles from './index.less';

// 类型定义
export interface DeclaredEmissionProps {
  dateType?: string;
  dateRange?: { startTime: string; endTime: string };
  dataTypeKey?: string;
}

// 区域类型定义
export type AreaType = 'all' | 'urban' | 'central' | 'county';
const DeclaredEmission: React.FC<DeclaredEmissionProps> = ({
  dateType,
  dateRange,
  dataTypeKey = '建筑垃圾',
}) => {
  // 地图状态
  const { mapState } = useMapState();
  const mapStateRef = useLatestValue(mapState);

  // 当前选中的区域类型
  const [currentTab, setCurrentTab] = useState<AreaType>('all');
  const currentTabRef = useLatestValue(currentTab);
  const [searchParams, setSearchParams] = useState({startTime:undefined});
  // 环卫人员区域数据
  // const [data, setData] = useState<AreaBarItem[]>([]);
  const [data, setData] = useState<AreaBarItem[]>([
    { name: '锦江区', count: 456, percentage: 97.2 },
    { name: '金牛区', count: 400, percentage: 83.5 },
    { name: '成华区', count: 322, percentage: 70.8 },
    { name: '青羊区', count: 186, percentage: 65.6 },
    { name: '双流区', count: 152, percentage: 12.9 },
    { name: '武侯区', count: 122, percentage: 10.6 },
    { name: '龙泉驿区', count: 121, percentage: 10.5 },
    { name: '温江区', count: 120, percentage: 10.4 },
    { name: '新都区', count: 119, percentage: 10.3 },
    { name: '郫都区', count: 118, percentage: 10.2 },
    { name: '都江堰市', count: 117, percentage: 10.1 },
  ]);

  // 处理Tab切换
  const handleTabChange = (tab: string) => {
    setCurrentTab(tab as AreaType);
  };

  // 转换日期类型为API参数
  const translateDateType = useCallback((type: string) => {
    switch (type) {
      case 'year':
        return '1';
      case 'month':
        return '2';
      case 'day':
        return '3';
      case 'range':
        return '4';
      default:
        return '2'; // 默认月视图
    }
  }, []);

  // 区域编码生成函数
  const getRegionCodes = (areaType: AreaType, regionCode: string) => {
    // 默认所有区域
    if (areaType === 'all') {
      return regionCode.length > 4
        ? regionCode
        : regionCode === '5101'
        ? '510104,510105,510106,510107,510108,510112,510113,510114,510115,510116,510117,510121,510129,510131,510132,510181,510182,510183,510184,510185'
        : '';
    }

    // 城市新区
    if (areaType === 'urban') {
      return '510112,510113,510114,510115,510116,510117';
    }

    // 中心城区
    if (areaType === 'central') {
      return '510104,510105,510106,510107,510108';
    }

    // 县市新城
    if (areaType === 'county') {
      return '510121,510129,510131,510132,510181,510182,510183,510184,510185';
    }

    return '';
  };

  // 构建API请求参数
  const buildApiParams = useCallback(() => {
    const currentMapState = mapStateRef.current;

    // 如果没有必要的时间参数，返回null表示不应该发起请求
    if (
      !currentMapState.leftPanelTime?.startTime ||
      !currentMapState.leftPanelTime?.endTime
    ) {
      return null;
    }

    // 使用当前时间类型，如果不存在则使用props或默认值
    const effectiveType =
      currentMapState.leftPanelTime.type || dateType || 'month';

    // 基础参数对象
    const params: any = {
      type: translateDateType(effectiveType),
    };
    // 获取区域编码列表
    const districtCodeList = getRegionCodes(
      currentTabRef.current,
      currentMapState.regionCode,
    );
    if (districtCodeList) {
      params.districtCodeList = districtCodeList;
    }
    params.startTime = formatDateTime(currentMapState.leftPanelTime.startTime);
    params.endTime = formatDateTime(
      currentMapState.leftPanelTime.endTime,
      true,
    );

    // 处理区域参数
    if (currentMapState.regionCode === '5101') {
      // 成都，这两个参数就不传
      params.districtCode = undefined;
      params.streetCode = undefined;
    } else if (currentMapState.regionCode.length === 6) {
      // 区县级别
      params.districtCode = currentMapState.regionCode;
    } else if (currentMapState.regionCode.length === 9) {
      // 街道级别
      params.districtCode = currentMapState.regionCode.substring(0, 6);
      params.streetCode = currentMapState.regionCode;
    }

    // 使用传入的dataTypeKey获取对应的subTypeCode
    params.subTypeCode = useDataType(dataTypeKey);

    return params;
  }, [mapStateRef, currentTabRef, dateType, translateDateType, dataTypeKey]);

  // 跟踪上一次的API参数，避免重复调用
  const prevApiParamsRef = useRef<string>('');

  // 在地图状态变化和Tab变化时加载数据
  useEffect(() => {
    const params = buildApiParams();

    // 如果没有必要的参数，不发送请求
    if (!params) {
      console.log('缺少必要的日期参数，不加载环卫人员区域数据');
      return;
    }

    // 参数签名，用于比较参数是否有实际变化
    const paramsSignature = JSON.stringify(params);

    // 检查参数是否真正变化，防止重复调用
    if (paramsSignature === prevApiParamsRef.current) {
      console.log('环卫人员区域参数未变化，跳过重复加载');
      return;
    }
    setSearchParams(params);
    // 更新上一次参数签名
    prevApiParamsRef.current = paramsSignature;
  }, [mapState, currentTab, buildApiParams]);


  const { data: dumpData } = useRequest(
    () =>
      services.DataBase.getSjdzInfoData({
        typeCode: 'zzcc-jzlj-aqytjpfl',
        params: {
          ...searchParams,
        },
      }).then((res) => {
        if (res.code === 200) {
          return res?.data?.data?.records?.[0];
        }
        throw new Error('获取数据失败');
      }),
    {
      refreshDeps: [searchParams],
      manual: !searchParams?.startTime,
    },
  );

  const list = useMemo(() => {
    const code = getRegionCodes(currentTab, mapStateRef.current?.regionCode);

    if (!dumpData?.list?.length) return [];

    if (currentTab === 'all') {
      return dumpData?.list?.map((item: any) => ({
        name: item.areaName,
        count: item.num,
        percentage: ((item.num / dumpData?.total) * 100).toFixed(0),
      }));
    }

    return dumpData?.list
      ?.filter((item: any) => code.includes(item.area))
      .map((item: any) => ({
        name: item.areaName,
        count: item.num,
        percentage: ((item.num / dumpData?.total) * 100).toFixed(0),
      }));
  }, [dumpData, currentTab, mapStateRef.current?.regionCode]);

  
  return (
    <div className={styles.container}>
      <ModuleTitleWithTabs
        title="申报排放量"
        tabs={[
          { key: 'all', label: '全部' },
          { key: 'urban', label: '城市新区' },
          { key: 'central', label: '中心城区' },
          { key: 'county', label: '县市新城' },
        ]}
        activeKey={currentTab}
        onTabChange={handleTabChange}
        enableDistrictCheck={true}
      />
      <div className={styles.content}>
        <AreaBarList
          data={list}
          height={290}
          isThinProgress={true}
          unit='万方'
          showPercentage={false}
          showCount={true}
          // percentageUnit="万方"
        />
      </div>
    </div>
  );
};

export default DeclaredEmission;
