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

// 类型定义
export interface CompletionRateProps {
  dateType?: string;
  dateRange?: { startTime: string; endTime: string };
  dataTypeKey?: string;
  pageId?: string; // 新增页面ID参数
}

// 区域类型定义
export type AreaType = 'all' | 'urban' | 'central' | 'county';

// 区域级别定义
export enum RegionLevelEnum {
  CITY = '1',      // 市级
  DISTRICT = '2',  // 区县级
  STREET = '3',    // 街道级
  GRID = '4',      // 网格级
}

// Tab 定义
const TABS = [
  { key: RegionLevelEnum.DISTRICT, label: '区县' },
  { key: RegionLevelEnum.STREET, label: '街道' }
];

// 区域编码生成函数，参考LeftContent中的getRegionCodes实现
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 '';
};

const CompletionRate: React.FC<CompletionRateProps> = ({ 
  dateType, 
  dateRange, 
  dataTypeKey = '餐饮油烟事件',
  pageId = 'restaurantOil' // 默认为restaurantOil
}) => {
  // 地图状态
  const { mapState } = useMapState();
  const mapStateRef = useLatestValue(mapState);
  
  // 当前选中的区域类型
  const [currentTab, setCurrentTab] = useState<AreaType>('all');
  const currentTabRef = useLatestValue(currentTab);
  
  // 图表数据
  const [data, setData] = useState<{ name: string; percentage: number }[]>([]);

  // 转换日期类型为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'; // 默认月视图
    }
  }, []);

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

  // 构建API请求参数
  const buildApiParams = useCallback(() => {
    const currentMapState = mapStateRef.current;
    
    // 如果没有必要的时间参数，返回null表示不应该发起请求
    if (!currentMapState.rightPanelTime?.startTime || !currentMapState.rightPanelTime?.endTime) {
      return null;
    }
    
    // 获取当前页面的时间设置
    const pageTimeSettings = currentMapState.pageTimeSettings?.[pageId];
    if (!pageTimeSettings) {
      console.log(`缺少${pageId}页面的时间设置，使用全局设置`);
    }
    
    // 使用页面级别的时间设置，如果存在的话
    const rightPanelTime = pageTimeSettings?.rightPanelTime || currentMapState.rightPanelTime;
    
    // 使用当前时间类型，如果不存在则使用props或默认值
    const effectiveType = rightPanelTime.type || dateType || 'month';
    
    // 基础参数对象
    const params: any = {
      type: translateDateType(effectiveType)
    };
    
    // 处理日期参数
    if (effectiveType === 'range') {
      params.customizeStart = formatDateTime(rightPanelTime.startTime);
      params.customizeEnd = formatDateTime(rightPanelTime.endTime, true);
    } else {
      // 年、月、日视图使用time参数 - 手动添加时间部分
      params.time = formatDateTime(rightPanelTime.startTime);
    }
    
    // 获取区域编码列表
    const districtCodeList = getRegionCodes(currentTabRef.current, currentMapState.regionCode);
    if (districtCodeList) {
      params.districtCodeList = districtCodeList;
    }
    
    // 处理区域参数
    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, pageId]);

  // 使用usePageAwareApi管理区县办结率API调用
  const closeRateRankApi = usePageAwareApi({
    apiFunction: async (params: any) => {
      console.log('发起区县办结率请求，参数:', params);
      const response = await getDistrictCompletionRate(params);
      
      if (response.code === 200 && response.data) {
        return response.data;
      }
      
      throw new Error('获取区县办结率数据失败');
    },
    onSuccess: (data: any) => {
      if (!data || !Array.isArray(data) || data.length === 0) {
        setData([]);
        return;
      }
      
      // 先按count从大到小排序
      const sortedData = data.sort((a: any, b: any) => (b.value || 0) - (a.value || 0));
      
      // 找到最大的count值
      const maxCount = sortedData.length > 0 ? sortedData[0].value || 0 : 0;
      
      // 格式化数据并计算percentage
      const formattedData = sortedData.map((item: any) => ({
        name: item.name,
        count: item.value || 0,
        percentage: maxCount > 0 ? Math.round((item.value || 0) / maxCount * 100) : 0 // 计算百分比
      }));
      
      console.log('区县办结率数据成功:');
      setData(formattedData);
    },
    onError: (error: any) => {
      console.error('获取区县办结率数据出错:', error);
      setData([]);
    },
    apiName: '区县办结率',
    debounceTime: 300,
    cacheTime: 5000, // 缓存5秒，避免频繁刷新时重复请求
    enableDebug: false,
    pageId: pageId, // 添加页面ID以启用页面感知
  });

  // 在地图状态变化和Tab变化时加载数据
  useEffect(() => {
    const params = buildApiParams();
    
    // 如果没有必要的参数，不发送请求
    if (!params) {
      console.log('缺少必要的日期参数，暂不加载区县办结率数据');
      return;
    }
    
    console.log(`加载${pageId}页面区县办结率数据，参数:`, params);
    closeRateRankApi.callApi(params);
    
  }, [mapState.regionCode, mapState.rightPanelTime, mapState.pageTimeSettings, currentTab, buildApiParams, closeRateRankApi, pageId]);

  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={data} 
          height={290}
          showCount={true}
          showPercentage={false}
          unit='%'
        />
      </div>
    </div>
  );
};

export default CompletionRate; 