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 chartData = useMemo(() => {
    //桥梁
    if (viewType == 'bridge' || viewType == 'location') {
      const list =
        activeTab === 'level'
          ? bridgeMaintenanceLevelData
          : bridgeMaintenanceTypeData;
      return 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 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,
  ]);

  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;
