import React, { useState, useEffect } from 'react';
import { Flex, Space } from 'antd';
import styles from './index.less';
import SmoothLineChart from '@/components/V2504/SmoothLineChart';
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 RestaurantOilAlarmProps {
  deviceId: string;
  deviceName?: string;
  startTime?: string; 
  endTime?: string;
}

// 告警详情弹窗组件
const RestaurantOilAlarm: React.FC<RestaurantOilAlarmProps> = ({
  deviceId,
  deviceName = '--',
  startTime = '',
  endTime = ''
}) => {
  // 日期选择器状态
  const [dateType, setDateType] = useState<string>('day');
  // 告警趋势数据
  const [trendData, setTrendData] = useState<{ time: string; value: number }[]>([]);
  // 告警详情数据
  const [alarmData, setAlarmData] = useState<any[]>([]);
  // 加载状态
  const [loadingTrend, setLoadingTrend] = useState<boolean>(false);
  const [loadingDetails, setLoadingDetails] = useState<boolean>(false);

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

  // 实时运行状态数据
  const statusData = [
    { name: '油烟浓度', value: '--', unit: 'mg/m³' },
    { name: '颗粒物浓度', value: '--', unit: 'mg/m³' },
    { name: '非甲烷总烃', value: '--', unit: 'mg/m³' },
    { name: '风机状态', value: '--', unit: '' },
    { name: '净化器状态', value: '--', unit: '' },
  ];
  // const statusData = [
  //   { name: '油烟浓度', value: 0.222, unit: 'mg/m³' },
  //   { name: '颗粒物浓度', value: 0.222, unit: 'mg/m³' },
  //   { name: '非甲烷总烃', value: 0.222, unit: 'mg/m³' },
  //   { name: '风机状态', value: '开', unit: '' },
  //   { name: '净化器状态', value: '关', unit: '' },
  // ];

  // 告警详情数据类型
  interface AlarmData {
    id: string;
    alarmTime: string;
    oilConcentration: string;
    excessValue: string;
  }

  // 加载数据
  useEffect(() => {
    if (deviceId && startTime && endTime) {
      loadAlarmTrend(deviceId, dateType, startTime, endTime);
      loadAlarmDetails(deviceId, startTime, endTime);
    }
  }, [deviceId, startTime, endTime]);

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

  // 构建日期参数
  const buildDateParams = (dateType: string, startTimeBase: string, endTimeBase: string) => {
    let startTime = startTimeBase;
    let endTime = endTimeBase;
    
    // 根据日期类型调整时间范围
    const now = new Date();
    if (dateType === 'day') {
      // 当天数据
      const today = new Date();
      startTime = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
      endTime = startTime;
    } else if (dateType === 'month') {
      // 当月数据
      const firstDay = new Date(now.getFullYear(), now.getMonth(), 1);
      const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0);
      startTime = `${firstDay.getFullYear()}-${String(firstDay.getMonth() + 1).padStart(2, '0')}-${String(firstDay.getDate()).padStart(2, '0')}`;
      endTime = `${lastDay.getFullYear()}-${String(lastDay.getMonth() + 1).padStart(2, '0')}-${String(lastDay.getDate()).padStart(2, '0')}`;
    } else if (dateType === 'year') {
      // 当年数据
      const firstDay = new Date(now.getFullYear(), 0, 1);
      const lastDay = new Date(now.getFullYear(), 11, 31);
      startTime = `${firstDay.getFullYear()}-${String(firstDay.getMonth() + 1).padStart(2, '0')}-${String(firstDay.getDate()).padStart(2, '0')}`;
      endTime = `${lastDay.getFullYear()}-${String(lastDay.getMonth() + 1).padStart(2, '0')}-${String(lastDay.getDate()).padStart(2, '0')}`;
    }
    
    return { startTime, endTime };
  };

  // 加载告警趋势数据
  const loadAlarmTrend = async (deviceId: string, dateType: string, startTimeBase: string, endTimeBase: string) => {
    if (!deviceId || !startTimeBase || !endTimeBase) {
      console.error('加载告警趋势数据：缺少必要的参数');
      return;
    }
    
    setLoadingTrend(true);
    
    try {
      const { startTime, endTime } = buildDateParams(dateType, startTimeBase, endTimeBase);
      
      const response = await services.DataBase.getSjdzInfoData({
        typeCode: 'dp-yyyzt-yygjqs',
        params: {
          startTime: formatDateTime(startTime),
          endTime: formatDateTime(endTime, true),
          mn: deviceId,
          type: dateType
        }
      });
      
      console.log('告警趋势数据:', response);
      
      if (response.code === 200 && response.data?.data && response.data.data.records) {
        processTrendData(response.data.data.records, dateType);
      } else {
        console.error('获取告警趋势数据失败');
        setTrendData([]);
      }
    } catch (error) {
      console.error('加载告警趋势数据出错:', error);
      setTrendData([]);
    } finally {
      setLoadingTrend(false);
    }
  };

  // 处理趋势数据
  const processTrendData = (data: any, dateType: string) => {
    try {
      if (!data || !Array.isArray(data)) {
        console.error('趋势数据格式不正确');
        return;
      }
      
      // 处理API返回的趋势数据
      const formattedData = data.map((item: any) => ({
        time: translateTrendTime(item.sj),
        value: parseInt(item.num) || 0
      }));
      
      console.log('格式化后的趋势数据:', formattedData);
      setTrendData(formattedData);
    } catch (error) {
      console.error('处理趋势数据出错:', error);
      setTrendData([]);
    }
  };
  
  const translateTrendTime = (inputDate: string | number) => {
    if (typeof inputDate === 'string') {
      // 处理类似'202504'的格式
      if (inputDate.length === 6) {
        const month = parseInt(inputDate.substring(4, 6));
        return `${month}月`;
      }
      // 处理类似'20250425'的格式
      if (inputDate.length === 8) {
        const month = parseInt(inputDate.substring(4, 6));
        const day = parseInt(inputDate.substring(6, 8));
        return `${month}月${day}日`;
      }
      return inputDate.substring(0, 10);
    }
    // 处理number类型
    if (typeof inputDate === 'number') {
      if (inputDate === 23) {
        return '23:59:59';
      }
      return `${inputDate.toString().padStart(2, '0')}:00:00`;
    }
    return inputDate;
  }

  // 加载告警详情数据
  const loadAlarmDetails = async (deviceId: string, startTime: string, endTime: string) => {
    if (!deviceId || !startTime || !endTime) {
      console.error('加载告警详情数据：缺少必要的参数');
      return;
    }
    
    setLoadingDetails(true);
    
    try {
      const response = await services.DataBase.getSjdzInfoData({
        typeCode: 'dp-yy-sbgjjl',
        params: {
          pageSize: 20,
          pageNo: 0,
          startTime: formatDateTime(startTime),
          endTime: formatDateTime(endTime, true),
          mn: deviceId
        }
      });
      
      console.log('告警详情数据:', response);
      
      if (response.code === 200 && response.data?.data) {
        processAlarmData(response.data.data);
      } else {
        console.error('获取告警详情数据失败');
        setAlarmData([]);
      }
    } catch (error) {
      console.error('加载告警详情数据出错:', error);
      setAlarmData([]);
    } finally {
      setLoadingDetails(false);
    }
  };

  // 处理告警详情数据
  const processAlarmData = (data: any) => {
    try {
      const { records } = data;
      
      if (records?.length > 0) {
        const record = records[0];
        
        if (record.list && Array.isArray(record.list)) {
          console.log('告警详情数据:', record);
          
          // 处理告警详情数据
          const formattedData = record.list.map((item: any, index: number) => ({
            id: (index + 1).toString(),
            alarmTime: item.datetime || '--',
            oilConcentration: item.soot || '--',
            excessValue: item.cbbs || '--'
          }));
          
          setAlarmData(formattedData);
        } else {
          console.warn('告警详情数据格式不正确');
          setAlarmData([]);
        }
      } else {
        setAlarmData([]);
      }
    } catch (error) {
      console.error('处理告警详情数据出错:', error);
      setAlarmData([]);
    }
  };

  // 告警详情表格列定义
  const columns: ColumnsType<AlarmData> = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '告警时间',
      dataIndex: 'alarmTime',
      key: 'alarmTime',
      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: '超标倍数',
      dataIndex: 'excessValue',
      key: 'excessValue',
      width: 100,
    },
  ];

  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={23} 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.address}</span>
              </div>
            </Space>
          </div>
        </div>

        {/* 告警趋势 */}
        <div className={styles.alarmTrend}>
          <ModuleTitle
            title="告警趋势"
            showDateSelector
            dateType={dateType}
            onDateTypeChange={setDateType}
          />
          <div className={styles.chartContainer}>
            <SmoothLineChart
              data={trendData}
              showUnitText={false}
              lineColor='rgb(255, 100, 89)'
              lineColorStop1="rgba(255, 100, 89, 0)"
              lineColorStop2="rgba(255, 100, 89, 0.36)"
              style={{ height: '200px', width: '520px' }}
              // loading={loadingTrend}
            />
          </div>
        </div>
      </Flex>

      <Flex gap={23} className={styles.bottomRow}>
        {/* 实时运行状态 */}
        <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>

        {/* 告警详情 */}
        <div className={styles.alarmDetails}>
          <ModuleTitle title="告警详情" />
          <div className={styles.tableContainer}>
            <BlueTable
              columns={columns}
              dataSource={alarmData}
              pagination={false}
              scroll={{ y: 211 }}
              size='small'
              loading={loadingDetails}
            />
          </div>
        </div>
      </Flex>
    </div>
  );
};

export default RestaurantOilAlarm;