import { useGlobalModalServices } from '@/pages/GlobalModalServices/provider';
import services from '@/services';
import { useRequest } from 'ahooks';
import { Space } from 'antd';
import dayjs from 'dayjs';
import React, { useMemo, useState } from 'react';
import { useBridgeManage } from '../../context';
import styles from './index.less';

type TabKey = 'month' | 'year';

const BridgeMaintenance: React.FC = () => {
  const [activeTab, setActiveTab] = useState<TabKey>('month');
  const { viewType, isUsingValue } = useBridgeManage();
  const { dispatch } = useGlobalModalServices();
  const tabLabels: Record<TabKey, string> = {
    month: '本月',
    year: '本年',
  };
  const { data: resData } = useRequest(
    () =>
      services.DataBase.getSjdzInfoData({
        typeCode: 'zzcc-dq-dlqlbhxx',
        params: {
          type: viewType == 'road' ? '2' : '1',
          startTime:
            activeTab === 'month'
              ? dayjs().startOf('month').format('YYYY-MM-DD')
              : dayjs().startOf('year').format('YYYY-MM-DD'),
          endTime:
            activeTab === 'month'
              ? dayjs().endOf('month').format('YYYY-MM-DD')
              : dayjs().endOf('year').format('YYYY-MM-DD'),
        },
      }).then((res) => {
        if (res.code === 200) {
          return res?.data?.data?.records?.[0];
        }
        throw new Error('获取数据失败');
      }),
    {
      refreshDeps: [viewType, activeTab],
    },
  );

  const tabs: TabKey[] = ['month', 'year'];
  const list = resData?.list?.slice(0, 3);
  const data = useMemo(() => {
    return {
      bridge: {
        title: '桥梁维护情况',
        subtitle: '巡查发现桥梁病害',
        subtitleCount: resData?.total,
        topTitle: '桥梁病害类型TOP3',
        items: list || [],
      },
      road: {
        title: '道路维护情况',
        subtitle: '巡查发现道路病害',
        subtitleCount: resData?.total,
        topTitle: '道路病害类型TOP3',
        items: list || [],
      },
    };
  }, [resData]);
  const currentData = data[viewType === 'road' ? 'road' : 'bridge'];

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <div className={styles.title}>{currentData.title}</div>
        <div className={styles.tabWrapper}>
          <Space size={10}>
            {tabs.map((tab) => (
              <div
                key={tab}
                className={`${styles.tabBtn} ${
                  activeTab === tab ? styles.active : ''
                }`}
                onClick={() => setActiveTab(tab)}
              >
                {tabLabels[tab]}
              </div>
            ))}
          </Space>
        </div>
      </div>

      <div
        className={styles.subTitle}
        onClick={() => {
          dispatch.push('BridgeMaintenanceList', {
            props: {
              type: viewType == 'road' ? '2' : '1',
            },
          });
        }}
        style={{ cursor: 'pointer' }}
      >
        <span>{currentData.subtitle}</span>
        <span className={styles.count}>{currentData.subtitleCount}</span>
        <span className={styles.unit}>件</span>
      </div>

      <div className={styles.content}>
        <div className={styles.section}>
          <div className={styles.sectionTitle}>{currentData.topTitle}</div>
          <div className={styles.items}>
            {currentData.items.map((item, index) => (
              <div
                key={index}
                className={styles.item}
                onClick={() => {
                  dispatch.push('BridgeMaintenanceList', {
                    props: {
                      type: viewType == 'road' ? '2' : '1',
                      diseasetypename: item?.name,
                    },
                  });
                }}
                style={{ cursor: 'pointer' }}
              >
                <div className={styles.info}>
                  <span className={styles.label}>{item?.name}</span>
                  <span className={styles.value}>{item?.num}</span>
                  <span className={styles.unit}>件</span>
                  <span className={styles.percentValue}>
                    {((item?.num / resData?.total) * 100).toFixed(2)}
                  </span>
                  <span className={styles.percent}>%</span>
                </div>
                <div className={styles.progress}>
                  <div
                    className={styles.bar}
                    style={{
                      width: `${((item?.num / resData?.total) * 100).toFixed(
                        2,
                      )}%`,
                    }}
                  />
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

export default BridgeMaintenance;
