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 './EmergencyPlanAssociation.less';
import eqicon1 from '@/assets/business_firekeynotearea/eqicon1.png';
import ksdyIcon from '@/assets/business_firekeynotearea/ksdy.svg';
import deleteIcon from '@/assets/business_firekeynotearea/delete.svg';
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 EmergencyPlanAssociation = () => {
    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 = {
                legend: {
                    data: [{
                        name: '调用次数',
                        icon: 'rect',
                        itemStyle: {
                            color: '#4B69F1'
                        }
                    }],
                    top: 0,
                    left: 'center',
                    itemWidth: 12,
                    itemHeight: 3,
                    textStyle: {
                        fontSize: 12,
                        color: '#333'
                    },
                },
                grid: {
                    left: '3%',
                    right: '3%',
                    bottom: '3%',
                    top: 30,
                    containLabel: true,
                },
                xAxis: {
                    type: 'category',
                    data: ['电气火灾', '防水防潮', '人员疏散', '燃气泄漏', '油锅起火'],
                    axisLabel: {
                        fontSize: 12,
                        color: '#666666',
                        margin: 12,
                    },
                    axisLine: {
                        lineStyle: {
                            color: 'rgba(0, 0, 26, 0.15)',
                            type: 'solid', // 改为实线
                        },
                    },
                    axisTick: {
                        show: false
                    }
                },
                yAxis: {
                    type: 'value',
                    min: 0,
                    max: 25,
                    splitNumber: 5,
                    axisLabel: {
                        fontSize: 12,
                        color: '#666666',
                    },
                    axisLine: {
                        show: false,
                    },
                    splitLine: {
                        lineStyle: {
                            color: 'rgba(0, 0, 26, 0.15)',
                            type: 'dashed',
                        },
                    },
                },
                series: [
                    {
                        name: '调用次数',
                        type: 'bar',
                        barWidth: 32,
                        data: [16, 22, 16, 16, 8],
                        itemStyle: {
                            // borderRadius: [4, 4, 0, 0],
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [
                                    { offset: 0, color: '#199BFB' },
                                    { offset: 1, color: '#1373FA' },
                                ],
                            },
                        },
                    },
                ],
            };
            chart.setOption(option);
            // 响应式调整
            const handleResize = () => {
                if (chart && !chart.isDisposed()) {
                    chart.resize();
                }
            };
            window.addEventListener('resize', handleResize);
            return () => {
                window.removeEventListener('resize', handleResize);
                if (chart && !chart.isDisposed()) {
                    chart.dispose();
                }
            };
        }
    }, []);

    // 表格列定义（同步图片）
    const columns = [
        {
            title: '编号',
            dataIndex: 'bh',
            key: 'bh',
            width: 140,
        },
        {
            title: '部位名称',
            dataIndex: 'bwmc',
            key: 'bwmc',
            width: 180,
        },
        {
            title: '部位类型',
            dataIndex: 'bwlx',
            key: 'bwlx',
            width: 120,
        },
        {
            title: '关联预案数',
            dataIndex: 'glyans',
            key: 'glyans',
            width: 120,
        },
        {
            title: '最近更新',
            dataIndex: 'zjgx',
            key: 'zjgx',
            width: 160,
        },
        {
            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: '#44BB5F', cursor: 'pointer' }}>关联</span>
                </>
            ),
        },
    ];

    // 表格数据（同步图片）
    const mockData = [
        {
            key: '1',
            bh: '01',
            bwmc: '数据机房A区',
            bwlx: '数据机房',
            glyans: 5,
            zjgx: '2025-09-10 14:23:45',
            effect: '有更新',
        },
        {
            key: '2',
            bh: '02',
            bwmc: 'B区厨房',
            bwlx: '厨房区域',
            glyans: 3,
            zjgx: '2025-09-10 14:23:45',
            effect: '有更新',
        },
        {
            key: '3',
            bh: '03',
            bwmc: '数据中心机房',
            bwlx: '配电房',
            glyans: 4,
            zjgx: '2025-09-10 14:23:45',
            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.topBlock}>
                        <div className={styles.topBlockTitle}>
                            <div className={styles.titleLeft}>
                                <div className={styles.titleIcon}></div>
                                <div>应急预案关联管理功能组成图</div>
                            </div>
                        </div>
                        <div className={styles.topBlockBg}>
                            <img
                                src={require('@/assets/business_firekeynotearea/relation-group.png')}
                                alt="应急预案关联管理功能组成图"
                                style={{ width: '50%' }}
                            />
                        </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>
                        <div className={styles.middleBlock2Chart} ref={chartRef}></div>
                    </div>
                    <div className={styles.middleBlock1}>
                        <div className={styles.block1Header}>
                            <div className={styles.block1Title}>
                                <div className={styles.titleIcon}></div>
                                关联应急预案
                            </div>
                        </div>
                        {/* 关联应急预案列表 */}
                        <div className={styles.planListWrap}>
                            {[
                                {
                                    title: '电气火灾应急预案',
                                    desc: '适用场景: 电气短路、设备过载引发的火灾',
                                    update: '2023-05-07',
                                    user: '张正',
                                },
                                {
                                    title: '精密设备防水防潮应急预案',
                                    desc: '适用场景: 电气短路、设备过载引发的火灾',
                                    update: '2023-05-07',
                                    user: '张正',
                                },
                                {
                                    title: '精密设备防水防潮应急预案',
                                    desc: '适用场景: 电气短路、设备过载引发的火灾',
                                    update: '2023-05-07',
                                    user: '张正',
                                }
                            ].map((item, idx) => (
                                <div className={styles.planCard} key={item.title}>
                                    <div style={{ flex: 1 }}>
                                        <div className={styles.planCardTitle}>{item.title}</div>
                                        <div className={styles.planCardDesc}>{item.desc}</div>
                                        <div className={styles.planCardUpdate}>上次修订：{item.update} | 修订人：{item.user}</div>
                                    </div>
                                    <div className={styles.planCardFooter}>
                                        <div className={styles.planCardBtns}>
                                            <Button className={styles.quickBtn} type="primary" size="small">
                                                <img src={ksdyIcon} alt="快速调用" style={{ width: 12, height: 12, marginRight: 4, verticalAlign: 'middle' }} />
                                                快速调用
                                            </Button>
                                            <Button className={styles.delBtn} type="danger" size="small">
                                                <img src={deleteIcon} alt="删除" style={{ width: 12, height: 12, marginRight: 4, verticalAlign: 'middle' }} />
                                                删除
                                            </Button>
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </div>

                    </div>
                    <div className={styles.middleBlock1}>
                        <div className={styles.block1Header}>
                            <div className={styles.block1Title}>
                                <div className={styles.titleIcon}></div>
                                预案更新通知
                            </div>
                        </div>
                        {/* 预案更新通知列表 */}
                        <div className={styles.planListWrap}>
                            {[
                                {
                                    title: '电气火灾应急预案已更新',
                                    desc: '该预案已修订，涉及数据机房A区等3个重点部位需要同步更新',
                                    time: '10分钟',
                                },
                                {
                                    title: '仓库物品堆放安全管理预案已发布',
                                    desc: '新预案适用于各类仓库区域，建议进行关联',
                                    time: '20分钟',
                                },
                                {
                                    title: '防汛应急预案年度修订提醒',
                                    desc: '距离防汛应急预案下次修订时间还有30天',
                                    time: '40分钟',
                                }
                            ].map((item, idx) => (
                                <div className={styles.planCard} key={item.title}>
                                    <div style={{ flex: 1 }}>
                                        <div className={styles.planCardTitle}>{item.title}</div>
                                        <div className={styles.planCardUpdate}>{item.desc}</div>
                                    </div>
                                    <div className={styles.planCardFooter}>
                                        <div style={{color: '#FF2526', fontSize: 12}}>
                                            {item.time}
                                        </div>
                                    </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 EmergencyPlanAssociation;