import EmptySpace from '@/components/EmptySpace';
import { message } from '@/layouts/messageStore';
import services from '@/services';
import { cqiDisplay, getCqiLineChartStyles, getCqiStatusStyle, getCqiStatusTexts } from '@/utils/ui';
import { CaretDownOutlined, CaretUpOutlined } from '@ant-design/icons';
import { useRequest } from 'ahooks';
import { Flex, Popover, Space, Spin } from 'antd';
import dayjs from 'dayjs';
import React, { useEffect, useMemo, useState } from 'react';
import { useGlobalModalServices } from '../../provider';
import LineCharts from '../LineCharts';
import styles from './index.less';

const RealtimeCQI: React.FC<{ objectId: string }> = ({ objectId }) => {
  const { dispatch } = useGlobalModalServices();

  const [cqiData, setCqiData] = useState<any>({});
  //影响指标Top3
  const { data: indexTop3, loading } = useRequest(
    () =>
      services.Physicalsign.getPhysicalsignindexquestioninstanceListTop({
        objectId: objectId, // 对象id
        indexId: '1',
        n: '3', // Top3
        indexType: '1', // 内评价0，外评价1，默认外评价
        physicalSignType: '1',
      }),
    {
      refreshDeps: [objectId],
    },
  );
  const cards = useMemo(() => {
    return [
      {
        name: '安全',
        value:
          cqiData?.currentIndex?.indexs?.find(
            (item: any) => item.name === '安全',
          )?.value ?? 0,
        id: cqiData?.currentIndex?.indexs?.find(
          (item: any) => item.name === '安全',
        )?.id,
        ...getCqiStatusStyle(
          cqiData?.currentIndex?.indexs?.find(
            (item: any) => item.name === '安全',
          )?.value,
        ),
      },
      {
        name: '整洁',
        value:
          cqiData?.currentIndex?.indexs?.find(
            (item: any) => item.name === '整洁',
          )?.value ?? 0,
        id: cqiData?.currentIndex?.indexs?.find(
          (item: any) => item.name === '整洁',
        )?.id,
        ...getCqiStatusStyle(
          cqiData?.currentIndex?.indexs?.find(
            (item: any) => item.name === '整洁',
          )?.value,
        ),
      },
      {
        name: '有序',
        value:
          cqiData?.currentIndex?.indexs?.find(
            (item: any) => item.name === '有序',
          )?.value ?? 0,
        id: cqiData?.currentIndex?.indexs?.find(
          (item: any) => item.name === '有序',
        )?.id,
        ...getCqiStatusStyle(
          cqiData?.currentIndex?.indexs?.find(
            (item: any) => item.name === '有序',
          )?.value,
        ),
      },
      {
        name: '便民',
        value:
          cqiData?.currentIndex?.indexs?.find(
            (item: any) => item.name === '便民',
          )?.value ?? 0,
        id: cqiData?.currentIndex?.indexs?.find(
          (item: any) => item.name === '便民',
        )?.id,
        ...getCqiStatusStyle(
          cqiData?.currentIndex?.indexs?.find(
            (item: any) => item.name === '便民',
          )?.value,
        ),
      },
      {
        name: '美观',
        value: '--',
        id: cqiData?.currentIndex?.indexs?.find(
          (item: any) => item.name === '美观',
        )?.id,
        color: '#57EF58',
        background: 'rgba(39, 211, 134, 0.2)',
        // value: cqiData?.currentIndex?.indexs?.find((item: any) => item.name === '美观')?.value ?? 0,
        // ...getCqiStatusStyle(cqiData?.currentIndex?.indexs?.find((item: any) => item.name === '美观')?.value)
      },
    ];
  }, [cqiData]);

  // 获取CQI数据
  const getCqiData = () => {
    const params = {
      physicalSignType: '1', // 1实况指数  3周期指数
      indexType: '1', // 指数体系类型 0:内评价 1:外评价
      indexHierarchy: '1,2', // 指数层级，从1开始，多个用,逗号隔开
      objectId: objectId, // 区域网格id
      indexId: '', // 指数id
    };
    services.Physicalsign.getComparisonIndexInstance(params).then((res) => {
      if (res.code === 200) {
        setCqiData(res.data);
      }
    });
  };

  useEffect(() => {
    if (objectId) {
      getCqiData();
    }
  }, [objectId]);

  return (
    <div className={styles.container}>
      <Flex justify="space-between" align="center" className={styles.header}>
        <Space className={styles.title}>
          实时CQI
          <span className={styles.title_time}>
            {cqiData?.currentIndex?.time}
          </span>
        </Space>
        <Flex justify="flex-end" className={styles.compare}>
          <Space size={10}>
            <span className={styles.tips}>
              较{dayjs().diff(cqiData?.indexTime, 'h')}小时前
            </span>
            <div>
              <Space>
                {cqiData?.status === 'up' ? (
                  <CaretUpOutlined style={{ color: 'rgb(9, 195, 92)' }} />
                ) : (
                  <CaretDownOutlined style={{ color: 'rgb(255, 71, 71)' }} />
                )}
                <div
                  className={styles.rightValue}
                  style={{
                    color:
                      cqiData?.status === 'up'
                        ? 'rgb(9, 195, 92)'
                        : 'rgb(255, 71, 71)',
                  }}
                >
                  {cqiData?.diffValue}
                </div>
              </Space>
            </div>
          </Space>
        </Flex>
      </Flex>

      <Flex
        justify="space-between"
        align="center"
        className={styles.chartSection}
      >
        <div>
          <Flex align="center" gap={13}>
            <span
              className={styles.num}
              style={{
                color: getCqiStatusStyle(cqiData?.currentIndex?.cqi)?.color,
              }}
            >
              {cqiDisplay(cqiData?.currentIndex?.cqi)}
            </span>
            <span
              className={styles.tag}
              style={{
                ...getCqiStatusStyle(cqiData?.currentIndex?.cqi),
                color: '#fff',
              }}
            >
              {getCqiStatusTexts(cqiData?.currentIndex?.cqi)?.text}
            </span>
          </Flex>
          <span className={styles.title}>
            {getCqiStatusTexts(cqiData?.currentIndex?.cqi)?.desc}
          </span>
        </div>
        <LineCharts
          style={{
            width: 336,
            height: 85,
          }}
          data={cqiData?.currentIndex?.indexDataList?.map((item: any) => ({
            value: item?.qualitySign,
            name: item?.time,
          }))}
          lineStyles={getCqiLineChartStyles(cqiData?.currentIndex?.cqi)}
        />
      </Flex>

      <div className={styles.cardSection}>
        <Flex justify="space-between">
          {cards.map((item, index) => (
            <Flex
              vertical
              justify="center"
              align="center"
              gap={10}
              key={index}
              className={styles.card}
              style={{ background: item.background }}
              onClick={() => {
                if (item.name === '美观') {
                  message.warning('指标正在构建中');
                  return;
                }

                dispatch.push('Category', {
                  title: item.name,
                  props: {
                    item: {
                      ...item,
                      objectId: cqiData?.currentIndex?.objectId,
                    },
                  },
                });
              }}
            >
              <div className={styles.name}>{item.name}</div>
              <div className={styles.value} style={{ color: item.color }}>
                {cqiDisplay(item.value)}
              </div>
            </Flex>
          ))}
        </Flex>
      </div>
      <div className={styles.subTitle}>影响指标TOP3</div>
      <div>
        {loading && (
          <Flex align="center" justify="center" style={{ height: '100%' }}>
            <Spin></Spin>
          </Flex>
        )}
        {indexTop3?.data?.length ? (
          <>
            {indexTop3?.data?.map((item, index) => (
              <Flex
                className={styles.listCard}
                justify="space-between"
                align="center"
                key={item.indexId}
                onClick={() => {
                  dispatch.push('InfluenceSign', {
                    props: {
                      data: item,
                      objectId: objectId
                    },
                  });
                }}
              >
                <Flex gap={25} align="center">
                  <div className={styles.rankTag}>TOP{index + 1}</div>
                  <Popover
                    content={
                      <div className={styles.desc}>
                        <p>{item.conditionName}</p>
                        <span>{item.fullName}</span>
                      </div>
                    }
                  >
                    <div className={styles.desc}>
                      <p className="textellipsis">{item.conditionName}</p>
                      <span className="textellipsis">{item.fullName}</span>
                    </div>
                  </Popover>
                </Flex>
                <div className={styles.infRate}>
                  <span>影响占比</span>
                  <span>{item.percentage}</span>
                  <span>%</span>
                </div>
              </Flex>
            ))}
          </>
        ) : (
          <EmptySpace describe="暂无影响指标" style={{ padding: '10% 0' }} />
        )}
      </div>
    </div>
  );
};

export default RealtimeCQI;
