import React, { useRef, useState } from 'react';
import { Flex, Progress, Select } from 'antd';
import styles from './index.less';
import DescriptionItem from '@/components/DescriptionItem';
import BlueTable from '@/components/BlueTable';
import type { ColumnsType } from 'antd/es/table';
import { useRequest } from 'ahooks';
import services from '@/services';

interface DataType {
  monitorTime: string;
  deviceName: string;
  deviceCode: string;
  deviceType: string;
  onlineStatus: string;
  pipelineName: string;
  monitorValue: string;
  monitorResult: string;
}

const PipelineMonitor: React.FC = () => {
  const [deviceType, setDeviceType] = useState('DATA_SSKZNVYC_1');
  // const [monitorResult, setMonitorResult] = useState('all');
  const [total, setTotal] = useState(0)
  const [page, setPage] = useState({ current: 1, size: 10})

  let isUsingValue = true;

  const columns: ColumnsType<DataType> = [
    {
      title: '监测时间',
      dataIndex: 'monitoringTime',
      key: 'monitoringTime',
      width: 200,
      className: styles.tableCell
    },
    {
      title: '设备名称',
      dataIndex: 'sensorName',
      key: 'sensorName',
      width: 180,
      className: styles.tableCell
    },
    {
      title: '设备编码',
      dataIndex: 'sensorId',
      key: 'sensorId',
      width: 120,
      className: styles.tableCell
    },
    {
      title: '设备类型',
      dataIndex: 'sensorType',
      key: 'sensorType',
      width: 160,
      className: styles.tableCell
    },
    {
      title: '在线状态',
      dataIndex: 'onlineState',
      key: 'onlineState',
      width: 120,
      className: styles.tableCell,
      render: (text) => text === 1 ? '在线' : '离线'
    },
    {
      title: '管廊名称',
      dataIndex: 'galleryName',
      key: 'galleryName',
      width: 170,
      className: styles.tableCell,
      render: (text) => text ? text : '--'
    },
    {
      title: '监测数据值',
      dataIndex: 'value',
      key: 'value',
      width: 130,
      className: styles.tableCell
    },
    // {
    //   title: '监测结果',
    //   dataIndex: 'monitorResult',
    //   key: 'monitorResult',
    //   width: 100,
    //   render: (text) => (
    //     <span className={text === '正常' ? styles.normalStatus : styles.warningStatus}>
    //       {text}
    //     </span>
    //   )
    // }
  ];

  const { data: cpbmhqlbData, loading: tableLoading } = useRequest(
    () =>
      services.DataBase.getGzInfoData({
        "typeCode": "gz-gl-cpbmhqlb",
        "data": {
          "productCode": deviceType,
          current:  page.current,
          size: page.size,
        }
      }).then((res) => {
        if (res.code === 200) {
          setTotal(res?.data?.total)
          return res?.data?.records || {};
        }
        throw new Error('获取数据失败');
      }),
    {
      refreshDeps: [deviceType, page]
    }
  );

  const { data: cpzxlData } = useRequest(
    () =>
      services.DataBase.getGzInfoData({
        typeCode: 'gz-gl-cpzxl',
      }).then((res) => {
        if (res.code === 200) {
          return res?.data || {};
        }
        throw new Error('获取数据失败');
      })
  );

  const { data: cplxlbData } = useRequest(
    () =>
      services.DataBase.getGzInfoData({
        typeCode: 'gz-gl-cplxlb',
      }).then((res) => {
        if (res.code === 200) {
          return res?.data || [];
        }
        throw new Error('获取数据失败');
      })
  );

  const mockData: DataType[] = isUsingValue ? [
    {
      monitorTime: '2024-10-21 10:20:20',
      deviceName: '氧气浓度传感器01',
      deviceCode: 'YQ001',
      deviceType: '氧气浓度传感器',
      onlineStatus: '在线',
      pipelineName: '天府大道管廊A段',
      monitorValue: '25% VOL',
      monitorResult: '预警'
    },
    {
      monitorTime: '2024-10-21 10:20:20',
      deviceName: '一氧化碳传感器02',
      deviceCode: 'CO002',
      deviceType: '一氧化碳气体传感器',
      onlineStatus: '在线',
      pipelineName: '天府大道管廊B段',
      monitorValue: '25% VOL',
      monitorResult: '正常'
    },
    {
      monitorTime: '2024-10-21 10:20:20',
      deviceName: '甲烷传感器03',
      deviceCode: 'JW003',
      deviceType: '甲烷气体传感器',
      onlineStatus: '在线',
      pipelineName: '天府大道管廊C段',
      monitorValue: '25% VOL',
      monitorResult: '正常'
    },
    {
      monitorTime: '2024-10-21 10:20:20',
      deviceName: '硫化氢传感器04',
      deviceCode: 'LH004',
      deviceType: '硫化氢气体传感器',
      onlineStatus: '在线',
      pipelineName: '天府大道管廊D段',
      monitorValue: '25% VOL',
      monitorResult: '正常'
    },
    {
      monitorTime: '2024-10-21 10:20:20',
      deviceName: '温度传感器05',
      deviceCode: 'WD005',
      deviceType: '温度传感器',
      onlineStatus: '在线',
      pipelineName: '天府大道管廊E段',
      monitorValue: '25% VOL',
      monitorResult: '正常'
    },
    {
      monitorTime: '2024-10-21 10:20:20',
      deviceName: '温度传感器06',
      deviceCode: 'WD006',
      deviceType: '温度传感器',
      onlineStatus: '在线',
      pipelineName: '天府大道管廊F段',
      monitorValue: '25% VOL',
      monitorResult: '正常'
    },
    {
      monitorTime: '2024-10-21 10:20:20',
      deviceName: '液位监测传感器07',
      deviceCode: 'YW007',
      deviceType: '液位监测传感器',
      onlineStatus: '在线',
      pipelineName: '天府大道管廊G段',
      monitorValue: '25% VOL',
      monitorResult: '正常'
    },
    {
      monitorTime: '2024-10-21 10:20:20',
      deviceName: '氧气浓度传感器08',
      deviceCode: 'YQ008',
      deviceType: '氧气浓度传感器',
      onlineStatus: '在线',
      pipelineName: '天府大道管廊H段',
      monitorValue: '25% VOL',
      monitorResult: '正常'
    },
    {
      monitorTime: '2024-10-21 10:20:20',
      deviceName: '一氧化碳传感器09',
      deviceCode: 'CO009',
      deviceType: '一氧化碳气体传感器',
      onlineStatus: '在线',
      pipelineName: '天府大道管廊I段',
      monitorValue: '25% VOL',
      monitorResult: '正常'
    },
    {
      monitorTime: '2024-10-21 10:20:20',
      deviceName: '甲烷传感器10',
      deviceCode: 'JW010',
      deviceType: '甲烷气体传感器',
      onlineStatus: '在线',
      pipelineName: '天府大道管廊J段',
      monitorValue: '25% VOL',
      monitorResult: '正常'
    }
  ] : [];

  const deviceTypeList = isUsingValue ? [
    { type: '氧气浓度传感器', count: 156, rate: 49.56, warning: 12 },
    { type: '一氧化碳气体传感器', count: 156, rate: 59.56, warning: 12 },
    { type: '甲烷气体传感器', count: 156, rate: 69.56, warning: 12 },
    { type: '硫化氢气体传感器', count: 156, rate: 79.56, warning: 12 },
    { type: '温度传感器', count: 156, rate: 19.56, warning: 12 },
    { type: '温度传感器', count: 156, rate: 49.56, warning: 12 },
    { type: '液位监测传感器', count: 156, rate: 89.56, warning: 12 },
    { type: '液位监测传感器', count: 156, rate: 99.56, warning: 12 },
  ] : [
    { type: '--', count: '--', rate: '--', warning: '--' },
    { type: '--', count: '--', rate: '--', warning: '--' },
    { type: '--', count: '--', rate: '--', warning: '--' },
    { type: '--', count: '--', rate: '--', warning: '--' },
    { type: '--', count: '--', rate: '--', warning: '--' },
    { type: '--', count: '--', rate: '--', warning: '--' },
    { type: '--', count: '--', rate: '--', warning: '--' },
    { type: '--', count: '--', rate: '--', warning: '--' },
  ];

  const commonValueStyle = {
    fontFamily: 'D-DIN Exp',
    fontSize: '36px',
    fontWeight: '700',
    background: 'linear-gradient(180deg, #9CF8F7 0%, #25BBFF 100%)',
    WebkitBackgroundClip: 'text',
    WebkitTextFillColor: 'transparent',
  };

  const commonLabelStyle = {
    color: '#BCCEE9',
    fontSize: '20px',
    marginTop: '-4px'
  };

  const commonUnitStyle = {
    color: '#BCCEE9',
    fontSize: '20px',
  };

  return (
    <div className={styles.container}>
      <div className={styles.leftContent}>
        {/* 顶部统计区域 */}
        <div className={styles.statsSection}>
          <div className={styles.title}>感知设备概况</div>
          <Flex gap={40} align="center" justify="space-between" style={{ padding: '0 60px 0 10px' }}>
            <DescriptionItem
              name="已接入感知设备"
              value={cpzxlData?.utilityTunnelNum}
              unit="个"
              valueStyle={commonValueStyle}
              labelStyle={commonLabelStyle}
              unitStyle={commonUnitStyle}
            />
            <DescriptionItem
              name="在线"
              value={cpzxlData?.utilityTunnelOnlineNum}
              unit="个"
              valueStyle={commonValueStyle}
              labelStyle={commonLabelStyle}
              unitStyle={commonUnitStyle}
            />
            <DescriptionItem
              name="设备在线率"
              value={cpzxlData?.utilityTunnelOnlineRate * 100}
              unit="%"
              decimals={cpzxlData?.utilityTunnelOnlineRate && !Number.isInteger(cpzxlData?.utilityTunnelOnlineRate * 100) ? 2 : 0}
              valueStyle={{ ...commonValueStyle, background: '#55D355' }}
              labelStyle={commonLabelStyle}
              unitStyle={commonUnitStyle}
            />
            {/* <DescriptionItem
              name="预警数"
              value={isUsingValue ? 82 : '--'}
              unit="个" 
              valueStyle={{...commonValueStyle, background: '#FFB05A'}}
              labelStyle={commonLabelStyle}
              unitStyle={commonUnitStyle}
            /> */}
          </Flex>
        </div>

        {/* 设备类型分布区域 */}
        <div className={styles.deviceSection}>
          <div className={styles.title}>各设备类型分布</div>
          <div className={styles.header}>
            <span className={styles.type}>感知设备类型</span>
            <span className={styles.count}>设备总数</span>
            <span className={styles.rate}>设备在线率</span>
            <span className={styles.percentage}> </span>
            {/* <span className={styles.warning}>预警数</span> */}
          </div>
          <div className={styles.deviceList}>
            {/* 设备类型列表项 */}
            {cpzxlData?.sensorList?.map((item, index) => (
              <Flex key={item.index} className={styles.deviceItem} justify="space-between" align="center">
                <span className={styles.type}>{item.productName}</span>
                <span className={styles.count}>{item.sensorNum}</span>
                <Progress
                  size={{ height: 15 }}
                  percent={Number(item.onlineRate)}
                  showInfo={false}
                  trailColor="rgba(144, 205, 229, 0.22)"
                  strokeColor={{ from: '#00B9FF', to: '#79FFD1' }}
                  className={styles.progress}
                />
                <span className={styles.rate}>{Number.isInteger(item.onlineRate * 100) ? item.onlineRate * 100 : (item.onlineRate * 100)?.toFixed(2)}%</span>
                {/* <span className={styles.warning}>{item.warning}</span> */}
              </Flex>
            ))}
          </div>
        </div>
      </div>

      {/* 表格筛选和数据区域 */}
      <div className={styles.tableSection}>
        <div className={styles.title}>感知设备实时监测信息</div>
        <Flex gap={20} className={styles.filters}>
          <Select
            value={deviceType}
            onChange={setDeviceType}
            options={cplxlbData}
            className={styles.select}
            fieldNames={{ label: 'productName', value: 'productCode' }}
          />
          {/* <Select
            value={monitorResult}
            onChange={setMonitorResult}
            options={isUsingValue ? [
              { value: 'all', label: '监测结果' },
              { value: 'normal', label: '正常' },
              { value: 'warning', label: '预警' },
            ] : [{ value: 'all', label: '监测结果' }]}
            className={styles.select}
          /> */}
        </Flex>
        <BlueTable
          columns={columns}
          loading={tableLoading}
          dataSource={cpbmhqlbData || []}
          scroll={{ y: 470 }}
          pagination={{
            total: total,
            onChange: (pageNum, pageSize) => {
              setPage({ current: pageNum, size: pageSize})
            }
          }}
        />
      </div>
    </div>
  );
};

export default PipelineMonitor; 