"use client"

import React, {useEffect, useMemo, useState} from "react"
import type {MenuProps, TableColumnsType} from "antd"
import {
  Badge,
  Button,
  Card,
  Col,
  ConfigProvider,
  DatePicker,
  Descriptions,
  Divider,
  Drawer,
  Empty,
  Layout,
  Menu,
  Progress,
  Row,
  Segmented,
  Select,
  Space,
  Statistic,
  Switch,
  Table,
  Tabs,
  Tag,
  Timeline,
  Tooltip as AntdTooltip,
} from "antd"
import {
  Activity,
  AlertTriangle,
  BellRing,
  ClipboardList,
  Database,
  Droplets,
  Factory,
  Flame,
  Gauge,
  Layers3,
  LineChartIcon,
  Moon,
  Settings2,
  ShieldCheck,
  Sun,
  Table2,
  TrendingUp,
  Users,
  Waves
} from 'lucide-react'
import EChart from "@/components/echarts"
import dayjs from "dayjs"
import "dayjs/locale/zh-cn"
import zhCN from "antd/es/locale/zh_CN"
import 'leaflet/dist/leaflet.css'
import GisMapBaidu from "@/components/gisMapBaidu";

// 动态导入Leaflet，只在客户端渲染
const L = typeof window !== 'undefined' ? require('leaflet') : null

// 修复Leaflet默认图标问题（仅在客户端）
const fixLeafletIcons = () => {
  if (typeof window !== 'undefined' && L) {
    delete (L.Icon.Default.prototype as any)._getIconUrl;
    L.Icon.Default.mergeOptions({
      iconRetinaUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-icon-2x.png',
      iconUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-icon.png',
      shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-shadow.png',
    });
  }
};

fixLeafletIcons();

dayjs.locale("zh-cn")

const { Header, Sider, Content } = Layout
const { RangePicker } = DatePicker

// Helpers
const primary = "#10b981" // teal, avoid blue
const danger = "#ef4444"
const warn = "#f59e0b"
const ok = "#22c55e"
const muted = "#6b7280"

type Facility = {
  id: string
  industry: "燃气" | "供水" | "排水"
  type: string
  count: number
  age: number
  region: string
}

type Device = {
  id: string
  type: string
  status: "在线" | "离线"
  industry: Facility["industry"]
  risk: "高" | "中" | "低"
  lat: number
  lng: number
}

type Alert = {
  id: string
  level: "I级" | "II级" | "III级" | "IV级"
  industry: Facility["industry"]
  type: string
  time: string
  status: "待处置" | "处置中" | "已闭环"
  location: string
  desc: string
}

function useMockData() {
  const [facilities] = useState<Facility[]>(() => {
    const regions = ["中心城区", "东区", "西区", "南区", "北区"]
    const types = {
      燃气: ["高压管道", "调压站", "门站", "阀门井"],
      供水: ["原水管", "净水厂", "二次供水", "监测点"],
      排水: ["主干管", "泵站", "检查井", "溢流口"],
    } as const
    let i = 0
    return (["燃气", "供水", "排水"] as Facility["industry"][]).flatMap((ind) =>
      types[ind].map((t) => ({
        id: `f-${i++}`,
        industry: ind,
        type: t,
        count: Math.floor(Math.random() * 900 + 100),
        age: Math.floor(Math.random() * 30 + 1),
        region: regions[Math.floor(Math.random() * regions.length)],
      }))
    )
  })

  const [devices, setDevices] = useState<Device[]>(() => {
    const types = ["压力", "流量", "液位", "阀位", "水质", "气体浓度"]
    let i = 0
    return Array.from({ length: 250 }).map(() => ({
      id: `d-${i++}`,
      type: types[Math.floor(Math.random() * types.length)],
      status: Math.random() > 0.12 ? "在线" : "离线",
      industry: (["燃气", "供水", "排水"] as const)[Math.floor(Math.random() * 3)],
      risk: Math.random() > 0.8 ? "高" : Math.random() > 0.5 ? "中" : "低",
      lat: Math.random(),
      lng: Math.random(),
    }))
  })

  // Simulate device status fluctuation
  useEffect(() => {
    const t = setInterval(() => {
      setDevices((prev) =>
        prev.map((d) =>
          Math.random() > 0.97 ? { ...d, status: d.status === "在线" ? "离线" : "在线" } : d
        )
      )
    }, 4000)
    return () => clearInterval(t)
  }, [])

  const [alerts, setAlerts] = useState<Alert[]>(() => {
    const levels: Alert["level"][] = ["I级", "II级", "III级", "IV级"]
    const types = ["泄漏", "压力异常", "流量突变", "停电", "液位过低", "浊度异常"]
    let i = 0
    return Array.from({ length: 30 }).map(() => ({
      id: `a-${i++}`,
      level: levels[Math.floor(Math.random() * levels.length)],
      industry: (["燃气", "供水", "排水"] as const)[Math.floor(Math.random() * 3)],
      type: types[Math.floor(Math.random() * types.length)],
      time: dayjs().subtract(Math.floor(Math.random() * 200), "minute").format("YYYY-MM-DD HH:mm"),
      status: Math.random() > 0.6 ? "已闭环" : Math.random() > 0.3 ? "处置中" : "待处置",
      location: ["中心城区", "东区", "西区", "南区", "北区"][Math.floor(Math.random() * 5)],
      desc: "自动监测发现异常，已推送至管理单位核实。",
    }))
  })

  // Simulate new alerts
  useEffect(() => {
    const t = setInterval(() => {
      setAlerts((prev) => {
        const n: Alert = {
          id: `a-${prev.length + 1}`,
          level: Math.random() > 0.85 ? "I级" : Math.random() > 0.6 ? "II级" : Math.random() > 0.3 ? "III级" : "IV级",
          industry: (["燃气", "供水", "排水"] as const)[Math.floor(Math.random() * 3)],
          type: ["泄漏", "压力异常", "流量突变", "停电", "液位过低", "浊度异常"][Math.floor(Math.random() * 6)],
          time: dayjs().format("YYYY-MM-DD HH:mm"),
          status: "待处置",
          location: ["中心城区", "东区", "西区", "南区", "北区"][Math.floor(Math.random() * 5)],
          desc: "前端设备上报新预警，请尽快核查。",
        }
        return [n, ...prev].slice(0, 60)
      })
    }, 20000)
    return () => clearInterval(t)
  }, [])

  return { facilities, devices, alerts }
}

