import services from '@/services';
import { useRequest } from 'ahooks';
import { Badge, Flex, Space } from 'antd';
import * as echarts from 'echarts';
import EChartsReact from 'echarts-for-react';
import React, { useMemo, useRef, useState } from 'react';
import { useBridgeManage } from '../../context';
import styles from './index.less';

type TabKey = 'level' | 'type';

const BridgeTypeDistribution: React.FC = () => {
  const { viewType, isUsingValue } = useBridgeManage();
  const [activeTab, setActiveTab] = useState<TabKey>('level');
  const chartRef = useRef<EChartsReact>(null);

  //桥梁总数
  const { data: bridgeTotal } = useRequest(() =>
    services.DataBase.getSjdzInfoData({
      typeCode: 'zzcc-dq-qsqlzszmj',
    }).then((res) => {
      if (res.code === 200) {
        return res?.data?.data?.records?.[0];
      }
      throw new Error('获取数据失败');
    }),
  );
  //道路总数
  const { data: roadTotal } = useRequest(() =>
    services.DataBase.getSjdzInfoData({
      typeCode: 'zzcc-dq-qsdlzs',
    }).then((res) => {
      if (res.code === 200) {
        return res?.data?.data?.records?.[0];
      }
      throw new Error('获取数据失败');
    }),
  );

  //桥梁类型分布按养护等级
  const { data: bridgeMaintenanceLevelData } = useRequest(() =>
    services.DataBase.getSjdzInfoData({
      typeCode: 'zzcc-dq-qlyhdj',
    }).then((res) => {
      if (res.code === 200) {
        return res?.data?.data?.records;
      }
      throw new Error('获取数据失败');
    }),
  );
  //桥梁类型分布按养护类别
  const { data: bridgeMaintenanceTypeData } = useRequest(() =>
    services.DataBase.getSjdzInfoData({
      typeCode: 'zzcc-dq-qlyhlb',
    }).then((res) => {
      if (res.code === 200) {
        return res?.data?.data?.records;
      }
      throw new Error('获取数据失败');
    }),
  );

  //道路类型分布按养护等级
  const { data: roadMaintenanceLevelData } = useRequest(() =>
    services.DataBase.getSjdzInfoData({
      typeCode: 'zzcc-dq-dlayhdj ',
    }).then((res) => {
      if (res.code === 200) {
        return res?.data?.data?.records;
      }
      throw new Error('获取数据失败');
    }),
  );
  //道路类型分布按养护类别
  const { data: roadMaintenanceTypeData } = useRequest(() =>
    services.DataBase.getSjdzInfoData({
      typeCode: 'zzcc-dq-dlayhlb ',
    }).then((res) => {
      if (res.code === 200) {
        console.log(res);

        return res?.data?.data?.records;
      }
      throw new Error('获取数据失败');
    }),
  );

  const sortByName = (data: any[]) => {
    // 定义中文数字和罗马数字的映射关系
    const numberMap: { [key: string]: number } = {
      一: 1,
      二: 2,
      三: 3,
      四: 4,
      五: 5,
      I: 1,
      II: 2,
      III: 3,
      IV: 4,
      V: 5,
      Ⅰ: 1,
      Ⅱ: 2,
      Ⅲ: 3,
      Ⅳ: 4,
      Ⅴ: 5,
    };
    const getNumberFromName = (name: string): number => {
      // 匹配中文数字或罗马数字
      const match = name.match(/[一二三四五IIVⅠⅡⅢⅣⅤ]+/);
      if (match) {
        const key = match[0];
        return numberMap[key] || 0; // 如果未匹配到，返回 0
      }
      return 0;
    };
    return data?.sort((a, b) => {
      console.log(a, b);
      const numA = getNumberFromName(a.name);

      const numB = getNumberFromName(b.name);
      console.log(numA, numB);
      // debugger;
      return numA - numB;
    });
  };

  const chartData = useMemo(() => {
    //桥梁
    if (viewType == 'bridge' || viewType == 'location') {
      const list =
        activeTab === 'level'
          ? bridgeMaintenanceLevelData
          : bridgeMaintenanceTypeData;
      return sortByName(
        list?.map((item) => {
          return {
            name: item?.lb || item?.dj,
            value: item?.num,
            percent: ((item?.num / bridgeTotal?.num) * 100).toFixed(2),
          };
        }),
      );
    }
    const list =
      activeTab === 'level'
        ? roadMaintenanceLevelData
        : roadMaintenanceTypeData;
    return sortByName(
      list?.map((item) => {
        return {
          name: item?.lb || item?.dj,
          value: item?.num,
          percent: ((item?.num / roadTotal?.num) * 100).toFixed(2),
        };
      }),
    );
  }, [
    bridgeMaintenanceLevelData,
    bridgeMaintenanceTypeData,
    roadMaintenanceLevelData,
    roadMaintenanceTypeData,
    bridgeTotal,
    roadTotal,
    viewType,
    activeTab,
  ]);

  console.log(chartData);

  const tabLabels: Record<TabKey, string> = {
    level: '养护等级',
    type: '养护类别',
  };

  const tabs: TabKey[] = ['level', 'type'];

  const pieOption = {
    color: ['#FF9B5D', '#FFE335', '#35B2FF', '#77E67B', '#00FFB3'],
    tooltip: {
      borderWidth: '0',
      backgroundColor: 'rgba(73,81,92,.95)', //背景颜色
      textStyle: {
        color: '#fff', //字体颜色
      },
    },
    series: [
      {
        type: 'pie',
        padAngle: 5,
        // radius: ['46%', '66%'],
        radius: ['65%', '88%'],
        // center: ['36%', '35%'],
        label: {
          show: false,
        },

        data: chartData || [],
      },
    ],
  };

  const onChartReady = (instance: echarts.ECharts) => {
    instance.resize();
  };

  const title = viewType === 'road' ? '道路类型分布' : '桥梁类型分布';
  const unit = viewType === 'road' ? '条' : '座';

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <div className={styles.title}>{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>

      <Flex className={styles.content}>
        <div className={styles.chart}>
          <EChartsReact
            ref={chartRef}
            option={pieOption}
            style={{ height: 183, width: 183 }}
            onChartReady={onChartReady}
          />
        </div>

        <div className={`${styles.legend} `}>
          {/* <div className={styles.legend}> */}
          {chartData?.map((item, index) => (
            <Flex key={index} align="center" className={styles.legendItem}>
              <Badge color={pieOption.color[index]} />
              <span className={styles.name}>{item.name}</span>
              <span className={styles.value}>{item.value ?? '--'}</span>
              <span className={styles.unit}>{unit}</span>
              <span className={styles.percent}>{item.percent ?? '--'}%</span>
            </Flex>
          ))}
        </div>
      </Flex>
    </div>
  );
};

export default BridgeTypeDistribution;
