import { 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 { BridgeAreaDistributionProps } from '@/pages/Home_v_2504/components/SubPages/Municipal/components/LeftContent/components/BridgeAreaDistribution';
import useApiControl, {
  formatDateTime,
} from '@/pages/Home_v_2504/hooks/useApiControl';
import useLatestValue from '@/pages/Home_v_2504/hooks/useLatestValue';
import { getDistrictHighFrequencyArea } from '@/services/CityProblem';
import { useSetState } from 'ahooks';
import EChartsReact from 'echarts-for-react';
import { cloneDeep } from 'lodash';
import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from 'react';
import styles from './index.less';
import option from './option';
import services from '@/services';
import dayjs from 'dayjs';

// 类型定义
export interface OperationTrendProps {
  dateType?: string;
  dateRange?: { startTime: string; endTime: string };
  dataTypeKey?: string;
}
const OperationTrend: React.FC<BridgeAreaDistributionProps> = ({
  dateType,
  dateRange,
  dataTypeKey = '景观照明',
}) => {
  const [dataSource, setDataSource] = useSetState<{
    chartData?: {
      lightRate: number;
      faultRate: number;
      serviceabilityRatio: number;
      date: string;
    }[];
  }>({
    chartData: [],
  });
  // 地图状态
  const { mapState } = useMapState();
  const mapStateRef = useLatestValue(mapState);

  const chartRef = useRef<any>();
  // 环卫人员区域数据
  // const [data, setData] = useState<AreaBarItem[]>([]);
  const [data, setData] = useState<AreaBarItem[]>([
    { name: '锦江区', count: 1456, percentage: 97.2 },
    { name: '金牛区', count: 1400, percentage: 83.5 },
    { name: '成华区', count: 1322, percentage: 70.8 },
    { name: '青羊区', count: 1286, percentage: 65.6 },
    { name: '双流区', count: 1252, percentage: 12.9 },
    { name: '武侯区', count: 1122, percentage: 10.6 },
    { name: '龙泉驿区', count: 1121, percentage: 10.5 },
    { name: '温江区', count: 1120, percentage: 10.4 },
    { name: '新都区', count: 1119, percentage: 10.3 },
    { name: '郫都区', count: 1118, percentage: 10.2 },
    { name: '都江堰市', count: 1117, percentage: 10.1 },
  ]);

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

  // 构建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),
    };

    // 处理日期参数
    if (effectiveType === 'range') {
      params.customizeStart = formatDateTime(
        currentMapState.rightPanelTime.startTime,
      );
      params.customizeEnd = formatDateTime(
        currentMapState.rightPanelTime.endTime,
        true,
      );
    } else {
      // 年、月、日视图使用time参数
      params.time = formatDateTime(currentMapState.rightPanelTime.startTime);
    }

    // 处理区域参数
    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, dateType, translateDateType, dataTypeKey]);

  // 使用useApiControl管理环卫人员区域API调用
  const highFrequencyApi = useApiControl({
    apiFunction: async (params) => {
      console.log('发起环卫人员区域请求，参数:', params);
      const response = await getDistrictHighFrequencyArea(params);

      if (response.code === 200 && response.data) {
        return response.data;
      }

      throw new Error('获取环卫人员区域数据失败');
    },
    onSuccess: (data) => {
      if (!data || !Array.isArray(data) || data.length === 0) {
        setData([]);
        return;
      }

      // 如果接口返回数据都是0，生成模拟数据
      // if (data.every(item => parseFloat(item.value) === 0 && parseFloat(item.percent) === 0)) {
      //   data = [
      //     { name: '锦江区', value: 456, percent: '97.2' },
      //     { name: '金牛区', value: 400, percent: '83.5' },
      //     { name: '成华区', value: 322, percent: '70.8' },
      //     { name: '青羊区', value: 186, percent: '65.6' },
      //     { name: '双流区', value: 152, percent: '12.9' },
      //     { name: '武侯区', value: 122, percent: '10.6' },
      //     { name: '龙泉驿区', value: 121, percent: '10.5' },
      //     { name: '温江区', value: 120, percent: '10.4' },
      //     { name: '新都区', value: 119, percent: '10.3' },
      //     { name: '郫都区', value: 118, percent: '10.2' },
      //     { name: '都江堰市', value: 117, percent: '10.1' }
      //   ];
      //   console.log('使用模拟环卫人员区域数据');
      // }

      // 转换接口返回的数据格式为图表需要的格式
      const formattedData = data.map((item: any) => ({
        name: item.name,
        percentage: parseFloat(item.percent) || 0,
        count: parseInt(item.value) || 0,
      }));

      console.log('环卫人员区域数据成功:');
      setData(formattedData);
    },
    onError: (error) => {
      console.error('获取环卫人员区域数据出错:', error);
      setData([]);
    },
    apiName: '环卫人员区域',
    debounceTime: 300,
    cacheTime: 5000, // 缓存5秒，避免频繁刷新时重复请求
  });

  // 使用 useMemo 跟踪 rightPanelTime 的实际变化
  const memoizedRightPanelTime = useMemo(() => {
    return {
      type: mapState.rightPanelTime.type,
      startTime: mapState.rightPanelTime.startTime,
      endTime: mapState.rightPanelTime.endTime,
    };
  }, [
    mapState.rightPanelTime.type,
    mapState.rightPanelTime.startTime,
    mapState.rightPanelTime.endTime,
  ]);

  // 跟踪上一次的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;
    }

    console.log('加载景观照明-近半年运行趋势数据，参数:', params);
    // highFrequencyApi.callApi(params);

    // 更新上一次参数签名
    prevApiParamsRef.current = paramsSignature;
  }, [
    mapState.regionCode,
    memoizedRightPanelTime,
    buildApiParams,
    highFrequencyApi,
  ]);
  const INFO = useMemo(() => {
    const latest = dataSource.chartData?.at(-1);
    return [
      {
        name: '完好率',
        value: latest?.serviceabilityRatio,
        unit: '%',
      },
      {
        name: '亮灯率',
        value: latest?.lightRate,
        unit: '%',
      },
      {
        name: '故障处置及时率',
        value: latest?.faultRate,
        unit: '%',
      },
    ];
  }, [dataSource.chartData]);
  const LineOption = useMemo(() => {
    const temp = cloneDeep(option) as any;
    const xAxis = dataSource.chartData?.map((v) => v.date) ?? [];

    temp.xAxis[0].data = xAxis;

    temp.legend.data = INFO.map((v) => v.name);

    const seriesData1 =
      dataSource.chartData?.map((v) => v.serviceabilityRatio) ?? [];
    const seriesData2 = dataSource.chartData?.map((v) => v.lightRate) ?? [];
    const seriesData3 = dataSource.chartData?.map((v) => v.faultRate) ?? [];

    const max = 100;
    /** 计算最小值 */
    const min = Math.min(...seriesData1, ...seriesData2, ...seriesData3);

    temp.yAxis[0].min = min === Infinity ? 0 : min;
    temp.yAxis[0].max = max;

    const lineSeries = [
      {
        name: '完好率',
        type: 'line',
        // symbol: 'none',
        stack: 'Total',
        symbol: 'circle',
        showSymbol: false,
        lineStyle: {
          width: 3,
        },
        data: seriesData1,
        smooth: true,
      },
      {
        name: '亮灯率',
        type: 'line',
        // symbol: 'none',
        symbol: 'circle',
        showSymbol: false,
        lineStyle: {
          width: 3,
        },
        smooth: true,
        data: seriesData2,
      },
      {
        name: '故障处置及时率',
        type: 'line',
        // symbol: 'none',
        symbol: 'circle',
        showSymbol: false,
        lineStyle: {
          width: 3,
        },
        smooth: true,
        data: seriesData3,
      },
    ];
    temp.series = lineSeries;
    return temp;
  }, [dataSource.chartData]);

    /** 获取半年运行趋势 */
    const getHalfYearTrend = () => {
      services.DataBase.getSjdzInfoData({
        typeCode: 'hyzm-zmyxqkyd',
        params: {
          endTime: dayjs().format('YYYY-MM-DD'),
          startTime: dayjs().subtract(6, 'month').format('YYYY-MM-DD'),
        },
      }).then((res) => {
        if (res.code === 200) {
          const records = res.data?.data?.records;
  
          const data = records.map((record: any) => ({
            lightRate: record.ldl,
            faultRate: record.czl,
            serviceabilityRatio: record.whl,
            date: record.day,
          }));
  
          setDataSource({
            chartData: data,
          });
        }
      });
    };
  
    useEffect(() => {
      getHalfYearTrend();
    }, []);
  return (
    <div className={styles.container}>
      <ModuleTitleWithTabs title="近半年运行趋势" />
      <div className={styles.content}>
        <EChartsReact
          ref={chartRef}
          style={{
            height: 180,
          }}
          option={LineOption}
        ></EChartsReact>
      </div>
    </div>
  );
};

export default OperationTrend;
