import upIcon from '@/assets/images/urbanSituation/up.png';
import { useGlobalModalServices } from '@/pages/GlobalModalServices/provider';
import services from '@/services';
import { convertUnits, formatNumber } from '@/utils/ui';
import webSocketService from '@/utils/websocket';
import { useRequest } from 'ahooks';
import { Flex, Spin, Statistic, StatisticProps } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useMemo, useState } from 'react';
import CountUp from 'react-countup';
import DateSelect from './DateSelect';
import styles from './index.less';
import LineCharts from './LineCharts';

const formatter: StatisticProps['formatter'] = (value: any) => {
  return (
    <CountUp
      end={formatNumber(value)?.num as number}
      separator=""
      decimals={formatNumber(value)?.unit == '万件' ? 2 : 0}
    />
  );
};

const commonStatistic = (
  value: number | string,
  fontSize: number | string = 30,
) => {
  return (
    <Statistic
      valueStyle={{ fontSize: fontSize, lineHeight: 1 }}
      value={value}
      formatter={() => (
        <CountUp
          end={value as number}
          separator=""
          preserveValue
          decimals={Number.isInteger(value) ? 0 : 2}
        />
      )}
    />
  );
};

const OperatingSituation = () => {
  const [searchParams, setSearchParams] = useState<any>({ type: '2' });
  const { dispatch } = useGlobalModalServices();
  /** 疑难问题基础数据 */
  const [DEDataSource, setDEDataSource] = useState<any>();
  const { data, loading: dataLoading } = useRequest(
    () => services.CityProblemApi.getContentStatisticsV3(searchParams),
    {
      refreshDeps: [searchParams],
    },
  );

  // 添加 AI 实时巡查数据状态
  const [aiPatrolCount, setAiPatrolCount] = useState<number>(0);

  const getDifficultData = () => {
    services.Physicalsign.getDifficultEventsInfo().then((res) => {
      if (res.code === 200) {
        setDEDataSource(res.data);
      }
    });
  };

  // 连接WebSocket并订阅'total'类型消息
  useEffect(() => {
    // 订阅WebSocket消息
    const unsubscribe = webSocketService.subscribe('total', (data) => {
      if (data !== undefined && data !== null) {
        console.log('==> WEBSocket 实时巡查数据 AiPatrolCount', data);
        setAiPatrolCount(Number(data));
      }
    });

    // 组件卸载时取消订阅
    return () => {
      unsubscribe();
    };
  }, []);

  useEffect(() => {
    getDifficultData();
  }, []);

  const getSearchTime = (searchParams: any) => {
    const { type, time } = searchParams;
    if (type === '3') {
      return dayjs(time).format('YYYY-MM-DD');
    } else if (type === '2') {
      return dayjs(time).format('YYYY-MM');
    } else if (type === '1') {
      return dayjs(time).format('YYYY');
    }
  };

  const platformList = useMemo(() => {
    //市运行平台
    const scypt = data?.data?.items?.find(
      (item: any) => item.code === 'scypt',
    )?.value;
    //12345
    const complaint = data?.data?.items?.find(
      (item: any) => item.code === '12345',
    )?.value;
    //数字城管
    const szcg = data?.data?.items?.find(
      (item: any) => item.code === 'szcg',
    )?.value;
    //突出问题
    const tcwtts = data?.data?.items?.find(
      (item: any) => item.code === 'tcwtts',
    )?.value;
    //行走成都
    const walkCd = data?.data?.items?.find(
      (item: any) => item.code === '10',
    )?.value;

    //委内
    const wnywxt = data?.data?.items?.find(
      (item: any) => item.code === 'wnywxt',
    )?.value;

    return [
      {
        key: '1',
        name: '市城运平台',
        value: scypt,
        unit: formatNumber(scypt)?.unit,
        lineData: data?.data?.timeItems['scypt']?.map((item: any) => ({
          ...item,
          name: searchParams?.type === '3' ? item.time + '时' : item.time,
        })),
        onClick: () => {
          dispatch?.push('UrbanOperation' as any, {
            title: '市城运平台推送',
            props: {
              sourceSystemCode: data?.data?.items?.find(
                (item: any) => item.code === 'scypt',
              )?.code,
              datetType: searchParams?.type,

              time: getSearchTime(searchParams),
            },
          });
        },
      },
      {
        key: '2',
        name: '12345市民投诉',
        unit: formatNumber(complaint)?.unit,
        value: complaint,
        lineData: data?.data?.timeItems['12345']?.map((item: any) => ({
          ...item,
          name: searchParams?.type === '3' ? item.time + '时' : item.time,
        })),
        // onClick: () => {
        //   console.log(getSearchTime(searchParams));
        //   dispatch?.push('UrbanOperation' as any, {
        //     title: '12345市民投诉',

        //     props: {
        //       sourceSystemCode: data?.data?.items?.find(
        //         (item: any) => item.code === '12345',
        //       )?.code,
        //       datetType: searchParams?.type,

        //       time: getSearchTime(searchParams),
        //     },
        //   });
        // },
      },
      {
        key: '3',
        name: '数字城管巡查上报',
        value: szcg,
        unit: formatNumber(szcg)?.unit,
        lineData: data?.data?.timeItems['szcg']?.map((item: any) => ({
          ...item,
          name: searchParams?.type === '3' ? item.time + '时' : item.time,
        })),
        onClick: () => {
          //CgftEvent
          dispatch?.push('UrbanOperation' as any, {
            title: '数字城管巡查上报',

            props: {
              sourceSystemCode: data?.data?.items?.find(
                (item: any) => item.code === 'szcg',
              )?.code,
              datetType: searchParams?.type,

              time: getSearchTime(searchParams),
            },
          });
        },
      },
      {
        key: '22',
        name: '突出问题推送',
        value: tcwtts,
        unit: formatNumber(tcwtts)?.unit,
        lineData: data?.data?.timeItems['tcwtts']?.map((item: any) => ({
          ...item,
          name: searchParams?.type === '3' ? item.time + '时' : item.time,
        })),

        onClick: () => {
          //,CgftEvent
          dispatch?.push('UrbanOperation' as any, {
            title: '突出问题推送',
            props: {
              singleType: '1',
              sourceSystemCode: data?.data?.items?.find(
                (item: any) => item.code === 'tcwtts',
              )?.code,
              datetType: searchParams?.type,

              time: getSearchTime(searchParams),
            },
          });
        },
      },
      {
        key: '5',
        name: '行走成都',

        unit: formatNumber(walkCd)?.unit,
        value: walkCd,
        lineData: data?.data?.timeItems['10']?.map((item: any) => ({
          ...item,
          name: searchParams?.type === '3' ? item.time + '时' : item.time,
        })),
        onClick: () => {
          dispatch?.push('UrbanOperation' as any, {
            title: '行走成都',
            props: {
              sourceSystemCode: data?.data?.items?.find(
                (item: any) => item.code === '10',
              )?.code,
              datetType: searchParams?.type,

              time: getSearchTime(searchParams),
            },
          });
        },
      },
      {
        key: '6',
        name: '委内业务系统',
        value: wnywxt,
        unit: formatNumber(wnywxt)?.unit,
        lineData: data?.data?.timeItems['wnywxt']?.map((item: any) => ({
          ...item,
          name: searchParams?.type === '3' ? item.time + '时' : item.time,
        })),
        onClick: () => {
          dispatch.push('UrbanOperation', {
            title: '委内业务',
            props: {
              sourceSystemCode: data?.data?.items?.find(
                (item: any) => item.code === 'wnywxt',
              )?.code,
              datetType: searchParams?.type,

              time: getSearchTime(searchParams),
              showSourceSelect: true,
              sourceType: 'wnywxt',
            },
          });
        },
      },
    ];
  }, [dispatch, data, searchParams]);

  return (
    <div className={styles.container}>
      <div className={styles.titleWarp}>
        <div className={styles.title}>运行态势</div>
        <div className={styles.select}>
          <DateSelect
            onSelectedDate={(e) => {
              console.log(e);
              const currentTime = dayjs().format('HH:mm:ss');
              let time = `${e.time} ${currentTime}`;
              if (e.type === '1') {
                time = dayjs(e.time).format('YYYY-01-01') + ' ' + currentTime;
              } else if (e.type === '2') {
                time = dayjs(e.time).format('YYYY-MM-01') + ' ' + currentTime;
              }
              setSearchParams({
                time: time,
                type: e.type,
              });
            }}
          />
        </div>
      </div>
      <Spin
        spinning={dataLoading}
        style={{ width: '100%', height: '100%' }}
        wrapperClassName={styles.spin}
      >
        <div className={styles.content}>
          <Flex className={styles.platform} vertical justify="space-between">
            {platformList?.map((item) => {
              return (
                <Flex key={item?.key} align="center">
                  <div
                    className={styles.platItem}
                    style={{ cursor: 'pointer' }}
                    onClick={() => {
                      item?.onClick?.();
                    }}
                  >
                    <div className={styles.title}>{item?.name}</div>
                    <LineCharts
                      data={item?.lineData}
                      style={{ width: 126, height: 30 }}
                    />

                    <div className={styles.countWarp}>
                      <span>
                        {commonStatistic(convertUnits(item.value)?.num, 30)}
                      </span>
                      <span className={styles.unit}>
                        {convertUnits(item.value)?.unit}
                      </span>
                    </div>
                  </div>
                  <img src={upIcon} className={styles.upIcon} alt="" />
                </Flex>
              );
            })}
          </Flex>
          {/* <img
          src={require('@/assets/images/tljt.png')}
          alt=""
          style={{ marginTop: 10 }}
        /> */}
          <div className={styles.rigth}>
            <div className={styles.topWarp}>
              <div className={styles.title}>城市管理类问题总数</div>
              <div
                className={styles.countWarp}
                style={{ cursor: 'pointer' }}
                onClick={() => {
                  // dispatch.push('GeneralSituation', {
                  //   title: '事件总体情况',
                  // });
                  dispatch.push('UrbanOperation', {
                    title: '总体情况',
                    props: {
                      // sourceSystemCode: data?.data?.items?.find(
                      //   (item: any) => item.code === 'wnywxt',
                      // )?.code,
                      datetType: searchParams?.type,
                      lineData: data?.data?.timeItems[
                        '城市管理综合问题总数'
                      ]?.map((item: any) => ({
                        ...item,
                        name: item.time,
                      })),
                      time: getSearchTime(searchParams),
                      showSourceSelect: true,
                      sourceType: 'all',
                    },
                  });
                }}
              >
                {commonStatistic(
                  convertUnits(data?.data?.total?.value)?.num,
                  38,
                )}
                <span className={styles.unit}>
                  {convertUnits(data?.data?.total?.value)?.unit}
                </span>
              </div>
            </div>
            <div className={styles.roat} style={{ height: 25 }}></div>
            <div style={{ width: '100%', height: 76 }}>
              <LineCharts
                data={
                  data?.data?.timeItems['城市管理综合问题总数']?.map(
                    (item: any) => ({
                      ...item,
                      name:
                        searchParams?.type === '3'
                          ? item.time + '时'
                          : item.time,
                    }),
                  ) || []
                }
                style={{ width: '100%', height: 76 }}
              />
            </div>

            <div className={styles.eventWarp}>
              <div className={styles.eventItem}>
                <img
                  src={require('@/assets/images/evtIc1.png')}
                  alt=""
                  className={styles.icon}
                />
                <div className={styles.rw}>
                  <div className={styles.countWarp}>
                    {commonStatistic(
                      convertUnits(data?.data?.accept?.value)?.num,
                    )}
                    <span className={styles.unit}>
                      {convertUnits(data?.data?.accept?.value)?.unit}
                    </span>
                  </div>
                  <div className={styles.label}>立案</div>
                </div>
              </div>
              <div
                className={styles.eventItem}
                // style={{ cursor: 'pointer' }}
                onClick={() => {
                  // dispatch.push('ToDisposed', {
                  //   title: '待处置事件',
                  // });
                }}
              >
                <img
                  src={require('@/assets/images/evtIc2.png')}
                  alt=""
                  className={styles.icon}
                />
                <div className={styles.rw}>
                  <div className={styles.countWarp}>
                    {commonStatistic(
                      convertUnits(data?.data?.need?.value)?.num,
                    )}
                    <span className={styles.unit}>
                      {convertUnits(data?.data?.need?.value)?.unit}
                    </span>
                  </div>
                  <div className={styles.label}>应处置</div>
                </div>
              </div>
              <div className={styles.eventItem}>
                <img
                  src={require('@/assets/images/evtIc2.png')}
                  alt=""
                  className={styles.icon}
                />
                <div className={styles.rw}>
                  <div className={styles.countWarp}>
                    {commonStatistic(
                      convertUnits(data?.data?.disposed?.value)?.num,
                    )}
                    <span className={styles.unit}>
                      {convertUnits(data?.data?.disposed?.value)?.unit}
                    </span>
                  </div>

                  <div className={styles.label}>已处置</div>
                </div>
              </div>
              <div className={styles.eventItem}>
                <img
                  src={require('@/assets/images/evtIc4.png')}
                  alt=""
                  className={styles.icon}
                />
                <div className={styles.rw}>
                  <div className={styles.countWarp}>
                    <span></span>
                    <Statistic
                      valueStyle={{ fontSize: 30, lineHeight: 1 }}
                      value={data?.data?.disposalRate?.value}
                    />
                    <span className={styles.unit}>%</span>
                  </div>
                  <div className={styles.label}>处置率</div>
                </div>
              </div>
            </div>

          
            <div
              className={styles.cityIssue}
              onClick={() => {
                dispatch.push('DifficultEvents', {
                  title: '疑难问题',
                });
              }}
              style={{ cursor: 'pointer' }}
            >
              <div className={styles.label}>城市管理类疑难问题</div>
              <div className={styles.numWarp}>
                {commonStatistic(
                  convertUnits(DEDataSource?.cityManageEventTotal)?.num,
                  30,
                )}
                <span className={styles.unit} style={{ marginLeft: 5 }}>
                  {convertUnits(DEDataSource?.cityManageEventTotal)?.unit}
                </span>
              </div>
            </div>

            <div
              className={styles.cityIssue}
              onClick={() => {
                dispatch.push('AiPatrol');
              }}
              style={{ cursor: 'pointer' }}
            >
              <div className={styles.label}>市级监督AI实时巡查</div>
              <div className={styles.numWarp}>
                {commonStatistic(
                  // convertUnits(DEDataSource?.cityManageEventTotal)?.num,
                  aiPatrolCount,
                  30,
                )}
                <span className={styles.unit} style={{ marginLeft: 5 }}>
                  {/* {convertUnits(DEDataSource?.cityManageEventTotal)?.unit} */}
                  件
                </span>
              </div>
            </div>
          </div>
        </div>
      </Spin>
    </div>
  );
};

export default OperatingSituation;
