import React, { useState, useEffect } from 'react';
import { Input, Button, Select, message, Modal, Tag } from 'antd';
import { SearchOutlined, PlusOutlined } from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';
import StandardTable from '@/components/StandardTable';
import styles from './DutyLog.less';

const { Option } = Select;

const DutyLog = () => {
    const [loading, setLoading] = useState(false);
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [searchValue, setSearchValue] = useState('');
    const [eventType, setEventType] = useState('');
    const [eventStatus, setEventStatus] = useState('');
    const [pagination, setPagination] = useState({
        current: 3,
        pageSize: 5,
        total: 48,
        showSizeChanger: false,
        showQuickJumper: true,
        showTotal: (total) => `共${total}条`,
    });

    // 模拟数据
    const [dataSource, setDataSource] = useState([
        {
            key: '1',
            time: '2025-10-19 15:35:27',
            location: '义宾南区16号楼',
            eventType: '交通事故',
            description: '主干道发生交通事故,造成交通拥堵',
            status: '已解决',
        },
        {
            key: '2',
            time: '2025-10-15 13:44:41',
            location: '中山南大街甲1号楼-1-5号附近',
            eventType: '自然灾害',
            description: '强风导致广告牌松动,存在安全隐患',
            status: '待处理',
        },
        {
            key: '3',
            time: '2025-10-15 00:29:03',
            location: '西辛南区66号(卧龙环岛东南角)',
            eventType: '社会安全',
            description: '商场内发生顾客纠纷,可能引发冲突',
            status: '已解决',
        },
        {
            key: '4',
            time: '2025-10-14 17:21:38',
            location: '怡馨家园5号楼',
            eventType: '自然灾害',
            description: '强风导致广告牌松动,存在安全隐患',
            status: '已解决',
        },
        {
            key: '5',
            time: '2025-10-15 02:30:41',
            location: '站前南街',
            eventType: '社会安全',
            description: '商场内发生顾客纠纷,可能引发冲突',
            status: '已解决',
        },
    ]);

    // 最近值班日志数据
    const recentLogs = [
        {
            title: '设备故障报告',
            time: '2023-04-17 14:45',
            location: '3号机房',
            description: '服务器温度异常升高,已启动备用设备..',
            status: '预警',
        },
        {
            title: '网络中断处理',
            time: '2023-04-17 14:45',
            location: '3号机房',
            description: '主办公楼网络中断,已联系维修人员处理..',
            status: '紧急',
        },
        {
            title: '日常巡检记录',
            time: '2023-04-17 14:45',
            location: '83号机房',
            description: '完成日常安全巡检,所有设备运行正常...',
            status: '常规',
        },
    ];

    const [chartReady, setChartReady] = useState(false);

    // 确保DOM准备好后再渲染图表
    useEffect(() => {
        const timer = setTimeout(() => {
            setChartReady(true);
        }, 100);
        return () => clearTimeout(timer);
    }, []);

    // 事件类型分布数据（根据图片描述调整颜色）
    const eventTypeData = [
        { name: '交通事故', value: 10, color: '#4A90E2' }, // 浅蓝色
        { name: '自然灾害', value: 15, color: '#52C41A' }, // 绿色
        { name: '社会安全', value: 8, color: '#FAAD14' }, // 黄色
        { name: '电力故障', value: 5, color: '#FF7A45' }, // 橙色
        { name: '火灾隐患', value: 3, color: '#F5222D' }, // 红色
        { name: '设施故障', value: 7, color: '#1890FF' }, // 深蓝色
    ];

    // ECharts 玫瑰图配置（空心饼图）
    const roseChartOption = {
        tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
        },
        legend: {
            show: false
        },
        series: [
            {
                type: 'pie',
                radius: ['40%', '70%'], // 空心饼图：内半径40%，外半径70%
                center: ['50%', '50%'],
                roseType: 'area', // 玫瑰图类型：使用面积表示数值
                avoidLabelOverlap: false,
                itemStyle: {
                    borderRadius: 4,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: false
                },
                labelLine: {
                    show: false
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: 14,
                        fontWeight: 'bold'
                    },
                    scale: true,
                    scaleSize: 5
                },
                data: eventTypeData.map(item => ({
                    value: item.value,
                    name: item.name,
                    itemStyle: {
                        color: item.color
                    }
                }))
            }
        ]
    };

    // 表格列配置
    const columns = [
        {
            title: '时间',
            dataIndex: 'time',
            key: 'time',
            width: 180,
        },
        {
            title: '地点',
            dataIndex: 'location',
            key: 'location',
            width: 200,
        },
        {
            title: '事件类型',
            dataIndex: 'eventType',
            key: 'eventType',
            width: 120,
        },
        {
            title: '事件描述',
            dataIndex: 'description',
            key: 'description',
            ellipsis: true,
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width: 100,
            render: (status) => {
                const colorMap = {
                    '已解决': 'success',
                    '待处理': 'warning',
                    '已处理': 'processing',
                };
                return <Tag color={colorMap[status] || 'default'}>{status}</Tag>;
            },
        },
        {
            title: '操作',
            key: 'action',
            width: 150,
            render: (text, record) => (
                <div className={styles.actionButtons}>
                    <Button 
                        type="link" 
                        size="small" 
                        onClick={() => handleView(record)}
                        style={{ color: '#1890FF', padding: 0 }}
                    >
                        查看
                    </Button>
                    <Button 
                        type="link" 
                        size="small" 
                        danger
                        onClick={() => handleDelete(record)}
                        style={{ padding: 0 }}
                    >
                        删除
                    </Button>
                </div>
            ),
        },
    ];

    // 搜索处理
    const handleSearch = () => {
        setLoading(true);
        setTimeout(() => {
            setLoading(false);
            message.success('查询完成');
        }, 1000);
    };

    // 新增处理
    const handleAdd = () => {
        message.info('新增日志功能待实现');
    };

    // 查看处理
    const handleView = (record) => {
        message.info(`查看日志详情：${record.description}`);
    };

    // 删除处理
    const handleDelete = (record) => {
        Modal.confirm({
            title: '确认删除',
            content: `确定要删除该条日志记录吗？`,
            onOk() {
                setDataSource(dataSource.filter(item => item.key !== record.key));
                message.success('删除成功');
            },
        });
    };

    // 分页处理
    const handleTableChange = (pagination) => {
        setPagination(pagination);
    };

    // 渲染状态标签
    const renderStatusTag = (status) => {
        const statusConfig = {
            '预警': { color: '#FF7A45', bg: '#FFF7E6' },
            '紧急': { color: '#F5222D', bg: '#FFF1F0' },
            '常规': { color: '#1890FF', bg: '#E6F7FF' },
        };
        const config = statusConfig[status] || { color: '#666', bg: '#F5F5F5' };
        return (
            <span 
                className={styles.statusTag}
                style={{ 
                    color: config.color, 
                    backgroundColor: config.bg,
                    borderColor: config.color
                }}
            >
                {status}
            </span>
        );
    };

    // 渲染玫瑰图（使用 ECharts）
    const renderRoseChart = () => {
        return (
            <div className={styles.pieChartContainer}>
                {chartReady && (
                    <ReactECharts
                        option={roseChartOption}
                        style={{ height: '100%', width: '100%' }}
                        opts={{ renderer: 'canvas' }}
                    />
                )}
                <div className={styles.pieLegend}>
                    {eventTypeData.map((item, index) => (
                        <div key={index} className={styles.legendItem}>
                            <span 
                                className={styles.legendColor} 
                                style={{ backgroundColor: item.color }}
                            />
                            <span className={styles.legendText}>{item.name}</span>
                        </div>
                    ))}
                </div>
            </div>
        );
    };

    return (
        <div className={styles.containerDutyLog}>
            {/* A块：顶部统计卡片 */}
            <div className={styles.blockA}>
                
                <div className={styles.statCard}>
                    <div className={styles.statIcon}>
                        <div className={styles.cubeIcon}></div>
                    </div>
                    <div className={styles.statContent}>
                        <div className={styles.statNumber}>24</div>
                        <div className={styles.statLabel}>今日日志总数</div>
                    </div>
                </div>
                <div className={styles.statCard}>
                    <div className={styles.statIcon}>
                        <div className={styles.warningIcon}></div>
                    </div>
                    <div className={styles.statContent}>
                        <div className={styles.statNumber}>5</div>
                        <div className={styles.statLabel}>紧急事件</div>
                    </div>
                </div>
                <div className={styles.statCard}>
                    <div className={styles.statIcon}>
                        <div className={styles.successIcon}></div>
                    </div>
                    <div className={styles.statContent}>
                        <div className={styles.statNumber}>16</div>
                        <div className={styles.statLabel}>已处理事件</div>
                    </div>
                </div>
                <div className={styles.statCard}>
                    <div className={styles.statIcon}>
                        <div className={styles.clockIcon}></div>
                    </div>
                    <div className={styles.statContent}>
                        <div className={styles.statNumber}>5</div>
                        <div className={styles.statLabel}>待处理事件</div>
                    </div>
                </div>
            </div>

            {/* B块：主要内容区域 */}
            <div className={styles.blockB}>
                {/* 左块 */}
                <div className={styles.blockBLeft}>
                    {/* 上部分：事件类型分布 */}
                    <div className={styles.leftTop}>
                        <div className={styles.sectionTitle}>事件类型分布</div>
                        <div className={styles.chartWrapper}>
                            {renderRoseChart()}
                        </div>
                    </div>
                    {/* 下部分：最近值班日志 */}
                    <div className={styles.leftBottom}>
                        <div className={styles.sectionTitle}>最近值班日志</div>
                        <div className={styles.recentLogsList}>
                            {recentLogs.map((log, index) => (
                                <div key={index} className={styles.logCard}>
                                    <div className={styles.logTitle}>{log.title}</div>
                                    <div className={styles.logInfo}>
                                        <span>{log.time}</span>
                                        <span className={styles.logLocation}>{log.location}</span>
                                    </div>
                                    <div className={styles.logDescription}>{log.description}</div>
                                    <div className={styles.logFooter}>
                                        {renderStatusTag(log.status)}
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                </div>

                {/* 右块：值班日志列表 */}
                <div className={styles.blockBRight}>
                    <div className={styles.sectionTitle}>值班日志列表</div>
                    {/* 搜索和操作区域 */}
                    <div className={styles.searchBar}>
                        <Input
                            placeholder="请输入关键字..."
                            prefix={<SearchOutlined />}
                            className={styles.searchInput}
                            style={{ borderRadius: '2px' }}
                        />
                        <Select
                            placeholder="所有类型"
                            value={eventType}
                            onChange={setEventType}
                            allowClear
                            className={styles.filterSelect}
                            style={{ borderRadius: '2px' }}
                        >
                            <Option value="交通事故">交通事故</Option>
                            <Option value="自然灾害">自然灾害</Option>
                            <Option value="社会安全">社会安全</Option>
                            <Option value="电力故障">电力故障</Option>
                            <Option value="火灾隐患">火灾隐患</Option>
                            <Option value="设施故障">设施故障</Option>
                        </Select>
                        <Select
                            placeholder="所有状态"
                            value={eventStatus}
                            onChange={setEventStatus}
                            allowClear
                            className={styles.filterSelect}
                            style={{ borderRadius: '2px' }}
                        >
                            <Option value="已解决">已解决</Option>
                            <Option value="待处理">待处理</Option>
                            <Option value="已处理">已处理</Option>
                        </Select>
                        <Button 
                            type="primary" 
                            icon={<PlusOutlined />}
                            onClick={handleAdd}
                            className={styles.addButton}
                            style={{ borderRadius: '2px' }}
                        >
                            新增日志
                        </Button>
                    </div>
                    {/* 数据表格 */}
                    <div className={styles.tableContainer}>
                        <StandardTable
                            columns={columns}
                            data={{
                                list: dataSource,
                                pagination: pagination
                            }}
                            rowKey="key"
                            selectedRows={selectedRowKeys}
                            onSelectRow={setSelectedRowKeys}
                            onChange={handleTableChange}
                            loading={loading}
                        />
                    </div>
                </div>
            </div>
        </div>
    );
};

export default DutyLog;
