import React, { useState, useEffect } from 'react';
import { Flex, Space } from 'antd';
import styles from './index.less';
import DescriptionItem from '@/components/DescriptionItem';
import BlueTable from '@/components/BlueTable';
import { ColumnsType } from 'antd/es/table';
import ModuleTitle from '@/pages/Home_v_2504/components/common/ModuleTitle';
import services from '@/services';
import { formatDateTime } from '@/pages/Home_v_2504/hooks/useApiControl';

// 定义组件属性接口
interface RestaurantOilFacilityProps {
  deviceId: string;
  deviceName?: string;
  startTime?: string; 
  endTime?: string;
}

// 餐饮油烟设施弹窗组件
const RestaurantOilFacility: React.FC<RestaurantOilFacilityProps> = ({
  deviceId,
  deviceName = '--',
  startTime = '',
  endTime = ''
}) => {
  // 日期选择器状态
  const [dateType, setDateType] = useState<string>('day');
  // 设备状态数据
  const [statusData, setStatusData] = useState<any[]>([]);
  // 监测详情数据
  const [monitoringData, setMonitoringData] = useState<any[]>([]);
  // 加载状态
  const [loading, setLoading] = useState<boolean>(false);

  // 企业详情数据
  const [enterpriseInfo, setEnterpriseInfo] = useState({
    enterpriseName: deviceName || '--',
    deviceNum: deviceId || '--',
    contactPerson: '--',
    contactPhone: '--',
    address: '--',
    district: '--',
    street: '--'
  });

  // 加载设备详情数据
  useEffect(() => {
    if (deviceId) {
      loadDeviceDetails(deviceId);
      if (startTime && endTime) {
        loadMonitoringData(deviceId, startTime, endTime);
      }
    }
  }, [deviceId, startTime, endTime]);

  // 监测日期类型变化，重新加载数据
  useEffect(() => {
    if (deviceId && startTime && endTime) {
      loadMonitoringData(deviceId, startTime, endTime);
    }
  }, [dateType]);

  // 加载设备基本信息
  const loadDeviceDetails = async (deviceId: string) => {
    if (!deviceId) {
      console.error('缺少设备ID');
      return;
    }
    
    setLoading(true);
    
    try {
      const response = await services.DataBase.getSjdzInfoData({
        typeCode: 'dp-yy-1yxq',
        params: {
          xh: deviceId
        }
      });
      
      // const response = await services.DataBase.getSjdzInfoData({
      //   typeCode: 'dp-yyyzt-sbjcjl',
      //   params: {
      //     pageSize: 20,
      //     pageNo: 0,
      //     startTime: formatDateTime(startTime),
      //     endTime: formatDateTime(endTime, true),
      //     mn: deviceId
      //   }
      // });
      
      if (response.code === 200 && response.data?.data?.records) {
        processEnterpriseData(response.data.data.records);
      } else {
        console.error('获取设备基本信息失败');
      }
    } catch (error) {
      console.error('加载设备基本信息出错:', error);
    } finally {
      setLoading(false);
    }
  };

  // 加载监测数据
  const loadMonitoringData = async (deviceId: string, startTime: string, endTime: string) => {
    if (!deviceId || !startTime || !endTime) {
      console.error('缺少必要的参数');
      return;
    }
    
    setLoading(true);
    
    try {
      // 请求监测数据
      const response = await services.DataBase.getSjdzInfoData({
        typeCode: 'dp-yyyzt-sbjcjl',
        params: {
          pageSize: 20,
          pageNo: 0,
          startTime: formatDateTime(startTime),
          endTime: formatDateTime(endTime, true),
          mn: deviceId
        }
      });
      
      console.log('设备监测数据:', response);
      
      if (response.code === 200 && response.data?.data?.records) {
        processMonitoringData(response.data.data.records);
      } else {
        // 如果没有监测数据，显示模拟数据
        setStatusData([
          { name: '油烟浓度', value: 0, unit: 'mg/m³' },
          { name: '颗粒物浓度', value: 0, unit: 'mg/m³' },
          { name: '非甲烷总烃', value: 0, unit: 'mg/m³' },
          { name: '风机状态', value: '关', unit: '' },
          { name: '净化器状态', value: '关', unit: '' },
        ]);
        setMonitoringData([]);
        console.error('获取设备监测数据失败或为空');
      }
    } catch (error) {
      console.error('加载设备监测数据出错:', error);
      setMonitoringData([]);
    } finally {
      setLoading(false);
    }
  };

  // 处理企业基本信息数据
  const processEnterpriseData = (records: any[]) => {
    try {
      if (records?.length > 0) {
        const record = records[0];
        
        console.log('企业信息数据:', record);
        
        // 更新企业信息
        setEnterpriseInfo({
          enterpriseName: record.qymc || deviceName || '--',
          deviceNum: record.mn || deviceId || '--',
          contactPerson: record.lxr || '--',
          contactPhone: record.lxdh || '--',
          address: record.dz || '--',
          district: record.districtName || '--',
          street: record.streetName || '--'
        });
      }
    } catch (error) {
      console.error('处理企业数据出错:', error);
    }
  };

  // 处理监测数据
  const processMonitoringData = (records: any[]) => {
    try {
      if (records?.length > 0) {
        // 设置最新状态数据（取第一条记录）
        const latestRecord = records[0];
        setStatusData([
          { name: '油烟浓度', value: parseFloat(latestRecord.soot) || 0, unit: 'mg/m³' },
          { name: '颗粒物浓度', value: parseFloat(latestRecord.particulate) || 0, unit: 'mg/m³' },
          { name: '非甲烷总烃', value: parseFloat(latestRecord.nonMethane) || 0, unit: 'mg/m³' },
          { name: '风机状态', value: latestRecord.fan === '1' ? '开' : '关', unit: '' },
          { name: '净化器状态', value: latestRecord.purifier === '1' ? '开' : '关', unit: '' },
        ]);
        
        // 处理监测详情数据
        const formattedData = records.map((item: any, index: number) => ({
          id: (index + 1).toString(),
          monitoringTime: item.datetime || '--',
          oilConcentration: item.soot || '--',
          particleConcentration: item.particulate || '--',
          nmhc: item.nonMethane || '--',
          fanStatus: item.fan === '1' ? '开' : '关',
          purifierStatus: item.purifier === '1' ? '开' : '关',
          status: item.alarmStatus === '是' ? '超时' : '正常'
        }));
        
        setMonitoringData(formattedData);
      } else {
        setMonitoringData([]);
      }
    } catch (error) {
      console.error('处理监测数据出错:', error);
      setMonitoringData([]);
    }
  };

  // 监测详情数据
  interface MonitoringData {
    id: string;
    monitoringTime: string;
    oilConcentration: string;
    particleConcentration: string;
    nmhc: string;
    fanStatus: string;
    purifierStatus: string;
    status: string;
  }

  // 监测详情表格列定义
  const columns: ColumnsType<MonitoringData> = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '监测时间',
      dataIndex: 'monitoringTime',
      key: 'monitoringTime',
      width: 180,
      render: (text: string) => {
        if (!text) return '--';
        try {
          const timePart = text.split(' ')[1];
          return timePart || '--';
        } catch (e) {
          return '--';
        }
      }
    },
    {
      title: '油烟浓度 (mg/m³)',
      dataIndex: 'oilConcentration',
      key: 'oilConcentration',
      width: 160,
    },
    {
      title: '颗粒物浓度 (mg/m³)',
      dataIndex: 'particleConcentration',
      key: 'particleConcentration',
      width: 160,
    },
    {
      title: '非甲烷总烃 (mg/m³)',
      dataIndex: 'nmhc',
      key: 'nmhc',
      width: 160,
    },
    {
      title: '风机状态',
      dataIndex: 'fanStatus',
      key: 'fanStatus',
      width: 120,
    },
    {
      title: '净化器状态',
      dataIndex: 'purifierStatus',
      key: 'purifierStatus',
      width: 120,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (text) => (
        <div className={`${styles.statusTag} ${text === '超时' ? styles.timeoutStatus : styles.normalStatus}`}>
          {text}
        </div>
      ),
    },
  ];

  const valueStyle = {
    color: 'rgb(89, 238, 255)',
    fontFamily: 'D-DIN',
    fontSize: '24px',
    fontWeight: 700,
  }
  const textValueStyle = {
    ...valueStyle,
    fontSize: '20px',
  }
  return (
    <div className={styles.container}>
      <Flex gap={27} className={styles.topRow}>
        {/* 企业详情 */}
        <div className={styles.enterpriseInfo}>
          <ModuleTitle title="企业详情" />
          <div className={styles.infoContent}>
            <Space direction="vertical" size={9} className={styles.scrollArea}>
              <div className={styles.infoItem}>
                <span className={styles.label}>企业名称：</span>
                <span className={styles.value}>{enterpriseInfo.enterpriseName}</span>
              </div>
              <div className={styles.infoItem}>
                <span className={styles.label}>设备编号：</span>
                <span className={styles.value}>{enterpriseInfo.deviceNum}</span>
              </div>
              <div className={styles.infoItem}>
                <span className={styles.label}>联系人：</span>
                <span className={styles.value}>{enterpriseInfo.contactPerson}</span>
              </div>
              <div className={styles.infoItem}>
                <span className={styles.label}>联系电话：</span>
                <span className={styles.value}>{enterpriseInfo.contactPhone}</span>
              </div>
              <div className={styles.infoItem}>
                <span className={styles.label}>所属区县：</span>
                <span className={styles.value}>{enterpriseInfo.district}</span>
              </div>
              <div className={styles.infoItem}>
                <span className={styles.label}>所属街道：</span>
                <span className={styles.value}>{enterpriseInfo.street}</span>
              </div>
              <div className={styles.infoItem}>
                <span className={styles.label}>企业地址：</span>
                <span className={styles.value}>{enterpriseInfo.address}</span>
              </div>
            </Space>
          </div>
        </div>

        {/* 实时运行状态 */}
        <div className={styles.realTimeStatus}>
          <ModuleTitle title="实时运行状态" />
          <Flex wrap="wrap" gap={20} className={styles.statusCards}>
            {statusData.map((item, index) => (
              <div className={styles.statusCard} key={index}>
                <DescriptionItem
                  value={item.value}
                  name={item.name}
                  unit={item.unit}
                  valueStyle={typeof item.value === 'number' ? valueStyle : textValueStyle}
                  labelStyle={{
                    color: 'rgb(203, 237, 255)',
                    fontFamily: 'DingTalk JinBuTi',
                    fontSize: '18px',
                    fontWeight: 400,
                    lineHeight: '22px',
                  }}
                  unitStyle={{
                    color: 'rgb(188, 206, 233)',
                    fontFamily: '微软雅黑',
                    fontSize: '16px',
                    fontWeight: 400,
                    lineHeight: '21px',
                  }}
                  reverseName={true}
                  decimals={3}
                  showTextToValue={typeof item.value !== 'number'}
                />
              </div>
            ))}
          </Flex>
        </div>
      </Flex>

      {/* 监测详情 */}
      <div className={styles.monitoringDetails}>
        <ModuleTitle 
          title="监测详情" 
          // showDateSelector
          dateType={dateType}
          onDateTypeChange={setDateType}
        />
        <div className={styles.tableContainer}>
          <BlueTable
            columns={columns}
            dataSource={monitoringData}
            pagination={false}  // 禁用分页，改用滚动加载
            scroll={{ y: 305 }}
            size='small'
            loading={loading}
          />
        </div>
      </div>
    </div>
  );
};

export default RestaurantOilFacility; 