import DescriptionItem from '@/components/DescriptionItem';
import { ChartDataItem } from '@/components/V2504/ChartWithLegend';
import ModuleTitleWithTabs from '@/pages/Home_v_2504/components/common/ModuleTitleWithTabs';
import {
  useDataType,
  useMapState,
} from '@/pages/Home_v_2504/components/MapStateContext';
import useApiControl, {
  formatDateTime,
} from '@/pages/Home_v_2504/hooks/useApiControl';
import useLatestValue from '@/pages/Home_v_2504/hooks/useLatestValue';
import services from '@/services';
import { getSourceSystemRank } from '@/services/CityProblem';
import { useSetState } from 'ahooks';
import classNames from 'classnames';
import dayjs from 'dayjs';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import styles from './index.less';

interface OperationStatusProps {
  dateType?: string;
  dateRange?: { startTime: string; endTime: string };
  dataTypeKey?: string;
  isThinLayout?: boolean;
}
const commonValueStyle = {
  background: 'linear-gradient(180deg, #9CF8F7 0%, #25BBFF 100%)',
  WebkitBackgroundClip: 'text',
  WebkitTextFillColor: 'transparent',
  fontFamily: 'D-DIN',
  fontSize: '28px',
  fontWeight: 700,
};

const commonLabelStyle = {
  color: 'rgb(188, 206, 233)',
  fontSize: '14px',
  fontWeight: 400,
};

const commonUnitStyle = {
  color: '#BCCEE9',
  fontSize: '14px',
};
const OperationStatus: React.FC<OperationStatusProps> = ({
  dateType,
  dateRange,
  dataTypeKey = '景观照明',
  isThinLayout = true,
}) => {
  // 地图状态
  const { mapState } = useMapState();
  const mapStateRef = useLatestValue(mapState);

  // 统计数据
  const [data, setData] = useState<ChartDataItem[]>([]);
  const [dataSource, setDataSource] = useSetState<{
    info?: {
      turnOnTime: string;
      turnOnDate: string;
      turnOffTime: string;
      turnOffDate: string;
    };
    list?: {
      name: string;
      value: number;
    }[];
    power?: 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'; // 默认月视图
    }
  }, []);

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

    // 如果没有必要的时间参数，返回null表示不应该发起请求
    if (
      !currentMapState.rightPanelTime?.startTime ||
      !currentMapState.rightPanelTime?.endTime
    ) {
      return null;
    }
    // 使用当前时间类型，如果不存在则使用props或默认值
    const effectiveType =
      currentMapState.rightPanelTime.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 sourceSystemRankApi = useApiControl({
    apiFunction: async (params) => {
      console.log('发起问题来源请求，参数:', params);
      const response = await getSourceSystemRank(params);

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

      throw new Error('获取问题来源数据失败');
    },
    onSuccess: (data) => {
      if (!data || !Array.isArray(data) || data.length === 0) {
        let useMockData = true;
        if (useMockData) {
          data = [
            { name: 'I等', value: 456, percent: '97.2' },
            { name: 'II等', value: 400, percent: '83.5' },
            { name: 'III等', value: 322, percent: '70.8' },
            // { name: '青羊区', value: 186, percent: '65.6' },
            // { name: '双流区', value: 152, percent: '12.9' },
          ];
          // console.log('使用模拟问题来源数据');
        } else {
          setData([]);
          return;
        }
      }

      // 如果接口返回数据都是0，生成模拟数据
      // if (data.every(item => parseInt(item.value) === 0 && parseFloat(item.percent) === 0)) {

      // }

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

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

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

    // 如果没有必要的参数，不发送请求
    if (!params) {
      console.log('缺少必要的日期参数，不加载问题来源数据');
      return;
    }

    console.log('加载景观照明-运行情况数据，参数:', params);
    sourceSystemRankApi.callApi(params);
  }, [
    mapState.regionCode,
    mapState.rightPanelTime,
    buildApiParams,
    sourceSystemRankApi,
  ]);

  const totalValue = data.reduce((sum, item) => sum + (item.value || 0), 0);
  const formatTime = (str: string, length: number) => {
    return str.slice(0, length);
  };

  const INFO = useMemo(() => {
    return [
      {
        name: '开灯时间',
        value: dataSource.info?.turnOnTime
          ? formatTime(dataSource.info?.turnOnTime, 5)
          : '--',
        tag: dataSource.info?.turnOnDate
          ? formatTime(dataSource.info?.turnOnDate, 6)
          : '--',
        showTextToValue: true,
        icon: require('@/assets/images/V-2504/lightUp.png'),
        fontSize:34
      },
      {
        name: '关灯时间',
        value: dataSource.info?.turnOffTime
          ? formatTime(dataSource.info?.turnOffTime, 5)
          : '--',
        tag: dataSource.info?.turnOffDate
          ? formatTime(dataSource.info?.turnOffDate, 6)
          : '--',
        showTextToValue: true,
        icon: require('@/assets/images/V-2504/douseLight.png'),
        fontSize:34
      },
      {
        name: '自然光照度',
        value: dataSource?.power,
        unit: 'lux',
        tag: '实时',
        icon: require('@/assets/images/V-2504/lightUp.png'),
        fontSize:28
      },
    ];
  }, [dataSource.info, dataSource?.power]);

  /** 获取光照时间 */
  const getLightTime = () => {
    services.DataBase.getGzInfoData({
      typeCode: 'gz-dl-zdpjz',
    }).then((res) => {
      if (res.code === 200) {
        setDataSource({
          power: res.data,
        });
      }
    });
  };

  /** 获取数据*/
  const getData = () => {
    services.DataBase.getSjdzInfoData({
      typeCode: 'hyzm-zmyxjckz',
      params: {
        endTime: dayjs().format('YYYY-MM-DD'),
        startTime: dayjs().subtract(3, 'day').format('YYYY-MM-DD'),
      },
    }).then((res) => {
      if (res.code === 200) {
        const record = res.data?.data?.records;

        setDataSource({
          info: {
            turnOnTime: record[0]?.actualTrunOn,
            turnOffTime: record[0]?.actualTrunOff,
            turnOnDate: dayjs(record[0]?.lightSwitchDate).format('MM月DD日'),
            turnOffDate: dayjs(record[0]?.lightSwitchDate)
              .add(1, 'day')
              .format('MM月DD日'),
            // turnOffDate: dayjs(record[0]?.lightSwitchDate).format('MM月DD日'),
          },
        });
      }
    });
  };

  useEffect(() => {
    getData();

    getLightTime();
  }, []);
  return (
    <div className={styles.container}>
      <ModuleTitleWithTabs title="运行情况" />
      <div className={classNames(styles.content)}>
        {INFO.map((item, index) => {
          return (
            <div className={styles.item} key={index}>
              <div style={{ display: 'flex', justifyContent: 'center' }}>
                <div className={styles.tagWrap}>
                  <img
                    className={styles.icon}
                    src={require('@/assets/images/V-2504/timeIcon.png')}
                    alt=""
                  />
                  <span className={styles.tag}>{item?.tag}</span>
                </div>
              </div>
              <DescriptionItem
                showTextToValue={item.showTextToValue}
                name={item.name}
                unit={item.unit}
                valueStyle={{...commonValueStyle,fontSize:item.fontSize}}
                labelStyle={commonLabelStyle}
                unitStyle={commonUnitStyle}
                style={{
                  alignItems: 'center',
                  marginTop: index==2?23:17,
                }}
                decimals={0}
                value={item?.value}
              />
              <img src={item.icon} alt="" className={styles.bg} />
            </div>
          );
        })}
      </div>
    </div>
  );
};

export default OperationStatus;
