import React, { useEffect, useRef, useState } from 'react';
import { Card, Result, Select, Button, Segmented ,Input} from 'antd';
import { CheckCircleOutlined, ExportOutlined, SearchOutlined } from '@ant-design/icons';
import * as echarts from 'echarts';
import StandardTable from '@/components/StandardTable';
import styles from './RealtimeMonitoring.less';

import eqicon1 from '@/assets/business_basic/eqicon1.png';
import eqicon2 from '@/assets/business_basic/iconre1.svg';
import eqicon3 from '@/assets/business_basic/iconre2.svg';
import eqicon4 from '@/assets/business_basic/iconre3.svg';

import ssbj1 from '@/assets/business_basic/ssbj1.svg';
import ssbj2 from '@/assets/business_basic/ssbj2.svg';
import ssbj3 from '@/assets/business_basic/ssbj3.svg';
import ssbj4 from '@/assets/business_basic/ssbj4.svg';


const RealtimeMonitoring = () => {
    const chartRef = useRef(null);
    const pieChartRef = useRef(null);
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [selectedRows, setSelectedRows] = useState([]);
    const [loading, setLoading] = useState(false);
    const [dataSource, setDataSource] = useState([]);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 5,
        total: 0,
    });

    // 饼图初始化
    useEffect(() => {
        if (pieChartRef.current) {
            const pieChart = echarts.init(pieChartRef.current);

            const pieOption = {
                color: ['#4B69F1', '#FFD85A', '#A493FB', '#9AA5D5'],
                legend: {
                    orient: 'vertical',
                    right: '10%',
                    top: 'center',
                    itemWidth: 10,
                    itemHeight: 3,
                    textStyle: {
                        fontSize: 12,
                        color: '#333'
                    }
                },
                series: [{
                    name: '设备状态',
                    type: 'pie',
                    radius: ['40%', '70%'],
                    center: ['35%', '50%'],
                    avoidLabelOverlap: false,
                    label: {
                        show: false,
                        position: 'center'
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: '14',
                            fontWeight: 'bold'
                        }
                    },
                    labelLine: {
                        show: false
                    },
                    data: [
                        { value: 480, name: '正常运行' },
                        { value: 289, name: '待维护' },
                        { value: 200, name: '故障' },
                        { value: 150, name: '离线' }
                    ]
                }]
            };

            pieChart.setOption(pieOption);

            // 响应式调整
            const handlePieResize = () => {
                if (pieChart && !pieChart.isDisposed()) {
                    pieChart.resize();
                }
            };

            window.addEventListener('resize', handlePieResize);

            return () => {
                window.removeEventListener('resize', handlePieResize);
                if (pieChart && !pieChart.isDisposed()) {
                    pieChart.dispose();
                }
            };
        }
    }, []);


    useEffect(() => {
        if (chartRef.current) {
            const chart = echarts.init(chartRef.current);

            // 强制初始化时调整大小
            setTimeout(() => {
                if (chart && !chart.isDisposed()) {
                    chart.resize();
                }
            }, 100);

            const option = {
                color: ['#8979FF', '#3CC3DF'],

                legend: {
                    // data: ['消防水泵1', '消防水泵2'],
                    top: "-3px",
                    // left: "center",
                    // itemGap: 40,
                    itemWidth: 20,
                    itemHeight: 8,
                    // icon: 'path://M902 472.7H747.9c-19.1-113.3-117.7-200-236.4-200s-217.3 86.7-236.4 200H119.7c-4.4 0-8 3.6-8 8v64c0 4.4 3.6 8 8 8h155.5c19.1 113.3 117.7 200 236.4 200S728.9 666 748 552.7h154c4.4 0 8-3.6 8-8v-64c0-4.4-3.6-8-8-8z m-390.5 200c-88.2 0-160-71.8-160-160s71.8-160 160-160 160 71.8 160 160-71.8 160-160 160z',
                    textStyle: {
                        fontSize: 10
                    }
                },
                grid: {
                    left: '2%',
                    right: '4%',
                    bottom: '2%',
                    top: '12%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
                    axisLabel: {
                        fontSize: 10
                    },
                    splitLine: {
                        show: true,
                        lineStyle: {
                            type: 'dashed'
                        }
                    }
                },
                yAxis: {
                    type: 'value',
                    min: 0,
                    max: 10,
                    interval: 2,
                    axisLabel: {
                        formatter: '{value}',
                        fontSize: 10
                    },
                    splitLine: {
                        show: true,
                        lineStyle: {
                            type: 'dashed'
                        }
                    }
                },
                series: [
                    {
                        name: '故障报警',
                        type: 'line',
                        smooth: true,
                        lineStyle: {
                            width: 2,
                            color: '#8979FF'
                        },
                        areaStyle: {
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [
                                    { offset: 0, color: 'rgba(137, 121, 255, 0.3)' },
                                    { offset: 1, color: 'rgba(137, 121, 255, 0.05)' }
                                ]
                            }
                        },
                        symbol: 'circle',
                        symbolSize: 4,
                        itemStyle: {
                            color: '#fff',
                            borderColor: '#8979FF',
                            borderWidth: 1
                        },
                        data: [3, 5, 4, 6, 7, 5, 4]
                    },
                    {
                        name: '火灾报警',
                        type: 'line',
                        smooth: true,
                        lineStyle: {
                            width: 2,
                            color: '#FF928A'
                        },
                        areaStyle: {
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [
                                    { offset: 0, color: 'rgba(255, 146, 138, 0.3)' },
                                    { offset: 1, color: 'rgba(255, 146, 138, 0.05)' }
                                ]
                            }
                        },
                        symbol: 'circle',
                        symbolSize: 4,
                        itemStyle: {
                            color: '#fff',
                            borderColor: '#FF928A',
                            borderWidth: 1
                        },
                        data: [2, 3, 4, 3, 5, 4, 3]
                    }
                ]
            };

            chart.setOption(option);

            // 响应式调整 - 使用多种方式监听容器尺寸变化
            let resizeTimer = null;
            const handleResize = () => {
                // 防抖处理，避免频繁调用resize
                if (resizeTimer) {
                    clearTimeout(resizeTimer);
                }
                resizeTimer = setTimeout(() => {
                    if (chart && !chart.isDisposed()) {
                        chart.resize();
                    }
                }, 50); // 减少延迟时间
            };

            // 监听窗口大小变化
            window.addEventListener('resize', handleResize);

            // 监听容器尺寸变化（解决菜单栏伸缩时的自适应问题）
            let resizeObserver = null;
            if (window.ResizeObserver) {
                resizeObserver = new ResizeObserver((entries) => {
                    for (let entry of entries) {
                        // 使用requestAnimationFrame确保在下一帧执行
                        requestAnimationFrame(() => {
                            handleResize();
                        });
                    }
                });
                resizeObserver.observe(chartRef.current);
            }

            // 额外监听父容器的尺寸变化
            const parentContainer = chartRef.current?.parentElement;
            let parentObserver = null;
            if (parentContainer && window.ResizeObserver) {
                parentObserver = new ResizeObserver((entries) => {
                    for (let entry of entries) {
                        requestAnimationFrame(() => {
                            handleResize();
                        });
                    }
                });
                parentObserver.observe(parentContainer);
            }

            // 使用MutationObserver监听DOM结构变化（菜单展开收起时）
            const mutationObserver = new MutationObserver((mutations) => {
                mutations.forEach((mutation) => {
                    if (mutation.type === 'attributes' &&
                        (mutation.attributeName === 'class' || mutation.attributeName === 'style')) {
                        // 延迟执行，确保DOM更新完成
                        setTimeout(() => {
                            handleResize();
                        }, 200);
                    }
                });
            });

            // 监听整个页面的class和style变化
            mutationObserver.observe(document.body, {
                attributes: true,
                attributeFilter: ['class', 'style'],
                subtree: true
            });

            return () => {
                window.removeEventListener('resize', handleResize);
                if (resizeObserver) {
                    resizeObserver.disconnect();
                }
                if (parentObserver) {
                    parentObserver.disconnect();
                }
                if (mutationObserver) {
                    mutationObserver.disconnect();
                }
                if (resizeTimer) {
                    clearTimeout(resizeTimer);
                }
                if (chart && !chart.isDisposed()) {
                    chart.dispose();
                }
            };
        }
    }, []);

    // 表格列定义
    const columns = [
        {
            title: '编号',
            dataIndex: 'id',
            key: 'id',
            width: 60,
            render: (text, record, index) => {
                const page = pagination.current || 1;
                const pageSize = pagination.pageSize || 5;
                const number = (page - 1) * pageSize + index + 1;
                return `0${number}`.slice(-2);
            }
        },
        {
            title: '设备编号',
            dataIndex: 'deviceId',
            key: 'deviceId',
            width: 140,
        },
        {
            title: '设备名称',
            dataIndex: 'deviceName',
            key: 'deviceName',
            width: 110,
        },
        {
            title: '所在位置',
            dataIndex: 'installLocation',
            key: 'installLocation',
            width: 200,
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width: 80,
            render: (text) => {
                const statusMap = {
                    '故障': { color: '#FF4D4F', bg: '#FFF2F0' },
                    '预警': { color: '#FAAD14', bg: '#FFF3E9' },
                    '正常': { color: '#44BB5F', bg: '#D8F7DE' }
                };
                const status = statusMap[text] || { color: '#333', bg: '#F5F5F5' };
                return (
                    <span style={{
                        color: status.color,
                        backgroundColor: status.bg,
                        padding: '2px 8px',
                        borderRadius: '4px',
                        fontSize: '12px'
                    }}>
                        {text}
                    </span>
                );
            }
        },
        {
            title: '最后维护',
            dataIndex: 'lastMaintenance',
            key: 'lastMaintenance',
            width: 150,
        },
        {
            title: '操作',
            key: 'action',
            width: 140,
            render: (_, record) => (
                <div>
                    <Button type="link" size="small" style={{
                        padding: '2px 8px',
                        fontSize: 12,
                        backgroundColor: 'transparent',
                        borderRadius: '4px'
                    }}>
                        详情
                    </Button>
                </div>
            ),
        },
    ];

    // 模拟数据
    const mockData = [
        {
            key: '1',
            id: '001',
            deviceId: 'DEV2024001',
            deviceName: '烟雾探测器',
            installLocation: '总部大楼1层大厅',
            status: '故障',
            lastMaintenance: '2025-09-10',
        },
        {
            key: '2',
            id: '002',
            deviceId: 'DEV2024002',
            deviceName: '烟雾探测器',
            installLocation: '总部大楼3层 东区',
            status: '预警',
            lastMaintenance: '2025-09-10',
        },
        {
            key: '3',
            id: '003',
            deviceId: 'DEV2024003',
            deviceName: '消防栓',
            installLocation: '总部大楼地下一层',
            status: '正常',
            lastMaintenance: '2025-09-10',
        },
        {
            key: '4',
            id: '004',
            deviceId: 'DEV2024001',
            deviceName: '消防水泵',
            installLocation: '总部大楼地下一层',
            status: '故障',
            lastMaintenance: '2025-09-10',
        },
        {
            key: '5',
            id: '005',
            deviceId: 'DEV2024005',
            deviceName: '消防水泵',
            installLocation: '总部大楼地下一层',
            status: '正常',
            lastMaintenance: '2025-09-10',
        },
        {
            key: '6',
            id: '006',
            deviceId: 'DEV2024006',
            deviceName: '消防水泵',
            installLocation: '总部大楼地下一层',
            status: '预警',
            lastMaintenance: '2025-09-10',
        },
        {
            key: '7',
            id: '007',
            deviceId: 'DEV2024007',
            deviceName: '消防水泵',
            installLocation: '总部大楼地下一层',
            status: '故障',
            lastMaintenance: '2025-09-10',
        },
        {
            key: '8',
            id: '008',
            deviceId: 'DEV2024008',
            deviceName: '消防水泵',
            installLocation: '总部大楼地下一层',
            status: '正常',
            lastMaintenance: '2025-09-10',
        },
        {
            key: '9',
            id: '009',
            deviceId: 'DEV2024009',
            deviceName: '消防水泵',
            installLocation: '总部大楼地下一层',
            status: '预警',
            lastMaintenance: '2025-09-10',
        },
        {
            key: '10',
            id: '010',
            deviceId: 'DEV2024010',
            deviceName: '消防水泵',
            installLocation: '总部大楼地下一层',
            status: '故障',
            lastMaintenance: '2025-09-10',
        },
        {
            key: '11',
            id: '011',
            deviceId: 'DEV2024011',
            deviceName: '消防水泵',
            installLocation: '总部大楼地下一层',
            status: '正常',
            lastMaintenance: '2025-09-10',
        },
        {
            key: '12',
            id: '012',
            deviceId: 'DEV2024012',
            deviceName: '消防水泵',
            installLocation: '总部大楼地下一层',
            status: '预警',
            lastMaintenance: '2025-09-10',
        },
    ];

    // 初始化数据
    useEffect(() => {
        setPagination(prev => ({ ...prev, total: mockData.length }));
    }, []);

    // 根据分页获取当前页数据
    const getCurrentPageData = () => {
        const { current, pageSize } = pagination;
        const startIndex = (current - 1) * pageSize;
        const endIndex = startIndex + pageSize;
        return mockData.slice(startIndex, endIndex);
    };

    // 表格选择变化
    const onSelectChange = (newSelectedRowKeys, newSelectedRows) => {
        setSelectedRowKeys(newSelectedRowKeys);
        setSelectedRows(newSelectedRows);
    };

    // 新增设备按钮点击事件
    const handleAddDevice = () => {
        console.log('新增设备');
        // TODO: 实现新增设备逻辑
    };

    // 导出数据按钮点击事件
    const handleExportData = () => {
        console.log('导出数据');
        // TODO: 实现导出数据逻辑
    };

    // 分页变化处理
    const handleTableChange = (pagination) => {
        setPagination(prev => ({
            ...prev,
            current: pagination.current,
            pageSize: pagination.pageSize,
        }));
    };

    return (
        <div className={styles.realtimeContainer}>
            {/* 第一个div - 高度20% */}
            <div className={styles.realtimeContainerTop}>
                <div className={styles.realtimeSectionContent}>
                    <div className={styles.realtimeBlocksContainer}>
                        {/* 块1 */}
                        <div className={styles.realtimeBlockItem}>
                            <div className={styles.realtimeBlockLeft}>
                                <div className={styles.realtimeBlockTitle}>设备总数</div>
                                <div className={styles.realtimeBlockNumber}>1280</div>
                            </div>
                            <div className={styles.realtimeBlockRight}>
                                <img src={eqicon1} alt="设备总数" className={styles.realtimeBlockImage} />
                            </div>
                        </div>

                        {/* 块2 */}
                        <div className={styles.realtimeBlockItem}>
                            <div className={styles.realtimeBlockLeft}>
                                <div className={styles.realtimeBlockTitle}>本月报警</div>
                                <div className={styles.realtimeBlockNumber}>32</div>
                            </div>
                            <div className={styles.realtimeBlockRight}>
                                <img src={eqicon2} alt="高风险设备" className={styles.realtimeBlockImage} />
                            </div>
                        </div>

                        {/* 块3 */}
                        <div className={styles.realtimeBlockItem}>
                            <div className={styles.realtimeBlockLeft}>
                                <div className={styles.realtimeBlockTitle}>巡检任务</div>
                                <div className={styles.realtimeBlockNumber}>158</div>
                            </div>
                            <div className={styles.realtimeBlockRight}>
                                <img src={eqicon3} alt="今日预警次数" className={styles.realtimeBlockImage} />
                            </div>
                        </div>

                        {/* 块4 */}
                        <div className={styles.realtimeBlockItem}>
                            <div className={styles.realtimeBlockLeft}>
                                <div className={styles.realtimeBlockTitle}>待处理隐患</div>
                                <div className={styles.realtimeBlockNumber}>19</div>
                            </div>
                            <div className={styles.realtimeBlockRight}>
                                <img src={eqicon4} alt="未处理预警" className={styles.realtimeBlockImage} />
                            </div>
                        </div>

                    </div>
                </div>
            </div>

            <div className={styles.realtimeContainerMiddle}>
                <div className={styles.realtimeSectionContent}>

                    <div className={styles.realtimeMiddleBlock2}>
                        <div className={styles.realtimeMiddleBlock2Title}>
                            <div className={styles.realtimeTitleLeft}>
                                <div className={styles.realtimeTitleIcon}></div>
                                <div>设备运行参数</div>
                            </div>
                        </div>
                        <div className={styles.realtimeMiddleBlock2Chart} ref={chartRef}>
                        </div>
                    </div>


                    <div className={styles.realtimeMiddleBlock1}>
                        <div className={styles.realtimeBlock1Header}>
                            <div className={styles.realtimeBlock1Title}>
                                <div className={styles.realtimeTitleIcon}></div>
                                设备状态分布
                            </div>

                        </div>
                        {/* 设备状态饼图 */}
                        <div className={styles.realtimeDeviceStatusChart} ref={pieChartRef}>
                        </div>
                    </div>


                    <div className={styles.realtimeMiddleBlock12}>
                        <div className={styles.parameterTitle}>
                            <div className={styles.realtimeTitleIcon}></div>
                            参数实时监测
                        </div>

                        <div className={styles.parameterGridContainer}>
                            <div className={styles.parameterRow}>
                                <div className={styles.parameterBlock1}>
                                    <div className={styles.warningBadge}>预警</div>
                                    <div className={styles.blockContent}>
                                        <div className={styles.parameterName}>消防水池水位</div>
                                        <div className={styles.parameterValue}>2.35m</div>
                                        <div className={styles.parameterRange}>正常范围: 2.5-4.0m</div>
                                    </div>
                                </div>
                                <div className={styles.parameterBlock2}>
                                    <div className={styles.warningBadge}>正常</div>
                                    <div className={styles.blockContent}>
                                        <div className={styles.parameterName}>管网水压</div>
                                        <div className={styles.parameterValue}>0.68MPa</div>
                                        <div className={styles.parameterRange}>正常范围: 0.6-0.8 Mpa</div>
                                    </div>
                                </div>
                            </div>
                            <div className={styles.parameterRow}>
                                <div className={styles.parameterBlock3}>
                                    <div className={styles.warningBadge}>正常</div>
                                    <div className={styles.blockContent}>
                                        <div className={styles.parameterName}>电器线路电流</div>
                                        <div className={styles.parameterValue}>125 A</div>
                                        <div className={styles.parameterRange}>正常范围: 0-150 A</div>
                                    </div>
                                </div>
                                <div className={styles.parameterBlock4}>
                                    <div className={styles.warningBadge}>故障</div>
                                    <div className={styles.blockContent}>
                                        <div className={styles.parameterName}>排烟系统风速</div>
                                        <div className={styles.parameterValue}>8,2m/s</div>
                                        <div className={styles.parameterRange}>正常范围: 10-15 m/s</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>

            {/* 第三个div - 占满剩余位置 */}
            <div className={styles.realtimeContainerBottom}>
                <div className={styles.realtimeSectionContent}>
                    <div className={styles.realtimeLeftBlock}>
                        {/* 第一行块 - 蓝色方块加标题 */}
                        <div className={styles.realtimeLeftBlockTitle}>
                            <div className={styles.realtimeTitleIcon}></div>
                            <div>实时报警信息</div>
                        </div>
                        <div className={styles.realtimeDevelopmentContainer}>

                            {/* 块A */}
                            <div className={styles.realtimeDevelopmentBlockA}>
                                <img src={ssbj1} alt="ssbj1" style={{ width: '30px', height: '30px', marginRight: "10px" }} />
                                <div className={styles.realtimeLeftContent}>
                                    <div className={styles.realtimeMainText}>灭火器压力不足</div>
                                    <div className={styles.realtimeSubText} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                        <span>2号楼3层 丨 15分钟前</span>
                                        <span style={{ color: '#999', fontSize: '11px' }}>10:23:34</span>
                                    </div>
                                </div>
                            </div>

                            {/* 块B */}
                            <div className={styles.realtimeDevelopmentBlockB}>
                            <img src={ssbj2} alt="ssbj1" style={{ width: '30px', height: '30px', marginRight: "10px" }} />
                                <div className={styles.realtimeLeftContent}>
                                    <div className={styles.realtimeMainText}>烟雾探测器电池低电量</div>
                                    <div className={styles.realtimeSubText} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                        <span>1号楼5层 丨 1小时前</span>
                                        <span style={{ color: '#999', fontSize: '11px' }}>09:15:22</span>
                                    </div>
                                </div>
                            </div>

                            {/* 块C */}
                            <div className={styles.realtimeDevelopmentBlockC}>
                            <img src={ssbj3} alt="ssbj1" style={{ width: '30px', height: '30px', marginRight: "10px" }} />
                                <div className={styles.realtimeLeftContent}>
                                    <div className={styles.realtimeMainText}>消防栓维护到期</div>
                                    <div className={styles.realtimeSubText} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                        <span>3号楼1层 丨 2小时前</span>
                                        <span style={{ color: '#999', fontSize: '11px' }}>08:45:18</span>
                                    </div>
                                </div>
                            </div>

                            {/*  块D */}
                            <div className={styles.realtimeDevelopmentBlockD}>
                            <img src={ssbj4} alt="ssbj1" style={{ width: '30px', height: '30px', marginRight: "10px" }}  />
                                <div className={styles.realtimeLeftContent}>
                                    <div className={styles.realtimeMainText}>应急照明故障</div>
                                    <div className={styles.realtimeSubText} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                        <span>地下停车场 丨 3小时前</span>
                                        <span style={{ color: '#999', fontSize: '11px' }}>07:30:45</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div className={styles.realtimeRightBlock}>
                        {/* 表格 */}
                        <div className={styles.realtimeTableHeader}>
                            <div className={styles.realtimeTableTitle}>
                                <div className={styles.realtimeTitleIcon}></div>
                                <div>实时监控数据</div>
                            </div>

                            <div className={styles.realtimeTableActions}>
                                <Input 
                                    placeholder="搜索设备..." 
                                    style={{ width: 180, fontSize: 12, borderRadius: '2px' }} 
                                    suffix={<SearchOutlined style={{ color: '#999' }} />}
                                />
                                <button 
                                    className={styles.realtimeActionButton} 
                                    onClick={handleAddDevice}
                                    style={{
                                        backgroundColor: '#2E4CD4',
                                        color: '#fff',
                                        border: '1px solid #2E4CD4',
                                        borderRadius: '2px'
                                    }}
                                >
                                    <span className={styles.realtimeButtonIcon}>+</span>
                                    <span>添加设备</span>
                                </button>
                                <button className={styles.realtimeActionButton} onClick={handleExportData}>
                                    <span className={styles.realtimeButtonIcon}><ExportOutlined /></span>
                                    <span>导出数据</span>
                                </button>
                            </div>
                        </div>

                        {/* 表格 */}
                        <div className={styles.realtimeTableContainer}>
                            <StandardTable
                                columns={columns}
                                data={{
                                    list: getCurrentPageData(),
                                    pagination: pagination
                                }}
                                loading={loading}
                                selectionType="checkbox"
                                onSelectRow={onSelectChange}
                                onChange={handleTableChange}
                                pagination={{
                                    ...pagination,
                                    showSizeChanger: false,
                                    showQuickJumper: true,
                                    showTotal: (total, range) =>
                                        `共 ${total} 条`,
                                }}
                            // scroll={{ x: 1200 }}
                            />
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default RealtimeMonitoring;