'use client'
import React, {useEffect, useRef, useState} from 'react';
import deom1 from "../assets/deom1.png";
import deom2 from "../assets/deom2.png";
import Uptow from "../assets/up-two.png";
import markerData from "../assets/markerData.json";
import fameng from "../assets/fameng.png";
import shuifa from "../assets/shuifa.png";
import dataJson from "../assets/index.json";
import "../assets/BaiduMapPage.css";

import {Badge, Card, Col, Modal, Row,} from "antd"

// 添加图标导入
import {CheckCircleOutlined, CloseCircleOutlined, ExclamationCircleOutlined, WifiOutlined} from '@ant-design/icons';
import RTMMPicEcharts from "@/components/realTimeMontorModule/RTMMPicEcharts";
import RTMMBarChart from "@/components/realTimeMontorModule/RTMMBarchart";
// ... 其余代码保持不变 ...

// 仅在浏览器环境中声明 window 类型
declare global {
    interface Window {
        BMapGL: any;
        initMap: () => void;
    }
}

function GisMapBaidu(props: { height: string }) {
    const mapRef = useRef<HTMLDivElement>(null);
    const [map, setMap] = useState<any>(null);
    const [isClient, setIsClient] = useState(false);

    // 设备列表状态
    const [popupFrameVisible, setPopupFrameVisible] = useState(false);
    const [manholeCoverData, setManholeCoverData] = useState<any>(null);

    // 标记是否在浏览器环境
    useEffect(() => {
        setIsClient(true);
    }, []);

    // 初始化地图
    useEffect(() => {
        if (!isClient || !mapRef.current) return;

        // 检查是否已加载百度地图 GL JS API
        if (!window.BMapGL) {
            // 动态加载百度地图 GL JS API
            const script = document.createElement('script');
            script.src = `https://api.map.baidu.com/api?v=2.0&ak=jWDCUpsk33htQsF6IEwk4ctkERTOFFH0&type=webgl`;
            script.async = true;
            script.onload = () => {
                initializeMap();
            };
            document.head.appendChild(script);
        } else {
            initializeMap();
        }

        return () => {
            // 清理工作
            if (map && map.destroy) {
                map.destroy();
            }
        };
    }, [isClient]);

    const initializeMap = () => {
        if (!window.BMapGL || !mapRef.current) return;

        // 创建地图实例
        const mapInstance = new window.BMapGL.Map(mapRef.current);
        // 设置中心点坐标
        const point = new window.BMapGL.Point(110.39573035064166, 28.44628067667752);
        mapInstance.centerAndZoom(point, 16);
        // 启用滚轮放大缩小
        mapInstance.enableScrollWheelZoom(true);
        // 设置初始倾斜角度为30度（范围：0-45度）
        mapInstance.setTilt(45);

        // 添加控件
        mapInstance.setMinZoom(16);
        mapInstance.setMaxZoom(19);
        mapInstance.setMapStyleV2({
            styleId: '62ce43ad2a1362c23e612b783d7406e7'
        });

        // 添加标记点
        if (markerData?.list?.dataOne) {
            markerData.list.dataOne.forEach((item: any) => {
                const icon = new window.BMapGL.Icon(fameng.src, new window.BMapGL.Size(23, 25), {
                    anchor: new window.BMapGL.Size(10, 25),
                });
                const markers = new window.BMapGL.Point(item.lng, item.lat);
                const marker = new window.BMapGL.Marker(markers, {icon});
                mapInstance.addOverlay(marker);

                // 创建信息窗口
                const opts = {
                    width: 300,
                    title: item.name
                };
                const infoWindow = new window.BMapGL.InfoWindow(
                    "倾斜角度：188deg<br/>" +
                    "状态：正常运行<br/>" +
                    "信噪比：16db<br/>" +
                    "负责人：张三<br/>" +
                    "联系方式：121234564", opts
                );

                marker.addEventListener('click', () => {
                    mapInstance.openInfoWindow(infoWindow, markers);
                    console.log('点击了标记点', item);
                    // 添加显示弹窗的逻辑
                    setManholeCoverData(item);
                    setPopupFrameVisible(true);
                });
            });
        }

        if (markerData?.list?.dataTwo) {
            markerData.list.dataTwo.forEach((item: any) => {
                const icon = new window.BMapGL.Icon(shuifa.src, new window.BMapGL.Size(23, 25), {
                    anchor: new window.BMapGL.Size(20, 0),
                });
                const markers = new window.BMapGL.Point(item.lng, item.lat);
                const marker = new window.BMapGL.Marker(markers, {icon});
                mapInstance.addOverlay(marker);

                // 创建信息窗口
                const opts = {
                    width: 300,
                    title: item.name
                };
                // const infoWindow = new window.BMapGL.InfoWindow(
                //     "倾斜角度：188deg<br/>" +
                //     "状态：正常运行<br/>" +
                //     "信噪比：16db<br/>" +
                //     "负责人：张三<br/>" +
                //     "联系方式：121234564", opts
                // );


                marker.addEventListener('click', () => {
                    // mapInstance.openInfoWindow(infoWindow, markers);
                    setManholeCoverData({
                        ...item,
                        neme:item.name,
                        itemCode:'12312442222',
                        type: '供水井盖',
                        state:'1',
                        worker:'东三社区',
                        miaoshu:'检测到倾斜角度异常',
                        time:'2023-08-01 10:00:00',

                        temperature:'25',//温度
                        humidity:'50',//湿度
                        flow:'100',//流量
                        flowSpeed:'2',//流速
                        waterLevel:'100',//水位
                        waterQuality:'100',//水质
                        PHValue:'7.0',//PH值
                        rongjieyang:'100',//融结氧
                        ammoniaNitrogen:'100',//氨氮
                    });
                    // 添加显示弹窗的逻辑
                    setPopupFrameVisible(true);
                });
            });
        }

        // 添加线路图层
        if (window.BMapGL.LineLayer && dataJson) {
            const lineLayer = new window.BMapGL.LineLayer({
                enablePicked: true,
                autoSelect: true,
                pickWidth: 30,
                pickHeight: 30,
                opacity: 1,
                selectedColor: 'blue',
                style: {
                    sequence: false,
                    marginLength: 18,
                    borderMask: true,
                    strokeWeight: 10,
                    strokeLineJoin: 'round',
                    strokeLineCap: 'round',
                    strokeTextureUrl: ['match', ['get', 'name'], 'demo1', deom1.src, 'demo2', deom2.src, Uptow.src],
                }
            });

            lineLayer.setData(dataJson);
            mapInstance.addNormalLayer(lineLayer);
        }

        setMap(mapInstance);

        // 添加点击地图事件
        mapInstance.addEventListener('click', (e: any) => {
            console.log('点击位置经纬度:', e.latlng?.lng, e.latlng?.lat);
        });
    };

    if (!isClient) {
        return (
            <div className="flex items-center justify-center h-full bg-gray-100">
                <div className="text-gray-500">地图加载中...</div>
            </div>
        );
    }

    // 合并return语句，修复Modal无法显示的问题
    return (
        <>
            <div className="flex flex-col font-sans" style={{ height: props.height + "vh" }}>
                <div className="flex flex-1 overflow-hidden statisticsBox">
                    {/* 添加左侧三个板块区域 */}
                    <div style={{ width: '380px', overflow: 'auto' }}>
                        {/* 板块1 */}
                        <Card title="状态监测统计（15天）" style={{ marginBottom: '10px',
                            backgroundColor: '#b9d8ff85'}}>
                            <div style={{ textAlign: 'center',height: '200px' }}>
                                <RTMMPicEcharts
                                    // title="告警类型统计"
                                    data={[
                                        {value: 335, name: '位移告警'},
                                        {value: 310, name: '倾斜告警'},
                                        {value: 234, name: '水位告警'},
                                        {value: 135, name: '电压告警'},
                                        {value: 1548, name: '温度告警'}
                                    ]}
                                    style={{height: '100%', width: '100%'}}
                                />
                            </div>
                        </Card>

                        {/* 板块2 */}
                        <Card title="设备状态" style={{ marginBottom: '16px', backgroundColor: '#b9d8ff85' }}>
                            <div>
                                {/* 修改为2行2列的四宫格布局 */}
                                <Row gutter={[16, 16]}>
                                    {/* 正常运行状态卡片 */}
                                    <Col span={12}>
                                        <div style={{
                                            display: 'flex',
                                            alignItems: 'center',
                                            padding: '12px',
                                            backgroundColor: 'rgba(255, 255, 255, 0.7)',
                                            borderRadius: '8px'
                                        }}>
                                            {/* 左侧图标 */}
                                            <div style={{
                                                width: '40px',
                                                height: '40px',
                                                backgroundColor: '#f0f9eb',
                                                borderRadius: '50%',
                                                display: 'flex',
                                                alignItems: 'center',
                                                justifyContent: 'center',
                                                marginRight: '12px'
                                            }}>
                                                <CheckCircleOutlined style={{ fontSize: '24px', color: '#52c41a' }} />
                                            </div>

                                            {/* 右侧文字和数值 */}
                                            <div>
                                                <div style={{ color: '#333' }}>正常运行</div>
                                                <div style={{ fontSize: '20px', fontWeight: 'bold', color: '#52c41a' }}>12</div>
                                            </div>
                                        </div>
                                    </Col>

                                    {/* 需要注意状态卡片 */}
                                    <Col span={12}>
                                        <div style={{
                                            display: 'flex',
                                            alignItems: 'center',
                                            padding: '12px',
                                            backgroundColor: 'rgba(255, 255, 255, 0.7)',
                                            borderRadius: '8px'
                                        }}>
                                            <div style={{
                                                width: '40px',
                                                height: '40px',
                                                backgroundColor: '#fffbe6',
                                                borderRadius: '50%',
                                                display: 'flex',
                                                alignItems: 'center',
                                                justifyContent: 'center',
                                                marginRight: '12px'
                                            }}>
                                                <ExclamationCircleOutlined style={{ fontSize: '24px', color: '#faad14' }} />
                                            </div>
                                            <div>
                                                <div style={{ color: '#333' }}>需要注意</div>
                                                <div style={{ fontSize: '20px', fontWeight: 'bold', color: '#faad14' }}>3</div>
                                            </div>
                                        </div>
                                    </Col>

                                    {/* 异常状态卡片 */}
                                    <Col span={12}>
                                        <div style={{
                                            display: 'flex',
                                            alignItems: 'center',
                                            padding: '12px',
                                            backgroundColor: 'rgba(255, 255, 255, 0.7)',
                                            borderRadius: '8px'
                                        }}>
                                            <div style={{
                                                width: '40px',
                                                height: '40px',
                                                backgroundColor: '#fff2f0',
                                                borderRadius: '50%',
                                                display: 'flex',
                                                alignItems: 'center',
                                                justifyContent: 'center',
                                                marginRight: '12px'
                                            }}>
                                                <CloseCircleOutlined style={{ fontSize: '24px', color: '#f5222d' }} />
                                            </div>
                                            <div>
                                                <div style={{ color: '#333' }}>异常状态</div>
                                                <div style={{ fontSize: '20px', fontWeight: 'bold', color: '#f5222d' }}>1</div>
                                            </div>
                                        </div>
                                    </Col>

                                    {/* 离线类型卡片 */}
                                    <Col span={12}>
                                        <div style={{
                                            display: 'flex',
                                            alignItems: 'center',
                                            padding: '12px',
                                            backgroundColor: 'rgba(255, 255, 255, 0.7)',
                                            borderRadius: '8px'
                                        }}>
                                            <div style={{
                                                width: '40px',
                                                height: '40px',
                                                backgroundColor: '#f5f5f5',
                                                borderRadius: '50%',
                                                display: 'flex',
                                                alignItems: 'center',
                                                justifyContent: 'center',
                                                marginRight: '12px'
                                            }}>
                                                <WifiOutlined style={{ fontSize: '24px', color: '#999999' }} />
                                            </div>
                                            <div>
                                                <div style={{ color: '#333' }}>离线类型</div>
                                                <div style={{ fontSize: '20px', fontWeight: 'bold', color: '#999999' }}>2</div>
                                            </div>
                                        </div>
                                    </Col>
                                </Row>
                            </div>
                        </Card>

                        {/* 板块3 */}
                        <Card title="分类监测态势" style={{ marginBottom: '16px', backgroundColor: '#b9d8ff85' }}>

                            <div style={{ height:'170px'}}>
                                <RTMMBarChart
                                    data={[
                                        {value: 120, name: '电用井盖'},
                                        {value: 85, name: '供水井盖'},
                                        {value: 60, name: '通信井盖'},
                                        {value: 45, name: '燃气井盖'},
                                        {value: 30, name: '污水井盖'},
                                        {value: 30, name: '雨水井盖'},
                                        {value: 30, name: '路灯井盖'},
                                        {value: 30, name: '网络井盖'},
                                        {value: 30, name: '电缆井盖'},
                                        {value: 30, name: '园林井盖'},
                                        {value: 30, name: '化粪池井盖'}
                                    ]}
                                    style={{height: '100%', width: '100%'}}
                                />
                            </div>
                        </Card>
                    </div>

                    {/* 地图容器区域 */}
                    <div ref={mapRef} className="flex-1 h-full"></div>
                </div>
            </div>


            <Modal
                title="GIS设备详情"
                open={popupFrameVisible}
                onCancel={() => setPopupFrameVisible(false)}
                width={800}
                className="custom-modal"
                // 添加mask={false}移除遮罩层
                mask={false}
                // 定位样式保持不变
                style={{
                    position: 'absolute',
                    right: 0,
                    top: 150,
                    textAlign: 'center',
                }}
            >
                {manholeCoverData && (
                    <div className="space-y-4" style={{ display: 'flex', justifyContent: 'space-between' }}>
                        <div style={{ width: '50%' }}>
                            <div className="space-y-4" style={{ textAlign: 'left' }}>
                                <Row gutter={16}>
                                    <Col span={12}>
                                        <div>
                                            <strong style={{ color: '#B0E0E6' }}>设备名称:</strong> {manholeCoverData.name}
                                        </div>
                                    </Col>
                                </Row>
                                <Row gutter={16}>
                                    <Col span={12}>
                                        <div>
                                            <strong style={{ color: '#B0E0E6' }}>设备编号:</strong> {manholeCoverData.itemCode}
                                        </div>
                                    </Col>
                                </Row>
                                <Row gutter={16}>
                                    <Col span={12}>
                                        <div>
                                            <strong style={{ color: '#B0E0E6' }}>设备类型:</strong> {manholeCoverData.type}
                                        </div>
                                    </Col>
                                </Row>
                                <Row gutter={16}>
                                    <Col span={12}>
                                        <div>
                                            <strong style={{ color: '#B0E0E6' }}>状态:</strong>
                                            <Badge
                                                style={{
                                                    marginLeft: '10px'
                                                }}
                                                status={manholeCoverData.state === "1" ? "success" : "error"}
                                                text={
                                                    <span style={{
                                                        color: manholeCoverData.state === "1" ? "#52c41a" : "#f5222d"
                                                    }}>
                                                        {manholeCoverData.state === "1" ? "正常" : "异常"}
                                                    </span>
                                                }
                                            />
                                        </div>
                                    </Col>
                                </Row>
                                <Row gutter={16}>
                                    <Col span={12}>
                                        <div>
                                            <strong style={{ color: '#B0E0E6' }}>权属单位:</strong> {manholeCoverData.worker}
                                        </div>
                                    </Col>
                                </Row>
                                <Row gutter={16}>
                                    <Col span={15}>
                                        <div>
                                            <strong style={{ color: '#B0E0E6' }}>监测描述:</strong> {manholeCoverData.miaoshu}
                                        </div>
                                    </Col>
                                </Row>
                                <div style={{ color: '#B0E0E6', fontWeight:'bold',fontSize:'20px'}}>窑井下监测信息</div>

                                <Row gutter={16}>
                                    <Col span={12}>
                                        <div>
                                            <strong style={{ color: '#B0E0E6' }}>温度:</strong> {manholeCoverData.temperature}
                                        </div>
                                    </Col>
                                    <Col span={12}>
                                        <div>
                                            <strong style={{ color: '#B0E0E6' }}>湿度:</strong> {manholeCoverData.humidity}
                                        </div>
                                    </Col>
                                </Row>
                                <Row gutter={16}>
                                    <Col span={12}>
                                        <div>
                                            <strong style={{ color: '#B0E0E6' }}>流量:</strong> {manholeCoverData.flow}
                                        </div>
                                    </Col>
                                    <Col span={12}>
                                        <div>
                                            <strong style={{ color: '#B0E0E6' }}>水位:</strong> {manholeCoverData.waterLevel}
                                        </div>
                                    </Col>
                                </Row>
                                <Row gutter={16}>
                                    <Col span={12}>
                                        <div>
                                            <strong style={{ color: '#B0E0E6' }}>流速:</strong> {manholeCoverData.flowSpeed}
                                        </div>
                                    </Col>
                                    <Col span={12}>
                                        <div>
                                            <strong style={{ color: '#B0E0E6' }}>水质:</strong> {manholeCoverData.waterQuality}
                                        </div>
                                    </Col>
                                </Row>
                                <Row gutter={16}>
                                    <Col span={12}>
                                        <div>
                                            <strong style={{ color: '#B0E0E6' }}>PH值:</strong> {manholeCoverData.PHValue}
                                        </div>
                                    </Col>
                                    <Col span={12}>
                                        <div>
                                            <strong style={{ color: '#B0E0E6' }}>氨氮:</strong> {manholeCoverData.ammoniaNitrogen}
                                        </div>
                                    </Col>
                                </Row>
                            </div>
                        </div>
                        <div style={{width: '50%'}}>2</div>
                    </div>
                )}
            </Modal>

            {/* 添加全局样式覆盖表头背景色 */}
            <style jsx global>{`
                 /* 修改Modal背景色和添加渐变边框 */
                .custom-modal .ant-modal-content {
                    background-color: rgba(58, 56, 153, 1) !important; /* 主背景色 */
                    color: white; /* 文字颜色 */
                    /* 添加由外向内的径向渐变边框 */
                    border: 2px solid transparent;
                    border-radius: 8px;
                    background-clip: padding-box, border-box;
                    background-origin: padding-box, border-box;
                    background-image: 
                        linear-gradient( rgba(58, 56, 153, 1),  rgba(58, 56, 153, 1)), /* 背景色 */
                        radial-gradient(circle at center, #ff6b6b, #4ecdc4); /* 由外向内的径向渐变边框 */
                }
                /* 可选：修改Modal标题栏样式 */
                .custom-modal .ant-modal-header {
                    background-color:  rgba(58, 56, 153, 1) !important;
                    border-bottom: none; /* 移除底部边框 */
                }
                
                .custom-modal .ant-modal-title{
                    color:white !important;
                    border-bottom:1px solid white;
                }
                
                .statisticsBox .ant-card .ant-card-head{
                    background-color:  rgba(58, 56, 153, 1) !important;
                    min-height: 40px !important;
                    color:white;
                    padding:0px 12px !important;
                }
                
                .statisticsBox .ant-card .ant-card-body {
                    padding:12px !important;
                }
            `}</style>
        </>
    );
}

export default GisMapBaidu;