function LevelTag({ level }: { level: Alert["level"] }) {
  const map = {
    "I级": { color: danger },
    "II级": { color: warn },
    "III级": { color: "#f97316" },
    "IV级": { color: ok },
  } as const
  return <Tag color={map[level].color}>{level}</Tag>
}

function StatusBadge({ s }: { s: Alert["status"] }) {
  const status = {
    待处置: "error",
    处置中: "processing",
    已闭环: "success",
  } as const
  // @ts-expect-error antd types for Badge status
  return <Badge status={status[s]} text={s} />
}

export default function Page() {
  const [collapsed, setCollapsed] = useState(false)
  const { facilities, devices, alerts } = useMockData()
  const [selectedMenu, setSelectedMenu] = useState("overview")
  const [drawerOpen, setDrawerOpen] = useState(false)
  const [selectedAlert, setSelectedAlert] = useState<Alert | null>(null)
  const [isDark, setIsDark] = useState(false) // 默认白色主题
  const [assetTab, setAssetTab] = useState("archive")
  const [monitorTab, setMonitorTab] = useState("summary")
  const [alertTab, setAlertTab] = useState("current")

  const totals = useMemo(() => {
    const sum = { 燃气: 0, 供水: 0, 排水: 0 } as Record<Facility["industry"], number>
    facilities.forEach((f) => (sum[f.industry] += f.count))
    return sum
  }, [facilities])

  const onlineRate = useMemo(() => {
    const total = devices.length
    const online = devices.filter((d) => d.status === "在线").length
    return Math.round((online / Math.max(total, 1)) * 100)
  }, [devices])

  const riskDist = useMemo(() => {
    const dist = { 高: 0, 中: 0, 低: 0 } as Record<Device["risk"], number>
    devices.forEach((d) => (dist[d.risk] += 1))
    return dist
  }, [devices])

  // Menu
  const menuItems: MenuProps["items"] = [
    { key: "overview", icon: <Layers3 size={18} />, label: "总体概览" },
    { key: "asset", icon: <Database size={18} />, label: "基础设施管理" },
    { key: "monitor", icon: <Activity size={18} />, label: "运行监测管理" },
    { key: "alert", icon: <BellRing size={18} />, label: "预警处置管理" },
    { type: "divider" as const },
    { key: "devices", icon: <Gauge size={18} />, label: "设备管理" },
    { key: "reports", icon: <ClipboardList size={18} />, label: "数据报表" },
    { key: "incidents", icon: <Users size={18} />, label: "事件中心" },
    { key: "bigscreen", icon: <LineChartIcon size={18} />, label: "数据大屏（示意）" },
    { type: "divider" as const },
    { key: "settings", icon: <Settings2 size={18} />, label: "设置" },
  ]

  // Charts Options
  const infraPieOption = useMemo(
    () => ({
      title: { text: "设施类型占比", left: "center", textStyle: { fontSize: 14 } },
      tooltip: { trigger: "item" },
      legend: { bottom: 0 },
      color: [primary, "#f59e0b", "#6366f1", "#ef4444", "#14b8a6", "#a855f7"],
      series: [
        {
          type: "pie",
          radius: ["35%", "60%"],
          avoidLabelOverlap: false,
          itemStyle: { borderRadius: 6, borderColor: "#fff", borderWidth: 2 },
          data: ["燃气", "供水", "排水"].map((ind) => ({
            name: ind,
            value: facilities
              .filter((f) => f.industry === ind)
              .reduce((acc, f) => acc + f.count, 0),
          })),
        },
      ],
    }),
    [facilities]
  )

  const deviceBarOption = useMemo(() => {
    const types = Array.from(new Set(devices.map((d) => d.type)))
    const byType = types.map((t) => devices.filter((d) => d.type === t).length)
    return {
      title: { text: "监测设备类型规模", left: "center", textStyle: { fontSize: 14 } },
      tooltip: { trigger: "axis" },
      xAxis: { type: "category", data: types, axisLabel: { rotate: 20 } },
      yAxis: { type: "value" },
      grid: { left: 40, right: 10, bottom: 50, top: 40 },
      color: [primary],
      series: [{ type: "bar", data: byType, barWidth: "50%", itemStyle: { borderRadius: [4, 4, 0, 0] } }],
    } as const
  }, [devices])

  const alertTrendOption = useMemo(() => {
    const days = 14
    const labels = Array.from({ length: days }).map((_, i) => dayjs().subtract(days - i - 1, "day").format("MM-DD"))
    const series = (["燃气", "供水", "排水"] as const).map((ind, idx) => ({
      name: ind,
      type: "line",
      smooth: true,
      data: labels.map(() => Math.floor(Math.random() * (idx === 0 ? 12 : idx === 1 ? 9 : 7)) + (idx === 0 ? 3 : 1)),
    }))
    return {
      title: { text: "预警趋势（近14天）", left: "center", textStyle: { fontSize: 14 } },
      tooltip: { trigger: "axis" },
      legend: { bottom: 0 },
      grid: { left: 40, right: 10, bottom: 40, top: 40 },
      xAxis: { type: "category", data: labels },
      yAxis: { type: "value" },
      color: [primary, "#f59e0b", "#a855f7"],
      series,
    } as const
  }, [])

  const onlineGaugeOption = useMemo(
    () => ({
      title: { text: "设备在线率", left: "center", top: 10, textStyle: { fontSize: 14 } },
      series: [
        {
          type: "gauge",
          startAngle: 200,
          endAngle: -20,
          radius: "90%",
          pointer: { show: false },
          progress: { show: true, width: 16, itemStyle: { color: onlineRate > 95 ? ok : onlineRate > 85 ? "#84cc16" : warn } },
          axisLine: { lineStyle: { width: 16 } },
          axisTick: { show: false },
          splitLine: { show: false },
          axisLabel: { show: false },
          detail: { valueAnimation: true, formatter: "{value}%", fontSize: 22, offsetCenter: [0, "10%"] },
          data: [{ value: onlineRate }],
        },
      ],
    }),
    [onlineRate]
  )

  const riskBarOption = useMemo(
    () => ({
      title: { text: "风险等级分布", left: "center", textStyle: { fontSize: 14 } },
      tooltip: { trigger: "axis" },
      grid: { left: 40, right: 10, top: 40, bottom: 20 },
      xAxis: { type: "category", data: ["高", "中", "低"] },
      yAxis: { type: "value" },
      color: [danger, warn, ok],
      series: [{ type: "bar", data: [riskDist["高"], riskDist["中"], riskDist["低"]], barWidth: "50%" }],
    }),
    [riskDist]
  )

  const efficiencyPieOption = useMemo(() => {
    const closed = alerts.filter((a) => a.status === "已闭环").length
    const correct = Math.floor(closed * (0.85 + Math.random() * 0.1)) // 假定人工复核正确率
    const wrong = Math.max(closed - correct, 0)
    return {
      title: { text: "预警正确性（闭环内）", left: "center", textStyle: { fontSize: 14 } },
      tooltip: { trigger: "item", formatter: "{b}: {c} ({d}%)" },
      legend: { bottom: 0 },
      color: [ok, danger],
      series: [
        {
          type: "pie",
          radius: ["35%", "60%"],
          data: [
            { name: "正确预警", value: correct },
            { name: "误报", value: wrong },
          ],
        },
      ],
    } as const
  }, [alerts])

  const radarCapacityOption = useMemo(
    () => ({
      title: { text: "应急保障能力雷达", left: "center", textStyle: { fontSize: 14 } },
      tooltip: {},
      radar: {
        indicator: [
          { name: "抢修速度", max: 100 },
          { name: "物资充足", max: 100 },
          { name: "跨部门联动", max: 100 },
          { name: "覆盖广度", max: 100 },
          { name: "应急演练", max: 100 },
        ],
      },
      color: [primary],
      series: [
        {
          type: "radar",
          data: [{ value: [78, 85, 72, 88, 76], name: "当前" }],
          areaStyle: { color: primary + "33" },
        },
      ],
    }),
    []
  )

  // Tables
  const facilityColumns: TableColumnsType<Facility> = [
    { title: "行业", dataIndex: "industry", key: "industry", width: 90 },
    { title: "类型", dataIndex: "type", key: "type" },
    { title: "数量", dataIndex: "count", key: "count", width: 100 },
    { title: "平均年限", dataIndex: "age", key: "age", width: 120, render: (v) => `${v} 年` },
    { title: "分布区域", dataIndex: "region", key: "region", width: 120 },
  ]

  const alertColumns: TableColumnsType<Alert> = [
    { title: "等级", dataIndex: "level", key: "level", width: 90, render: (v) => <LevelTag level={v} /> },
    { title: "行业", dataIndex: "industry", key: "industry", width: 90 },
    { title: "类型", dataIndex: "type", key: "type", width: 140 },
    { title: "时间", dataIndex: "time", key: "time", width: 160 },
    { title: "状态", dataIndex: "status", key: "status", width: 120, render: (s) => <StatusBadge s={s} /> },
    { title: "位置", dataIndex: "location", key: "location", width: 120 },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="small">
          <a
            onClick={() => {
              setSelectedAlert(record)
              setDrawerOpen(true)
            }}
          >
            查看
          </a>
          <a>派单</a>
          <a>联动</a>
        </Space>
      ),
      width: 160,
      fixed: "right",
    },
  ]

  const deviceColumns: TableColumnsType<Device> = [
    { title: "行业", dataIndex: "industry", key: "industry", width: 90 },
    { title: "类型", dataIndex: "type", key: "type", width: 100 },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      width: 100,
      render: (s) => <Badge status={s === "在线" ? "success" : "default"} text={s} />,
      filters: [
        { text: "在线", value: "在线" },
        { text: "离线", value: "离线" },
      ],
      onFilter: (v, r) => r.status === v,
    },
    {
      title: "风险",
      dataIndex: "risk",
      key: "risk",
      width: 100,
      render: (r) => <Tag color={r === "高" ? danger : r === "中" ? warn : ok}>{r}</Tag>,
      filters: [
        { text: "高", value: "高" },
        { text: "中", value: "中" },
        { text: "低", value: "低" },
      ],
      onFilter: (v, r) => r.risk === v,
    },
    { title: "编号", dataIndex: "id", key: "id" },
  ]

  const alertLevelColor = (lvl: Alert["level"]) =>
    lvl === "I级" ? danger : lvl === "II级" ? warn : lvl === "III级" ? "#f97316" : ok

  // Derived numbers
  const stats = [
    {
      title: "燃气总规模",
      value: totals["燃气"],
      icon: <Flame className="text-white" size={18} />,
      bg: "bg-emerald-500",
    },
    {
      title: "供水总规模",
      value: totals["供水"],
      icon: <Droplets className="text-white" size={18} />,
      bg: "bg-teal-500",
    },
    {
      title: "排水总规模",
      value: totals["排水"],
      icon: <Waves className="text-white" size={18} />,
      bg: "bg-cyan-500",
    },
    {
      title: "在线设备",
      value: devices.filter((d) => d.status === "在线").length,
      icon: <Gauge className="text-white" size={18} />,
      bg: "bg-lime-500",
    },
  ]

  // Map markers for device distribution
  const markers = devices.slice(0, 120).map((d) => ({
    id: d.id,
    top: `${Math.floor(d.lat * 85) + 5}%`,
    left: `${Math.floor(d.lng * 90) + 5}%`,
    color: d.risk === "高" ? danger : d.risk === "中" ? warn : ok,
    title: `${d.industry}/${d.type}（${d.status}）`,
  }))

  const themeTokens = useMemo(
    () => ({
      token: {
        colorPrimary: primary,
        colorInfo: primary,
        borderRadius: 8,
        fontSize: 13,
      },
      components: {
        Layout: {
          headerBg: isDark ? "#0f172a" : "#ffffff",
          siderBg: isDark ? "#0b1220" : "#ffffff",
          bodyBg: isDark ? "#0b1220" : "#f6f7f9",
        },
        Menu: {
          itemSelectedBg: isDark ? "#0ea5a8" : "#d1fae5",
          itemSelectedColor: isDark ? "#fff" : "#0f172a",
          itemActiveBg: "#0ea5a822",
        },
      },
    }),
    [isDark]
  )


  return (
    <ConfigProvider locale={zhCN} theme={themeTokens}>
      <Layout style={{ minHeight: "100vh" }}>
        <Sider collapsible collapsed={collapsed} onCollapse={setCollapsed} width={240} theme={isDark ? "dark" : "light"}>
          <div className="flex items-center gap-2 px-4 py-3">
            <ShieldCheck className="text-emerald-400" size={22} />
            {!collapsed && (
              <div className={isDark ? "text-emerald-100 font-medium" : "text-emerald-700 font-medium"}>
                城市生命线驾驶舱
              </div>
            )}
          </div>
          <Menu
            theme={isDark ? "dark" : "light"}
            mode="inline"
            selectedKeys={[selectedMenu]}
            onClick={(e) => setSelectedMenu(e.key)}
            items={menuItems}
          />
        </Sider>
        <Layout>
          <Header className="flex items-center justify-between px-4">
            <div className={`flex items-center gap-3 ${isDark ? "text-white" : "text-slate-800"}`}>
              <Factory size={18} />
              <span className="font-medium">综合运行态势</span>
              <span className={`text-xs hidden md:inline ${isDark ? "text-slate-300" : "text-slate-500"}`}>
                更新时间 {dayjs().format("YYYY-MM-DD HH:mm:ss")}
              </span>
            </div>
            <div className="flex items-center gap-3">
              <Select
                size="small"
                defaultValue="全市"
                options={[
                  { value: "全市", label: "全市" },
                  { value: "中心城区", label: "中心城区" },
                  { value: "东区", label: "东区" },
                  { value: "西区", label: "西区" },
                  { value: "南区", label: "南区" },
                  { value: "北区", label: "北区" },
                ]}
                style={{ width: 120 }}
              />
              <RangePicker size="small" />
              <Button size="small" onClick={() => setIsDark((v) => !v)} icon={isDark ? <Sun size={14} /> : <Moon size={14} />}>
                {isDark ? "暗色" : "白色"}
              </Button>
            </div>
          </Header>
          <Content className="p-4 md:p-6">
            {selectedMenu === "overview" && (
              <section className="space-y-4">
                <Row gutter={[16, 16]}>
                  {stats.map((s) => (
                    <Col xs={24} sm={12} md={12} lg={6} key={s.title}>
                      <Card>
                        <div className="flex items-center gap-3">
                          <div className={`w-9 h-9 rounded-md flex items-center justify-center ${s.bg}`}>{s.icon}</div>
                          <div className="flex-1">
                            <div className="text-xs text-slate-500">{s.title}</div>
                            <div className="text-xl font-semibold">{s.value.toLocaleString()}</div>
                          </div>
                          <AntdTooltip title="环比增长">
                            <TrendingUp className="text-emerald-500" size={18} />
                          </AntdTooltip>
                        </div>
                      </Card>
                    </Col>
                  ))}
                </Row>

                <Row gutter={[16, 16]}>
                  <Col xs={24} md={12} lg={8}>
                    <Card>
                      <EChart option={infraPieOption} />
                    </Card>
                  </Col>
                  <Col xs={24} md={12} lg={8}>
                    <Card>
                      <EChart option={deviceBarOption} />
                    </Card>
                  </Col>
                  <Col xs={24} md={24} lg={8}>
                    <Card>
                      <EChart option={onlineGaugeOption} />
                    </Card>
                  </Col>
                </Row>

                <Row gutter={[16, 16]}>
                  <Col xs={24} md={12}>
                    <Card>
                      <EChart option={alertTrendOption} />
                    </Card>
                  </Col>
                  <Col xs={24} md={12}>
                    <Card>
                      <EChart option={riskBarOption} />
                    </Card>
                  </Col>
                </Row>

                <Card title="监测分布（示意）" extra={<span className="text-xs text-slate-500">标注颜色代表风险等级</span>}>
                  <GisMapBaidu height={'50'}/>
                </Card>
              </section>
            )}

            {selectedMenu === "asset" && (
              <section className="space-y-4">
                <Tabs
                  activeKey={assetTab}
                  onChange={setAssetTab}
                  items={[
                    { key: "archive", label: "基础档案" },
                    { key: "run", label: "运行信息" },
                    { key: "mgmt", label: "管理信息" },
                    { key: "emergency", label: "应急保障" },
                  ]}
                />

                {assetTab === "archive" && (
                  <>
                    <Row gutter={[16, 16]}>
                      <Col xs={24} lg={14}>
                        <Card title="设施基础档案">
                          <Table
                            size="small"
                            rowKey="id"
                            columns={facilityColumns}
                            dataSource={facilities}
                            pagination={{ pageSize: 8 }}
                            scroll={{ x: 700 }}
                          />
                        </Card>
                      </Col>
                      <Col xs={24} lg={10}>
                        <Card title="行业重点指标">
                          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div>
                              <div className="text-xs text-slate-500 mb-1">平均设施年限</div>
                              <Statistic value={Math.round(facilities.reduce((a, b) => a + b.age, 0) / facilities.length)} suffix="年" />
                              <Progress percent={Math.min(100, Math.round((facilities.filter((f) => f.age >= 20).length / facilities.length) * 100))} size="small" />
                              <div className="text-xs text-slate-500 mt-1">20年以上占比</div>
                            </div>
                            <div>
                              <div className="text-xs text-slate-500 mb-1">重点设施数量</div>
                              <Statistic value={facilities.filter((f) => f.type.includes("主") || f.type.includes("厂")).reduce((a, b) => a + b.count, 0)} />
                              <div className="text-xs text-slate-500 mt-1">主干/厂站等关键设施总量</div>
                            </div>
                          </div>
                        </Card>
                        <Card className="mt-4" title="分布热点（示意）">
                          <EChart
                            option={{
                              title: { text: "区域设施数量", left: "center", textStyle: { fontSize: 14 } },
                              xAxis: { type: "category", data: ["中心城区", "东区", "西区", "南区", "北区"] },
                              yAxis: { type: "value" },
                              grid: { left: 40, right: 10, bottom: 20, top: 40 },
                              color: [primary],
                              series: [
                                {
                                  type: "bar",
                                  data: ["中心城区", "东区", "西区", "南区", "北区"].map(
                                    (r) => facilities.filter((f) => f.region === r).reduce((a, b) => a + b.count, 0)
                                  ),
                                  barWidth: "50%",
                                },
                              ],
                            }}
                          />
                        </Card>
                      </Col>
                    </Row>
                  </>
                )}

                {assetTab === "run" && (
                  <>
                    <Row gutter={[16, 16]}>
                      <Col xs={24} md={12}>
                        <Card title="日常供应能力（示意）">
                          <EChart
                            option={{
                              tooltip: { trigger: "axis" },
                              legend: { bottom: 0 },
                              grid: { left: 40, right: 10, top: 20, bottom: 40 },
                              xAxis: { type: "category", data: Array.from({ length: 24 }).map((_, i) => `${i}:00`) },
                              yAxis: { type: "value" },
                              color: [primary, "#f59e0b"],
                              series: [
                                { name: "供水(万m³/h)", type: "line", smooth: true, data: Array.from({ length: 24 }).map(() => 50 + Math.random() * 20) },
                                { name: "燃气(万m³/h)", type: "line", smooth: true, data: Array.from({ length: 24 }).map(() => 30 + Math.random() * 15) },
                              ],
                            }}
                          />
                        </Card>
                      </Col>
                      <Col xs={24} md={12}>
                        <Card title="承载能力（示意）">
                          <EChart
                            option={{
                              tooltip: { trigger: "axis" },
                              grid: { left: 40, right: 10, top: 20, bottom: 40 },
                              xAxis: { type: "category", data: ["中心", "东", "西", "南", "北"] },
                              yAxis: { type: "value" },
                              color: [primary],
                              series: [{ type: "bar", data: [92, 86, 74, 80, 77] }],
                            }}
                          />
                        </Card>
                      </Col>
                    </Row>
                  </>
                )}

                {assetTab === "mgmt" && (
                  <>
                    <Row gutter={[16, 16]}>
                      <Col xs={24} md={12}>
                        <Card title="管理单位信息">
                          <Descriptions size="small" column={1} bordered>
                            <Descriptions.Item label="燃气管理单位">市燃气集团、区属燃气公司等（共 6 家）</Descriptions.Item>
                            <Descriptions.Item label="供水管理单位">市自来水公司、二供物业等（共 9 家）</Descriptions.Item>
                            <Descriptions.Item label="排水管理单位">城排中心、各区运营公司（共 7 家）</Descriptions.Item>
                            <Descriptions.Item label="产权分布">市属 60%，区属 30%，社会 10%</Descriptions.Item>
                          </Descriptions>
                          <Divider className="my-3" />
                          <Timeline
                            items={[
                              { color: "green", children: "制度更新：设施巡检标准（本月）" },
                              { color: "blue", children: "完成年度普查 80%" },
                              { color: "orange", children: "外包维保单位进场（上周）" },
                            ]}
                          />
                        </Card>
                      </Col>
                      <Col xs={24} md={12}>
                        <Card title="产权分布">
                          <EChart
                            option={{
                              tooltip: { trigger: "item" },
                              legend: { bottom: 0 },
                              color: [primary, "#34d399", "#a7f3d0"],
                              series: [
                                { type: "pie", radius: ["35%", "60%"], data: [{ value: 60, name: "市属" }, { value: 30, name: "区属" }, { value: 10, name: "社会" }] },
                              ],
                            }}
                          />
                        </Card>
                      </Col>
                    </Row>
                  </>
                )}

                {assetTab === "emergency" && (
                  <>
                    <Row gutter={[16, 16]}>
                      <Col xs={24} md={12}>
                        <Card title="应急资源配置">
                          <div className="grid grid-cols-2 gap-4">
                            <Card size="small">
                              <div className="text-xs text-slate-500">物资仓库</div>
                              <div className="text-xl font-semibold mt-1">12 处</div>
                              <Progress percent={78} status="active" size="small" />
                              <div className="text-xs text-slate-500 mt-1">库存充足度</div>
                            </Card>
                            <Card size="small">
                              <div className="text-xs text-slate-500">抢修队伍</div>
                              <div className="text-xl font-semibold mt-1">26 支</div>
                              <Progress percent={86} status="active" size="small" />
                              <div className="text-xs text-slate-500 mt-1">到岗率</div>
                            </Card>
                            <Card size="small">
                              <div className="text-xs text-slate-500">重点防护目标</div>
                              <div className="text-xl font-semibold mt-1">143 处</div>
                              <Progress percent={92} status="active" size="small" />
                              <div className="text-xs text-slate-500 mt-1">纳入台账比例</div>
                            </Card>
                            <Card size="small">
                              <div className="text-xs text-slate-500">联动单位</div>
                              <div className="text-xl font-semibold mt-1">19 家</div>
                              <Progress percent={74} status="active" size="small" />
                              <div className="text-xs text-slate-500 mt-1">联动成熟度</div>
                            </Card>
                          </div>
                        </Card>
                      </Col>
                      <Col xs={24} md={12}>
                        <Card>
                          <EChart option={radarCapacityOption} />
                        </Card>
                      </Col>
                    </Row>
                  </>
                )}
              </section>
            )}

            {selectedMenu === "monitor" && (
              <section className="space-y-4">
                <Tabs
                  activeKey={monitorTab}
                  onChange={setMonitorTab}
                  items={[
                    { key: "summary", label: "监测概览" },
                    { key: "distribution", label: "监测分布" },
                    { key: "running", label: "运行概况" },
                  ]}
                />

                {monitorTab === "summary" && (
                  <>
                    <Row gutter={[16, 16]}>
                      <Col xs={24} md={12} lg={8}>
                        <Card>
                          <EChart option={onlineGaugeOption} />
                        </Card>
                      </Col>
                      <Col xs={24} md={12} lg={8}>
                        <Card>
                          <EChart option={deviceBarOption} />
                        </Card>
                      </Col>
                      <Col xs={24} md={24} lg={8}>
                        <Card>
                          <EChart option={riskBarOption} />
                        </Card>
                      </Col>
                    </Row>
                  </>
                )}

                {monitorTab === "distribution" && (
                  <>
                    <Card title="监测分布（按行业与风险）">
                      <Row gutter={[16, 16]}>
                        {(["燃气", "供水", "排水"] as const).map((ind) => (
                          <Col xs={24} md={8} key={ind}>
                            <Card size="small" title={ind}>
                              <div className="flex items-center gap-4">
                                <div className="flex-1">
                                  <div className="text-xs text-slate-500">设备在线</div>
                                  <div className="text-lg font-semibold">
                                    {devices.filter((d) => d.industry === ind && d.status === "在线").length}
                                  </div>
                                  <div className="text-xs text-slate-500">总量 {devices.filter((d) => d.industry === ind).length}</div>
                                </div>
                                <div className="flex-1">
                                  <div className="text-xs text-slate-500">高风险</div>
                                  <div className="text-lg font-semibold">
                                    {devices.filter((d) => d.industry === ind && d.risk === "高").length}
                                  </div>
                                  <Progress
                                    percent={Math.round(
                                      (devices.filter((d) => d.industry === ind && d.risk === "高").length /
                                        Math.max(devices.filter((d) => d.industry === ind).length, 1)) *
                                      100
                                    )}
                                    size="small"
                                  />
                                </div>
                              </div>
                            </Card>
                          </Col>
                        ))}
                      </Row>
                    </Card>

                    <Card title="（示意）">
                      <div className="relative w-full h-[380px] rounded-md overflow-hidden bg-slate-100">
                        <img
                          src="/images/city-map.png"
                          alt="城市简化地图"
                          className="absolute inset-0 w-full h-full object-cover opacity-90"
                        />
                        {markers.map((m) => (
                          <AntdTooltip key={m.id} title={m.title}>
                            <div
                              className="absolute w-2.5 h-2.5 rounded-full ring-2 ring-white/70"
                              style={{ top: m.top, left: m.left, backgroundColor: m.color }}
                            />
                          </AntdTooltip>
                        ))}
                      </div>
                    </Card>
                  </>
                )}

                {monitorTab === "running" && (
                  <>
                    <Card title="运行概况（报警覆盖）">
                      <EChart
                        option={{
                          tooltip: { trigger: "axis" },
                          legend: { bottom: 0 },
                          grid: { left: 40, right: 10, top: 20, bottom: 40 },
                          xAxis: { type: "category", data: Array.from({ length: 12 }).map((_, i) => dayjs().subtract(11 - i, "month").format("YYYY-MM")) },
                          yAxis: { type: "value" },
                          color: [primary, "#f59e0b", "#a855f7"],
                          series: (["燃气", "供水", "排水"] as const).map((ind, idx) => ({
                            name: ind,
                            type: "bar",
                            stack: "sum",
                            emphasis: { focus: "series" },
                            data: Array.from({ length: 12 }).map(() => Math.floor(Math.random() * (idx === 0 ? 50 : idx === 1 ? 40 : 30))),
                          })),
                        }}
                      />
                    </Card>
                    <Row gutter={[16, 16]} className="mt-1">
                      <Col xs={24} md={12}>
                        <Card>
                          <EChart option={alertTrendOption} />
                        </Card>
                      </Col>
                      <Col xs={24} md={12}>
                        <Card>
                          <EChart option={deviceBarOption} />
                        </Card>
                      </Col>
                    </Row>
                  </>
                )}
              </section>
            )}

            {selectedMenu === "alert" && (
              <section className="space-y-4">
                <Tabs
                  activeKey={alertTab}
                  onChange={setAlertTab}
                  items={[
                    { key: "current", label: "当前预警" },
                    { key: "history", label: "历史分析" },
                    { key: "efficiency", label: "预警效率" },
                    { key: "analysis", label: "预警分析" },
                  ]}
                />

                {alertTab === "current" && (
                  <>
                    <Row gutter={[16, 16]}>
                      <Col xs={24} lg={16}>
                        <Card title="总体预警处置情况">
                          <Table
                            size="small"
                            rowKey="id"
                            columns={alertColumns}
                            dataSource={alerts}
                            pagination={{ pageSize: 8 }}
                            onRow={(record) => ({
                              onClick: () => {
                                setSelectedAlert(record)
                                setDrawerOpen(true)
                              },
                            })}
                            scroll={{ x: 900 }}
                          />
                        </Card>
                      </Col>
                      <Col xs={24} lg={8}>
                        <Card title="处置效率">
                          <div className="grid grid-cols-2 gap-4">
                            <div>
                              <div className="text-xs text-slate-500">平均处置时效</div>
                              <div className="text-xl font-semibold mt-1">{(45 + Math.random() * 30).toFixed(0)} 分钟</div>
                              <Progress percent={78} status="active" size="small" />
                              <div className="text-xs text-slate-500 mt-1">较上月 +6%</div>
                            </div>
                            <div>
                              <div className="text-xs text-slate-500">闭环率</div>
                              <div className="text-xl font-semibold mt-1">
                                {Math.round((alerts.filter((a) => a.status === "已闭环").length / Math.max(alerts.length, 1)) * 100)}%
                              </div>
                              <Progress percent={86} status="active" size="small" />
                              <div className="text-xs text-slate-500 mt-1">较上周 +2%</div>
                            </div>
                          </div>
                        </Card>
                        <Card className="mt-4">
                          <EChart option={efficiencyPieOption} />
                        </Card>
                      </Col>
                    </Row>

                    <Drawer
                      title={
                        <div className="flex items-center gap-2">
                          <AlertTriangle size={18} color={selectedAlert ? alertLevelColor(selectedAlert.level) : primary} />
                          <span>预警详情</span>
                        </div>
                      }
                      placement="right"
                      width={520}
                      open={drawerOpen}
                      onClose={() => setDrawerOpen(false)}
                    >
                      {selectedAlert ? (
                        <div className="space-y-4">
                          <Descriptions size="small" column={1} bordered>
                            <Descriptions.Item label="预警编号">{selectedAlert.id}</Descriptions.Item>
                            <Descriptions.Item label="等级">
                              <LevelTag level={selectedAlert.level} />
                            </Descriptions.Item>
                            <Descriptions.Item label="行业">{selectedAlert.industry}</Descriptions.Item>
                            <Descriptions.Item label="类型">{selectedAlert.type}</Descriptions.Item>
                            <Descriptions.Item label="时间">{selectedAlert.time}</Descriptions.Item>
                            <Descriptions.Item label="位置">{selectedAlert.location}</Descriptions.Item>
                            <Descriptions.Item label="状态">
                              <StatusBadge s={selectedAlert.status} />
                            </Descriptions.Item>
                            <Descriptions.Item label="描述">{selectedAlert.desc}</Descriptions.Item>
                          </Descriptions>
                          <Card size="small" title="事件时序">
                            <EChart
                              option={{
                                grid: { left: 30, right: 10, top: 20, bottom: 20 },
                                xAxis: { type: "category", data: ["发现", "确认", "处置", "复盘"] },
                                yAxis: { type: "value" },
                                color: [primary],
                                series: [{ type: "line", smooth: true, data: [0, 12, 38, 60] }],
                              }}
                            />
                          </Card>
                          <Card size="small" title="一张图联动（示意）">
                            <div className="relative w-full h-[200px] rounded-md overflow-hidden">
                              <img src="/images/city-map.png" alt="地图联动示意图" className="absolute inset-0 w-full h-full object-cover opacity-90" />
                              <div className="absolute inset-0">
                                <div
                                  className="absolute w-3 h-3 rounded-full ring-2 ring-white animate-pulse"
                                  style={{ top: "42%", left: "56%", background: alertLevelColor(selectedAlert.level) }}
                                  title="预警位置"
                                />
                              </div>
                            </div>
                          </Card>
                          <Space>
                            <a className="text-emerald-600">查看工单</a>
                            <a className="text-emerald-600">下达指令</a>
                            <a className="text-emerald-600">通知联动</a>
                          </Space>
                        </div>
                      ) : (
                        <div className="text-slate-500 text-sm">请选择左侧预警查看详情。</div>
                      )}
                    </Drawer>
                  </>
                )}

                {alertTab === "history" && (
                  <>
                    <Row gutter={[16, 16]}>
                      <Col xs={24} md={12}>
                        <Card title="各行业预警数量（近6月）">
                          <EChart
                            option={{
                              tooltip: { trigger: "axis" },
                              legend: { bottom: 0 },
                              grid: { left: 40, right: 10, top: 20, bottom: 40 },
                              xAxis: { type: "category", data: Array.from({ length: 6 }).map((_, i) => dayjs().subtract(5 - i, "month").format("YYYY-MM")) },
                              yAxis: { type: "value" },
                              color: [primary, "#f59e0b", "#a855f7"],
                              series: (["燃气", "供水", "排水"] as const).map((ind, idx) => ({
                                name: ind,
                                type: "line",
                                smooth: true,
                                data: Array.from({ length: 6 }).map(() => Math.floor(Math.random() * (idx === 0 ? 60 : idx === 1 ? 45 : 35)) + 5),
                              })),
                            }}
                          />
                        </Card>
                      </Col>
                      <Col xs={24} md={12}>
                        <Card title="已闭环预警（示意）">
                          <Table
                            size="small"
                            rowKey="id"
                            columns={[
                              { title: "编号", dataIndex: "id" },
                              { title: "类型", dataIndex: "type" },
                              { title: "行业", dataIndex: "industry", width: 90 },
                              { title: "完成时间", dataIndex: "time", width: 160 },
                            ]}
                            dataSource={alerts.filter((a) => a.status === "已闭环")}
                            pagination={{ pageSize: 6 }}
                          />
                        </Card>
                      </Col>
                    </Row>
                  </>
                )}

                {alertTab === "efficiency" && (
                  <>
                    <Row gutter={[16, 16]}>
                      <Col xs={24} md={12}>
                        <Card title="整体效率">
                          <div className="grid grid-cols-2 gap-4">
                            <div>
                              <div className="text-xs text-slate-500">平均处置时效</div>
                              <div className="text-xl font-semibold mt-1">{(42 + Math.random() * 25).toFixed(0)} 分钟</div>
                              <Progress percent={82} status="active" size="small" />
                              <div className="text-xs text-slate-500 mt-1">较上月 +4%</div>
                            </div>
                            <div>
                              <div className="text-xs text-slate-500">正确预警率</div>
                              <div className="text-xl font-semibold mt-1">{(88 + Math.random() * 4).toFixed(1)}%</div>
                              <Progress percent={89} status="active" size="small" />
                              <div className="text-xs text-slate-500 mt-1">核实误报下降</div>
                            </div>
                          </div>
                        </Card>
                      </Col>
                      <Col xs={24} md={12}>
                        <Card>
                          <EChart option={efficiencyPieOption} />
                        </Card>
                      </Col>
                    </Row>
                  </>
                )}

                {alertTab === "analysis" && (
                  <>
                    <Row gutter={[16, 16]}>
                      <Col xs={24}>
                        <Card title="预警类型与成因分布">
                          <EChart
                            option={{
                              tooltip: { trigger: "axis" },
                              legend: { bottom: 0 },
                              grid: { left: 40, right: 10, top: 20, bottom: 40 },
                              xAxis: {
                                type: "category",
                                data: ["泄漏", "压力异常", "流量突变", "停电", "液位过低", "浊度异常"],
                                axisLabel: { rotate: 20 },
                              },
                              yAxis: { type: "value" },
                              color: [primary, "#f59e0b"],
                              series: [
                                { name: "设备原因", type: "bar", data: [30, 22, 18, 12, 9, 7] },
                                { name: "外部原因", type: "bar", data: [18, 15, 14, 28, 11, 10] },
                              ],
                            }}
                          />
                        </Card>
                      </Col>
                    </Row>
                  </>
                )}
              </section>
            )}

            {selectedMenu === "devices" && (
              <section className="space-y-4">
                <Row justify="space-between" align="middle">
                  <Col>
                    <div className="text-base font-medium">设备管理</div>
                  </Col>
                  <Col>
                    <Space>
                      <Segmented
                        options={["全部", "在线", "离线"]}
                        onChange={() => {}}
                        aria-label="设备状态筛选"
                      />
                      <Button size="small" icon={<Table2 size={14} />}>
                        批量导出
                      </Button>
                    </Space>
                  </Col>
                </Row>
                <Card>
                  <Table
                    size="small"
                    rowKey="id"
                    columns={deviceColumns}
                    dataSource={devices}
                    pagination={{ pageSize: 10 }}
                    scroll={{ x: 700 }}
                  />
                </Card>
              </section>
            )}

            {selectedMenu === "reports" && (
              <section className="space-y-4">
                <Row gutter={[16, 16]}>
                  <Col xs={24} md={12}>
                    <Card title="月度运行报告（示意）" extra={<Button size="small">导出 PDF</Button>}>
                      <EChart
                        option={{
                          tooltip: { trigger: "axis" },
                          grid: { left: 40, right: 10, top: 20, bottom: 30 },
                          xAxis: { type: "category", data: ["一", "二", "三", "四", "五", "六"] },
                          yAxis: { type: "value" },
                          color: [primary],
                          series: [{ type: "line", smooth: true, data: [120, 132, 101, 134, 90, 230] }],
                        }}
                      />
                    </Card>
                  </Col>
                  <Col xs={24} md={12}>
                    <Card title="安全事件统计（示意）" extra={<Button size="small">导出 Excel</Button>}>
                      <EChart
                        option={{
                          tooltip: { trigger: "axis" },
                          grid: { left: 40, right: 10, top: 20, bottom: 30 },
                          xAxis: { type: "category", data: ["燃气", "供水", "排水"] },
                          yAxis: { type: "value" },
                          color: [primary, "#f59e0b", "#a855f7"],
                          series: [{ type: "bar", data: [32, 21, 17], barWidth: "50%" }],
                        }}
                      />
                    </Card>
                  </Col>
                </Row>
              </section>
            )}

            {selectedMenu === "incidents" && (
              <section className="space-y-4">
                <Row gutter={[16, 16]}>
                  <Col xs={24} md={16}>
                    <Card title="事件列表（示意）" extra={<Button size="small">新建事件</Button>}>
                      <Empty description="暂无数据（示意）" />
                    </Card>
                  </Col>
                  <Col xs={24} md={8}>
                    <Card title="事件趋势（示意）">
                      <EChart
                        option={{
                          tooltip: { trigger: "axis" },
                          grid: { left: 40, right: 10, top: 20, bottom: 30 },
                          xAxis: { type: "category", data: Array.from({ length: 12 }).map((_, i) => `${i + 1}月`) },
                          yAxis: { type: "value" },
                          color: [primary],
                          series: [{ type: "line", smooth: true, data: Array.from({ length: 12 }).map(() => Math.floor(Math.random() * 20) + 5) }],
                        }}
                      />
                    </Card>
                  </Col>
                </Row>
              </section>
            )}

            {selectedMenu === "bigscreen" && (
              <section className="space-y-4">
                <Card title="数据大屏（示意）">
                  <Row gutter={[16, 16]}>
                    {[
                      { title: "设备总数", val: devices.length },
                      { title: "在线率", val: `${onlineRate}%` },
                      { title: "本月预警", val: (alerts.length + Math.floor(Math.random() * 30)).toString() },
                      { title: "闭环率", val: `${Math.round((alerts.filter((a) => a.status === "已闭环").length / Math.max(alerts.length, 1)) * 100)}%` },
                    ].map((s) => (
                      <Col xs={12} md={6} key={s.title}>
                        <Card size="small">
                          <div className="text-xs text-slate-500">{s.title}</div>
                          <div className="text-2xl font-semibold mt-1">{s.val}</div>
                        </Card>
                      </Col>
                    ))}
                  </Row>
                  <Row gutter={[16, 16]} className="mt-1">
                    <Col xs={24} md={12}>
                      <Card>
                        <EChart option={deviceBarOption} />
                      </Card>
                    </Col>
                    <Col xs={24} md={12}>
                      <Card>
                        <EChart option={riskBarOption} />
                      </Card>
                    </Col>
                  </Row>
                </Card>
              </section>
            )}

            {selectedMenu === "settings" && (
              <section className="space-y-4">
                <Card title="预警设置">
                  <Row gutter={[16, 16]}>
                    <Col xs={24} md={12}>
                      <Card size="small" title="阈值设置">
                        <div className="grid grid-cols-2 gap-4">
                          <div>
                            <div className="text-xs text-slate-500 mb-1">压力异常阈值</div>
                            <Select defaultValue="P≤0.3MPa" options={[{ value: "P≤0.3MPa", label: "P≤0.3MPa" }, { value: "P≤0.2MPa", label: "P≤0.2MPa" }]} />
                          </div>
                          <div>
                            <div className="text-xs text-slate-500 mb-1">流量突变阈值</div>
                            <Select defaultValue="ΔQ≥20%" options={[{ value: "ΔQ≥20%", label: "ΔQ≥20%" }, { value: "ΔQ≥30%", label: "ΔQ≥30%" }]} />
                          </div>
                          <div>
                            <div className="text-xs text-slate-500 mb-1">水质指标（浊度）</div>
                            <Select defaultValue="≥5 NTU" options={[{ value: "≥5 NTU", label: "≥5 NTU" }, { value: "≥3 NTU", label: "≥3 NTU" }]} />
                          </div>
                          <div>
                            <div className="text-xs text-slate-500 mb-1">液位过低</div>
                            <Select defaultValue="≤20%" options={[{ value: "≤20%", label: "≤20%" }, { value: "≤15%", label: "≤15%" }]} />
                          </div>
                        </div>
                      </Card>
                    </Col>
                    <Col xs={24} md={12}>
                      <Card size="small" title="通知策略">
                        <div className="grid grid-cols-2 gap-4">
                          <div className="flex items-center justify-between">
                            <span>高等级预警短信</span>
                            <Switch defaultChecked />
                          </div>
                          <div className="flex items-center justify-between">
                            <span>邮件抄送管理层</span>
                            <Switch />
                          </div>
                          <div className="flex items-center justify-between">
                            <span>自动派单</span>
                            <Switch />
                          </div>
                          <div className="flex items-center justify-between">
                            <span>与值守大屏联动</span>
                            <Switch defaultChecked />
                          </div>
                        </div>
                      </Card>
                    </Col>
                  </Row>
                </Card>
              </section>
            )}
          </Content>
        </Layout>
      </Layout>
    </ConfigProvider>
  )
}
