
import React, { useEffect, useRef, useState } from 'react';
import { Card, Result, Select, Button, Segmented, Input } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import * as echarts from 'echarts';
import StandardTable from '@/components/StandardTable';
import styles from './EmergencyDrillRecordAssociation.less';
import eqicon1 from '@/assets/business_firekeynotearea/eqicon1.png';
import eqicon6 from '@/assets/business_firekeynotearea/eqicon6.png';
import eqicon7 from '@/assets/business_firekeynotearea/eqicon7.png';
import eqicon8 from '@/assets/business_firekeynotearea/eqicon8.png';

const EmergencyDrillRecordAssociation = () => {
    const chartRef = useRef(null);
    const pieChartRef = useRef(null);
    const faultPieChartRef = 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: ['#44BB5F', '#F8C541', '#A493FB', '#4B69F1', '#949FD0'],
                legend: {
                    orient: 'vertical',
                    right: '10%',
                    top: 'center',
                    itemWidth: 13,
                    itemHeight: 4,
                    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: '服务器机房' },
                        { value: 161, 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 (faultPieChartRef.current) {
            const faultPieChart = echarts.init(faultPieChartRef.current);

            const faultPieOption = {
                color: ['#FF3E48', '#FF8800', '#FFC403'],
                legend: {
                    orient: 'vertical',
                    right: '10%',
                    top: 'center',
                    itemWidth: 8,
                    itemHeight: 8,
                    textStyle: {
                        fontSize: 12,
                        color: '#333'
                    }
                },
                series: [{
                    name: '设备故障类型',
                    type: 'pie',
                    radius: '70%',
                    center: ['35%', '50%'],
                    avoidLabelOverlap: false,
                    label: {
                        show: true,
                        position: 'outside',
                        formatter: '{b}: {c}',
                        fontSize: 12
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: '14',
                            fontWeight: 'bold'
                        }
                    },
                    labelLine: {
                        show: true
                    },
                    data: [
                        { value: 120, name: '紧急' },
                        { value: 80, name: '重要' },
                        { value: 60, name: '一般' }
                    ]
                }]
            };

            faultPieChart.setOption(faultPieOption);

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

            window.addEventListener('resize', handleFaultPieResize);

            return () => {
                window.removeEventListener('resize', handleFaultPieResize);
                if (faultPieChart && !faultPieChart.isDisposed()) {
                    faultPieChart.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: ['9:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00'],
                    axisLabel: {
                        fontSize: 10
                    }
                },
                yAxis: {
                    type: 'value',
                    min: 0,
                    max: 30,
                    axisLabel: {
                        formatter: '{value}',
                        fontSize: 10
                    }
                },
                series: [
                    {
                        name: '消防水泵1',
                        type: 'line',
                        smooth: false,
                        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: [12, 15, 18, 14, 16, 20, 22, 19, 17, 21, 23, 25]
                    },
                    {
                        name: '消防水泵2',
                        type: 'line',
                        smooth: false,
                        lineStyle: {
                            width: 2,
                            color: '#3CC3DF'
                        },
                        areaStyle: {
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [
                                    { offset: 0, color: 'rgba(60, 195, 223, 0.3)' },
                                    { offset: 1, color: 'rgba(60, 195, 223, 0.05)' }
                                ]
                            }
                        },
                        symbol: 'circle',
                        symbolSize: 4,
                        itemStyle: {
                            color: '#fff',
                            borderColor: '#3CC3DF',
                            borderWidth: 1
                        },
                        data: [8, 11, 14, 10, 13, 17, 19, 16, 14, 18, 20, 22]
                    }
                ]
            };

            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: 'drillId',
            key: 'drillId',
            width: 140,
        },
        {
            title: '演练时间',
            dataIndex: 'drillTime',
            key: 'drillTime',
            width: 180,
        },
        {
            title: '演练类型',
            dataIndex: 'drillType',
            key: 'drillType',
            width: 120,
        },
        {
            title: '关联部位',
            dataIndex: 'relatedPart',
            key: 'relatedPart',
            width: 120,
        },
        {
            title: '部位名称',
            dataIndex: 'partName',
            key: 'partName',
            width: 160,
        },
        {
            title: '演练次数',
            dataIndex: 'drillCount',
            key: 'drillCount',
            width: 100,
        },
        {
            title: '参与人数',
            dataIndex: 'participantCount',
            key: 'participantCount',
            width: 100,
        },
        {
            title: '效果评估',
            dataIndex: 'effect',
            key: 'effect',
            width: 120,
            render: (text) => {
                let color = '#FFF3E9', fontColor = '#FF8800', label = text;
                if (text === '优秀') {
                    color = '#D8F7DE';
                    fontColor = '#44BB5F';
                }
                return (
                    <span style={{
                        background: color,
                        color: fontColor,
                        borderRadius: 5,
                        padding: '3px 8px',
                        fontSize: 12,
                        fontWeight: 500
                    }}>{label}</span>
                );
            }
        },
        {
            title: '操作',
            key: 'action',
            width: 120,
            render: (_, record) => (
                <>
                    <span style={{ color: '#2E4CD4', cursor: 'pointer', marginRight: 16 }}>编辑</span>
                    <span style={{ color: '#FF2526', cursor: 'pointer' }}>删除</span>
                </>
            ),
        },
    ];

    // 表格数据（同步图片）
    const mockData = [
        {
            key: '1',
            drillId: 'YL202310001',
            drillTime: '2025-09-10 14:23:45',
            drillType: '实战演练',
            relatedPart: '三楼东侧',
            partName: '数据机房 A区',
            drillCount: 5,
            participantCount: 25,
            effect: '良好',
        },
        {
            key: '2',
            drillId: 'YL202310002',
            drillTime: '2025-09-10 14:23:45',
            drillType: '桌面推演',
            relatedPart: '二楼西侧',
            partName: 'B区厨房',
            drillCount: 6,
            participantCount: 18,
            effect: '良好',
        },
        {
            key: '3',
            drillId: 'YL202310003',
            drillTime: '2025-09-10 14:23:45',
            drillType: '模拟演练',
            relatedPart: '地下一层',
            partName: '数据中心机房',
            drillCount: 3,
            participantCount: 32,
            effect: '优秀',
        },
    ];

    // 初始化数据
    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,
        }));
    };

    // 重点部位卡片数据和选中状态
    const keypartsData = [
        {
            name: '配电房',
            location: '1楼 - 东区',
            risk: '高风险',
            riskColor: '#FFE0E2',
            riskTextColor: '#FF3E48',
        },
        {
            name: '消防控制室',
            location: '1楼 - 西区',
            risk: '中风险',
            riskColor: '#FFF8E2',
            riskTextColor: '#FFC403',
        },
        {
            name: '档案室',
            location: '2楼 - 中区',
            risk: '低风险',
            riskColor: '#DAF3FF',
            riskTextColor: '#00AAFA',
        }
    ];
    const [selectedKeypartIdx, setSelectedKeypartIdx] = useState(0);

    return (
        <div className={styles.Rcontainer}>
            {/* 第一个div - 高度20% */}
            <div className={styles.RcontainerTop}>
                <div className={styles.sectionContent}>
                    <div className={styles.blocksContainer}>
                        {/* 块1 */}
                        <div className={styles.blockItem + ' ' + styles.bgBlock1}>
                            <div className={styles.blockLeft}>
                                <div className={styles.blockTitle}>演练记录总数</div>
                                <div className={styles.blockNumber}>120</div>
                            </div>
                            <div className={styles.blockRight}>
                                <img src={eqicon1} alt="演练记录总数" className={styles.blockImage} />
                            </div>
                        </div>

                        {/* 块2 */}
                        <div className={styles.blockItem + ' ' + styles.bgBlock2}>
                            <div className={styles.blockLeft}>
                                <div className={styles.blockTitle}>重点部位数量</div>
                                <div className={styles.blockNumber}>32</div>
                            </div>
                            <div className={styles.blockRight}>
                                <img src={eqicon6} alt="重点部位数量" className={styles.blockImage} />
                            </div>
                        </div>

                        {/* 块3 */}
                        <div className={styles.blockItem + ' ' + styles.bgBlock3}>
                            <div className={styles.blockLeft}>
                                <div className={styles.blockTitle}>参与演练人员</div>
                                <div className={styles.blockNumber}>69</div>
                            </div>
                            <div className={styles.blockRight}>
                                <img src={eqicon7} alt="参与演练人员" className={styles.blockImage} />
                            </div>
                        </div>

                        {/* 块4 */}
                        <div className={styles.blockItem + ' ' + styles.bgBlock4}>
                            <div className={styles.blockLeft}>
                                <div className={styles.blockTitle}>平均演练达标率</div>
                                <div className={styles.blockNumber}>72%</div>
                            </div>
                            <div className={styles.blockRight}>
                                <img src={eqicon8} alt="平均演练达标率" className={styles.blockImage} />
                            </div>
                        </div>

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


            <div className={styles.RcontainerMiddle}>
                <div className={styles.sectionContent}>
                    <div className={styles.middleBlock2}>
                        <div className={styles.middleBlock2Title}>
                            <div className={styles.titleLeft}>
                                <div className={styles.titleIcon}></div>
                                <div>重点部位分布图</div>
                            </div>
                            <div className={styles.titleRight}>
                                实时定位
                            </div>
                        </div>
                        <div className={styles.middleBlock2Chart}>
                            {/* 地图图片 */}
                            <img
                                src={require('@/assets/business_firekeynotearea/map.png')}
                                alt="重点部位分布图"
                                style={{ width: '100%', height: '100%' }}
                            />
                        </div>
                    </div>
                    <div className={styles.middleBlock1}>
                        <div className={styles.block1Header}>
                            <div className={styles.block1Title}>
                                <div className={styles.titleIcon}></div>
                                重点部位类型分布
                            </div>
                            <Segmented
                                className={styles.block1Segmented}
                                options={['月', '季', '年']}
                                onChange={(value) => {
                                    console.log(value);
                                }}
                            />
                        </div>
                        {/* 设备状态饼图 */}
                        <div className={styles.deviceStatusChart} ref={pieChartRef}>
                        </div>

                    </div>

                    <div className={styles.middleBlock1}>
                        <div className={styles.block1Header}>
                            <div className={styles.block1Title}>
                                <div className={styles.titleIcon}></div>
                                重点部位列表
                            </div>
                            <div>共 3 项</div>
                        </div>
                        {/* 重点部位列表 */}
                        <div className={styles.keypartsList}>
                            {keypartsData.map((item, idx) => (
                                <div
                                    key={item.name}
                                    className={styles.keypartsCard + ' ' + (selectedKeypartIdx === idx ? styles.keypartsCardActive : '')}
                                    onClick={() => setSelectedKeypartIdx(idx)}
                                    style={{ cursor: 'pointer' }}
                                >
                                    <div>
                                        <div className={styles.keypartsCardHeader}>
                                            <span className={styles.keypartsCardTitle}>{item.name}</span>
                                        </div>
                                        <div className={styles.keypartsCardSub}>{item.location}</div>
                                    </div>
                                    <div
                                        className={styles.keypartsRiskTag}
                                        style={{ background: item.riskColor, color: item.riskTextColor }}
                                    >
                                        {item.risk}
                                    </div>
                                </div>
                            ))}
                        </div>

                    </div>

                </div>
            </div>

            {/* 第三个div - 占满剩余位置 */}
            <div className={styles.RcontainerBottom}>
                <div className={styles.sectionContent}>

                    <div className={styles.tableBlock}>
                        {/* 表格 */}
                        <div className={styles.tableHeader}>
                            <div className={styles.tableTitle}>
                                <div className={styles.titleIcon}></div>
                                <div>演练记录录入</div>
                            </div>

                            <div className={styles.tableActions}>
                                <div className={styles.searchInputWrap}>
                                    {/* 搜索输入框 */}
                                    <Input.Search
                                        className={styles.searchInput}
                                        style={{ width: 200 }}
                                        placeholder="搜索部位名称..."
                                        allowClear
                                    />
                                </div>
                                <div className={styles.searchBarWrap}>
                                    {/* 下拉选择 */}
                                    <Select
                                        className={styles.selectAll}
                                        defaultValue="所属类别"
                                        style={{ width: 100 }}
                                        options={[{ value: '所属类别', label: '所属类别' }]}
                                    />
                                    {/* 新增按钮 */}
                                    <Button className={styles.addBtn} type="primary">
                                        <PlusOutlined /> 新增演练记录
                                    </Button>
                                </div>
                            </div>
                        </div>

                        {/* 表格 */}
                        <div className={styles.tableContainer}>
                            <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 EmergencyDrillRecordAssociation; 