import { getStatus } from '@/pages/TheOperationOfTheDistrictCityAndCounty/components/DIstrictDetailBar';
import services from '@/services';
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 LineCharts from '../LineCharts';
import styles from './index.less';
import { getCqiStatusStyle, getCqiStatusTexts } from '@/utils/ui';
import QualityModal from '@/pages/Common/Quality/Modal';
import { useModel } from '@umijs/max';
import EmptySpace from '@/components/EmptySpace';
import Modal from '@/components/HncyModal';
import InfluenceSign from '@/pages/Common/Sign/InfluenceSign';

const RealtimeCQI: React.FC<{ objectId: string; }> = ({
  objectId,
}) => {
  console.log('realtimeCqi', objectId);
  const { setModalOpen, setModalOpt, setCurrentCqiData } = useModel(
    'qualityModal',
    (model) => ({
      setModalOpen: model.setModalOpen,
      setModalOpt: model.setModalOpt,
      setCurrentCqiData: model.setCurrentCqiData,
    }),
  );
  const [signModalOpt, setSignModalOpt] = useState<{
    open: boolean;
    title: string;
    data: any;
  }>({
    open: false,
    title: '',
    data: {}
  })
  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,
        ...getCqiStatusStyle(cqiData?.currentIndex?.indexs?.find((item: any) => item.name === '安全')?.value)
      },
      {
        name: '整洁',
        value:
        cqiData?.currentIndex?.indexs?.find((item: any) => item.name === '整洁')?.value ?? 0,
        ...getCqiStatusStyle(cqiData?.currentIndex?.indexs?.find((item: any) => item.name === '整洁')?.value)
      },
      {
        name: '有序',
        value:
        cqiData?.currentIndex?.indexs?.find((item: any) => item.name === '有序')?.value ?? 0,
        ...getCqiStatusStyle(cqiData?.currentIndex?.indexs?.find((item: any) => item.name === '有序')?.value)
      },
      {
        name: '便民',
        value:
        cqiData?.currentIndex?.indexs?.find((item: any) => item.name === '便民')?.value ?? 0,
        ...getCqiStatusStyle(cqiData?.currentIndex?.indexs?.find((item: any) => item.name === '便民')?.value)
      },
      {
        name: '美观',
        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,
              }}
            >
              {cqiData?.currentIndex?.cqi}
            </span>
            <span
              className={styles.tag}
              style={{ color: getCqiStatusStyle(cqiData?.currentIndex?.cqi)?.color }}
            >
              {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,
          }))}
        />
      </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={() => {
                setModalOpen(true);
                setModalOpt([{ title: item.name, type: 'category' }]);
                setCurrentCqiData({ ...item, objectId: cqiData?.currentIndex?.objectId });
              }}
            >
              <div className={styles.name}>{item.name}</div>
              <div className={styles.value} style={{ color: item.color }}>
                {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={() => setSignModalOpt({ open: true, title: '影响指标', data: item })}
                >
                  <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>

      <QualityModal />

      <Modal
        open={signModalOpt?.open}
        title={'影响指标'}
        onCancel={() => setSignModalOpt({ open: false, title: '', data: {} })}
        width={1470}
        height={846}
      >
        <InfluenceSign data={signModalOpt?.data} />
      </Modal>
    </div>
  );
};

export default RealtimeCQI;
