"use client"

import {useEffect, useState} from "react"
import {Button, Card, Col, Descriptions, Form, Input, Modal, Row, Select, Space, Statistic, Table, Tabs} from "antd"
import {DeleteOutlined, EditOutlined, EyeOutlined, PlusOutlined, SearchOutlined} from "@ant-design/icons"
import globalMessage from "@/app/_modules/globalMessage";
import EChart from "@/components/echarts"

const { Option } = Select
const { TabPane } = Tabs

export default function DataManagement() {
  const [selectedTab, setSelectedTab] = useState("drainage-areas")
  const [modalVisible, setModalVisible] = useState(false)
  const [detailModalVisible, setDetailModalVisible] = useState(false)
  const [editingRecord, setEditingRecord] = useState<any>(null)
  const [detailRecord, setDetailRecord] = useState<any>(null)
  const [form] = Form.useForm()

  // 各种数据状态
  const [drainageAreas, setDrainageAreas] = useState([
    {
      key: "1",
      id: "DA001",
      name: "中心城区雨水分区",
      type: "雨水分区",
      area: "15.6",
      population: "120000",
      status: "正常",
    },
    {
      key: "2",
      id: "DA002",
      name: "工业园区污水分区",
      type: "污水分区",
      area: "8.3",
      population: "45000",
      status: "正常",
    },
  ])

  const [pipelineData, setPipelineData] = useState([
    {
      key: "1",
      id: "PL001",
      name: "主干道雨水管",
      type: "雨水管",
      diameter: "1200mm",
      length: "2.5km",
      material: "钢筋混凝土",
      status: "良好",
    },
    {
      key: "2",
      id: "PL002",
      name: "支线污水管",
      type: "污水管",
      diameter: "800mm",
      length: "1.8km",
      material: "HDPE",
      status: "良好",
    },
  ])

  const [engineeringFacilities, setEngineeringFacilities] = useState([
    {
      key: "1",
      id: "EF001",
      name: "第一泵站",
      type: "泵站",
      capacity: "500m³/h",
      power: "75kW",
      status: "运行中",
    },
    {
      key: "2",
      id: "EF002",
      name: "调蓄池A",
      type: "调蓄设施",
      capacity: "10000m³",
      currentLevel: "30%",
      status: "待命",
    },
  ])

  const [waterloggingPoints, setWaterloggingPoints] = useState([
    {
      key: "1",
      id: "WP001",
      name: "人民路积水点",
      location: "人民路与南京路交叉口",
      riskLevel: "高",
      historicalDepth: "0.8m",
      status: "监控中",
    },
    {
      key: "2",
      id: "WP002",
      name: "商业区积水点",
      location: "淮海路商业广场",
      riskLevel: "中",
      historicalDepth: "0.5m",
      status: "监控中",
    },
  ])

  const [monitoringDevices, setMonitoringDevices] = useState([
    {
      key: "1",
      id: "MD001",
      name: "液位计LV002",
      type: "液位计",
      location: "人民路积水点",
      installDate: "2023-06-15",
      lastMaintenance: "2024-01-10",
      status: "在线",
    },
    {
      key: "2",
      id: "MD002",
      name: "流量计FL001",
      type: "流量计",
      location: "主干道管网",
      installDate: "2023-08-20",
      lastMaintenance: "2024-01-08",
      status: "在线",
    },
  ])

  // 查询条件状态
  const [searchParams, setSearchParams] = useState({
    drainageArea: { name: "", type: "" },
    pipeline: { id: "", type: "" },
    facility: { name: "", type: "" },
    waterlogging: { name: "", riskLevel: "" },
    device: { id: "", type: "" }
  })

  // 过滤后的数据
  const [filteredDrainageAreas, setFilteredDrainageAreas] = useState(drainageAreas)
  const [filteredPipelineData, setFilteredPipelineData] = useState(pipelineData)
  const [filteredEngineeringFacilities, setFilteredEngineeringFacilities] = useState(engineeringFacilities)
  const [filteredWaterloggingPoints, setFilteredWaterloggingPoints] = useState(waterloggingPoints)
  const [filteredMonitoringDevices, setFilteredMonitoringDevices] = useState(monitoringDevices)

  // 当原始数据变化时更新过滤数据
  useEffect(() => {
    setFilteredDrainageAreas(drainageAreas)
    setFilteredPipelineData(pipelineData)
    setFilteredEngineeringFacilities(engineeringFacilities)
    setFilteredWaterloggingPoints(waterloggingPoints)
    setFilteredMonitoringDevices(monitoringDevices)
  }, [drainageAreas, pipelineData, engineeringFacilities, waterloggingPoints, monitoringDevices])

  const handleEdit = (record: any) => {
    setEditingRecord(record)
    form.setFieldsValue(record)
    setModalVisible(true)
  }

  const handleViewDetail = (record: any) => {
    setDetailRecord(record)
    setDetailModalVisible(true)
  }

  const handleDelete = (record: any, dataType: string) => {
    Modal.confirm({
      title: "确认删除",
      content: `确定要删除 ${record.name} 吗？`,
      onOk() {
        switch (dataType) {
          case "drainage":
            setDrainageAreas(prev => prev.filter(item => item.id !== record.id))
            break
          case "pipeline":
            setPipelineData(prev => prev.filter(item => item.id !== record.id))
            break
          case "facility":
            setEngineeringFacilities(prev => prev.filter(item => item.id !== record.id))
            break
          case "waterlogging":
            setWaterloggingPoints(prev => prev.filter(item => item.id !== record.id))
            break
          case "device":
            setMonitoringDevices(prev => prev.filter(item => item.id !== record.id))
            break
        }
        globalMessage.success("删除成功")
      },
    })
  }

  const handleAdd = () => {
    setEditingRecord(null)
    form.resetFields()
    setModalVisible(true)
  }

  const handleSave = () => {
    form.validateFields().then(values => {
      if (editingRecord) {
        // 编辑现有记录
        const updatedData = {
          ...editingRecord,
          ...values
        }
        
        switch (selectedTab) {
          case "drainage-areas":
            setDrainageAreas(prev => prev.map(item => 
              item.id === editingRecord.id ? updatedData : item
            ))
            break
          case "pipeline-network":
            setPipelineData(prev => prev.map(item => 
              item.id === editingRecord.id ? updatedData : item
            ))
            break
          case "engineering-facilities":
            setEngineeringFacilities(prev => prev.map(item => 
              item.id === editingRecord.id ? updatedData : item
            ))
            break
          case "waterlogging-points":
            setWaterloggingPoints(prev => prev.map(item => 
              item.id === editingRecord.id ? updatedData : item
            ))
            break
          case "monitoring-devices":
            setMonitoringDevices(prev => prev.map(item => 
              item.id === editingRecord.id ? updatedData : item
            ))
            break
        }
      } else {
        // 添加新记录
        const newRecord = {
          ...values,
          key: Date.now().toString(),
          id: generateId(selectedTab)
        }
        
        switch (selectedTab) {
          case "drainage-areas":
            setDrainageAreas(prev => [...prev, newRecord])
            break
          case "pipeline-network":
            setPipelineData(prev => [...prev, newRecord])
            break
          case "engineering-facilities":
            setEngineeringFacilities(prev => [...prev, newRecord])
            break
          case "waterlogging-points":
            setWaterloggingPoints(prev => [...prev, newRecord])
            break
          case "monitoring-devices":
            setMonitoringDevices(prev => [...prev, newRecord])
            break
        }
      }
      
      globalMessage.success(editingRecord ? "编辑成功" : "新增成功")
      setModalVisible(false)
      setEditingRecord(null)
      form.resetFields()
    })
  }

  const generateId = (tab: string) => {
    const prefixMap: Record<string, string> = {
      "drainage-areas": "DA",
      "pipeline-network": "PL",
      "engineering-facilities": "EF",
      "waterlogging-points": "WP",
      "monitoring-devices": "MD"
    }
    
    const prefix = prefixMap[tab] || "ID"
    const timestamp = Date.now().toString().slice(-6)
    return `${prefix}${timestamp}`
  }

  // 查询处理函数
  const handleSearch = (dataType: string) => {
    switch (dataType) {
      case "drainage":
        const filteredDrainage = drainageAreas.filter(item => {
          return (
            (searchParams.drainageArea.name === "" || 
             item.name.toLowerCase().includes(searchParams.drainageArea.name.toLowerCase())) &&
            (searchParams.drainageArea.type === "" || 
             item.type.includes(searchParams.drainageArea.type))
          )
        })
        setFilteredDrainageAreas(filteredDrainage)
        break
        
      case "pipeline":
        const filteredPipeline = pipelineData.filter(item => {
          return (
            (searchParams.pipeline.id === "" || 
             item.id.toLowerCase().includes(searchParams.pipeline.id.toLowerCase())) &&
            (searchParams.pipeline.type === "" || 
             item.type.includes(searchParams.pipeline.type))
          )
        })
        setFilteredPipelineData(filteredPipeline)
        break
        
      case "facility":
        const filteredFacility = engineeringFacilities.filter(item => {
          return (
            (searchParams.facility.name === "" || 
             item.name.toLowerCase().includes(searchParams.facility.name.toLowerCase())) &&
            (searchParams.facility.type === "" || 
             item.type.includes(searchParams.facility.type))
          )
        })
        setFilteredEngineeringFacilities(filteredFacility)
        break
        
      case "waterlogging":
        const filteredWaterlogging = waterloggingPoints.filter(item => {
          return (
            (searchParams.waterlogging.name === "" || 
             item.name.toLowerCase().includes(searchParams.waterlogging.name.toLowerCase())) &&
            (searchParams.waterlogging.riskLevel === "" || 
             item.riskLevel.includes(searchParams.waterlogging.riskLevel))
          )
        })
        setFilteredWaterloggingPoints(filteredWaterlogging)
        break
        
      case "device":
        const filteredDevice = monitoringDevices.filter(item => {
          return (
            (searchParams.device.id === "" || 
             item.id.toLowerCase().includes(searchParams.device.id.toLowerCase())) &&
            (searchParams.device.type === "" || 
             item.type.includes(searchParams.device.type))
          )
        })
        setFilteredMonitoringDevices(filteredDevice)
        break
    }
  }

  // 更新搜索参数
  const updateSearchParams = (dataType: string, field: string, value: string) => {
    setSearchParams(prev => ({
      ...prev,
      [dataType]: {
        ...prev[dataType],
        [field]: value
      }
    }))
  }

  const commonColumns = [
    {
      title: "操作",
      key: "action",
      width: 200,
      render: (_, record) => (
        <Space>
          <Button size="small" icon={<EyeOutlined />} onClick={() => handleViewDetail(record)}>
            详情
          </Button>
          <Button size="small" icon={<EditOutlined />} onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Button 
            size="small" 
            danger 
            icon={<DeleteOutlined />} 
            onClick={() => {
              let dataType = ""
              switch (selectedTab) {
                case "drainage-areas": dataType = "drainage"; break
                case "pipeline-network": dataType = "pipeline"; break
                case "engineering-facilities": dataType = "facility"; break
                case "waterlogging-points": dataType = "waterlogging"; break
                case "monitoring-devices": dataType = "device"; break
              }
              handleDelete(record, dataType)
            }}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ]

  const drainageAreaColumns = [
    { title: "分区编号", dataIndex: "id", key: "id" },
    { title: "分区名称", dataIndex: "name", key: "name" },
    { title: "分区类型", dataIndex: "type", key: "type" },
    { title: "面积(km²)", dataIndex: "area", key: "area" },
    { title: "服务人口", dataIndex: "population", key: "population" },
    { title: "状态", dataIndex: "status", key: "status" },
    ...commonColumns,
  ]

  const pipelineColumns = [
    { title: "管线编号", dataIndex: "id", key: "id" },
    { title: "管线名称", dataIndex: "name", key: "name" },
    { title: "管线类型", dataIndex: "type", key: "type" },
    { title: "管径", dataIndex: "diameter", key: "diameter" },
    { title: "长度", dataIndex: "length", key: "length" },
    { title: "材质", dataIndex: "material", key: "material" },
    { title: "状态", dataIndex: "status", key: "status" },
    ...commonColumns,
  ]

  const facilityColumns = [
    { title: "设施编号", dataIndex: "id", key: "id" },
    { title: "设施名称", dataIndex: "name", key: "name" },
    { title: "设施类型", dataIndex: "type", key: "type" },
    { title: "处理能力", dataIndex: "capacity", key: "capacity" },
    { title: "功率/当前液位", dataIndex: "power", key: "power" },
    { title: "状态", dataIndex: "status", key: "status" },
    ...commonColumns,
  ]

  const waterloggingColumns = [
    { title: "点位编号", dataIndex: "id", key: "id" },
    { title: "点位名称", dataIndex: "name", key: "name" },
    { title: "位置", dataIndex: "location", key: "location" },
    { title: "风险等级", dataIndex: "riskLevel", key: "riskLevel" },
    { title: "历史最大积水深度", dataIndex: "historicalDepth", key: "historicalDepth" },
    { title: "状态", dataIndex: "status", key: "status" },
    ...commonColumns,
  ]

  const deviceColumns = [
    { title: "设备编号", dataIndex: "id", key: "id" },
    { title: "设备名称", dataIndex: "name", key: "name" },
    { title: "设备类型", dataIndex: "type", key: "type" },
    { title: "安装位置", dataIndex: "location", key: "location" },
    { title: "安装日期", dataIndex: "installDate", key: "installDate" },
    { title: "最后维护", dataIndex: "lastMaintenance", key: "lastMaintenance" },
    { title: "状态", dataIndex: "status", key: "status" },
    ...commonColumns,
  ]

  const renderTabContent = () => {
    switch (selectedTab) {
      case "drainage-areas":
        return (
          <Card title="排水分区基础数据管理">
            <div className="mb-4">
              <Space>
                <Input 
                  placeholder="分区名称" 
                  prefix={<SearchOutlined />} 
                  value={searchParams.drainageArea.name}
                  onChange={e => updateSearchParams("drainageArea", "name", e.target.value)}
                />
                <Select 
                  placeholder="分区类型" 
                  style={{ width: 120 }}
                  value={searchParams.drainageArea.type}
                  onChange={value => updateSearchParams("drainageArea", "type", value)}
                >
                  <Option value="雨水分区">雨水分区</Option>
                  <Option value="污水分区">污水分区</Option>
                </Select>
                <Button 
                  type="primary" 
                  icon={<SearchOutlined />} 
                  onClick={() => handleSearch("drainage")}
                >
                  查询
                </Button>
                <Button 
                  type="primary" 
                  icon={<PlusOutlined />} 
                  onClick={handleAdd}
                >
                  新增
                </Button>
              </Space>
            </div>
            <Table columns={drainageAreaColumns} dataSource={filteredDrainageAreas} />
          </Card>
        )

      case "pipeline-network":
        return (
          <Card title="排水管网基础数据管理">
            <div className="mb-4">
              <Space>
                <Input 
                  placeholder="管线编号" 
                  prefix={<SearchOutlined />} 
                  value={searchParams.pipeline.id}
                  onChange={e => updateSearchParams("pipeline", "id", e.target.value)}
                />
                <Select 
                  placeholder="管线类型" 
                  style={{ width: 120 }}
                  value={searchParams.pipeline.type}
                  onChange={value => updateSearchParams("pipeline", "type", value)}
                >
                  <Option value="雨水管">雨水管</Option>
                  <Option value="污水管">污水管</Option>
                </Select>
                <Button 
                  type="primary" 
                  icon={<SearchOutlined />} 
                  onClick={() => handleSearch("pipeline")}
                >
                  查询
                </Button>
                <Button 
                  type="primary" 
                  icon={<PlusOutlined />} 
                  onClick={handleAdd}
                >
                  新增
                </Button>
              </Space>
            </div>
            <Table columns={pipelineColumns} dataSource={filteredPipelineData} />
          </Card>
        )

      case "engineering-facilities":
        return (
          <Card title="工程设施基础数据管理">
            <div className="mb-4">
              <Space>
                <Input 
                  placeholder="设施名称" 
                  prefix={<SearchOutlined />} 
                  value={searchParams.facility.name}
                  onChange={e => updateSearchParams("facility", "name", e.target.value)}
                />
                <Select 
                  placeholder="设施类型" 
                  style={{ width: 120 }}
                  value={searchParams.facility.type}
                  onChange={value => updateSearchParams("facility", "type", value)}
                >
                  <Option value="泵站">泵站</Option>
                  <Option value="调蓄设施">调蓄设施</Option>
                  <Option value="闸门">闸门</Option>
                </Select>
                <Button 
                  type="primary" 
                  icon={<SearchOutlined />} 
                  onClick={() => handleSearch("facility")}
                >
                  查询
                </Button>
                <Button 
                  type="primary" 
                  icon={<PlusOutlined />} 
                  onClick={handleAdd}
                >
                  新增
                </Button>
              </Space>
            </div>
            <Table columns={facilityColumns} dataSource={filteredEngineeringFacilities} />
          </Card>
        )

      case "waterlogging-points":
        return (
          <Card title="易积水点管理">
            <div className="mb-4">
              <Space>
                <Input 
                  placeholder="点位名称" 
                  prefix={<SearchOutlined />} 
                  value={searchParams.waterlogging.name}
                  onChange={e => updateSearchParams("waterlogging", "name", e.target.value)}
                />
                <Select 
                  placeholder="风险等级" 
                  style={{ width: 120 }}
                  value={searchParams.waterlogging.riskLevel}
                  onChange={value => updateSearchParams("waterlogging", "riskLevel", value)}
                >
                  <Option value="高">高</Option>
                  <Option value="中">中</Option>
                  <Option value="低">低</Option>
                </Select>
                <Button 
                  type="primary" 
                  icon={<SearchOutlined />} 
                  onClick={() => handleSearch("waterlogging")}
                >
                  查询
                </Button>
                <Button 
                  type="primary" 
                  icon={<PlusOutlined />} 
                  onClick={handleAdd}
                >
                  新增
                </Button>
              </Space>
            </div>
            <Table columns={waterloggingColumns} dataSource={filteredWaterloggingPoints} />
          </Card>
        )

      case "monitoring-devices":
        return (
          <Card title="监测设备管理">
            <div className="mb-4">
              <Space>
                <Input 
                  placeholder="设备编号" 
                  prefix={<SearchOutlined />} 
                  value={searchParams.device.id}
                  onChange={e => updateSearchParams("device", "id", e.target.value)}
                />
                <Select 
                  placeholder="设备类型" 
                  style={{ width: 120 }}
                  value={searchParams.device.type}
                  onChange={value => updateSearchParams("device", "type", value)}
                >
                  <Option value="液位计">液位计</Option>
                  <Option value="流量计">流量计</Option>
                  <Option value="泵站设备">泵站设备</Option>
                </Select>
                <Button 
                  type="primary" 
                  icon={<SearchOutlined />} 
                  onClick={() => handleSearch("device")}
                >
                  查询
                </Button>
                <Button 
                  type="primary" 
                  icon={<PlusOutlined />} 
                  onClick={handleAdd}
                >
                  新增
                </Button>
              </Space>
            </div>
            <Table columns={deviceColumns} dataSource={filteredMonitoringDevices} />
          </Card>
        )

      default:
        return null
    }
  }

  // 获取当前tab的表单字段
  const getFormFields = () => {
    switch (selectedTab) {
      case "drainage-areas":
        return (
          <>
            <Form.Item 
              name="name" 
              label="分区名称" 
              rules={[{ required: true, message: '请输入分区名称' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item 
              name="type" 
              label="分区类型" 
              rules={[{ required: true, message: '请选择分区类型' }]}
            >
              <Select>
                <Option value="雨水分区">雨水分区</Option>
                <Option value="污水分区">污水分区</Option>
              </Select>
            </Form.Item>
            <Form.Item name="area" label="面积(km²)">
              <Input />
            </Form.Item>
            <Form.Item name="population" label="服务人口">
              <Input />
            </Form.Item>
            <Form.Item name="status" label="状态">
              <Select>
                <Option value="正常">正常</Option>
                <Option value="维护中">维护中</Option>
              </Select>
            </Form.Item>
          </>
        )
        
      case "pipeline-network":
        return (
          <>
            <Form.Item 
              name="name" 
              label="管线名称" 
              rules={[{ required: true, message: '请输入管线名称' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item 
              name="type" 
              label="管线类型" 
              rules={[{ required: true, message: '请选择管线类型' }]}
            >
              <Select>
                <Option value="雨水管">雨水管</Option>
                <Option value="污水管">污水管</Option>
              </Select>
            </Form.Item>
            <Form.Item name="diameter" label="管径">
              <Input />
            </Form.Item>
            <Form.Item name="length" label="长度">
              <Input />
            </Form.Item>
            <Form.Item name="material" label="材质">
              <Input />
            </Form.Item>
            <Form.Item name="status" label="状态">
              <Select>
                <Option value="良好">良好</Option>
                <Option value="一般">一般</Option>
                <Option value="需维护">需维护</Option>
              </Select>
            </Form.Item>
          </>
        )
        
      case "engineering-facilities":
        return (
          <>
            <Form.Item 
              name="name" 
              label="设施名称" 
              rules={[{ required: true, message: '请输入设施名称' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item 
              name="type" 
              label="设施类型" 
              rules={[{ required: true, message: '请选择设施类型' }]}
            >
              <Select>
                <Option value="泵站">泵站</Option>
                <Option value="调蓄设施">调蓄设施</Option>
                <Option value="闸门">闸门</Option>
              </Select>
            </Form.Item>
            <Form.Item name="capacity" label="处理能力">
              <Input />
            </Form.Item>
            <Form.Item name="power" label="功率/当前液位">
              <Input />
            </Form.Item>
            <Form.Item name="status" label="状态">
              <Select>
                <Option value="运行中">运行中</Option>
                <Option value="待命">待命</Option>
                <Option value="维护中">维护中</Option>
              </Select>
            </Form.Item>
          </>
        )
        
      case "waterlogging-points":
        return (
          <>
            <Form.Item 
              name="name" 
              label="点位名称" 
              rules={[{ required: true, message: '请输入点位名称' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item name="location" label="位置">
              <Input />
            </Form.Item>
            <Form.Item name="riskLevel" label="风险等级">
              <Select>
                <Option value="高">高</Option>
                <Option value="中">中</Option>
                <Option value="低">低</Option>
              </Select>
            </Form.Item>
            <Form.Item name="historicalDepth" label="历史最大积水深度">
              <Input />
            </Form.Item>
            <Form.Item name="status" label="状态">
              <Select>
                <Option value="监控中">监控中</Option>
                <Option value="维护中">维护中</Option>
              </Select>
            </Form.Item>
          </>
        )
        
      case "monitoring-devices":
        return (
          <>
            <Form.Item 
              name="name" 
              label="设备名称" 
              rules={[{ required: true, message: '请输入设备名称' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item 
              name="type" 
              label="设备类型" 
              rules={[{ required: true, message: '请选择设备类型' }]}
            >
              <Select>
                <Option value="液位计">液位计</Option>
                <Option value="流量计">流量计</Option>
                <Option value="泵站设备">泵站设备</Option>
              </Select>
            </Form.Item>
            <Form.Item name="location" label="安装位置">
              <Input />
            </Form.Item>
            <Form.Item name="installDate" label="安装日期">
              <Input type="date" />
            </Form.Item>
            <Form.Item name="lastMaintenance" label="最后维护">
              <Input type="date" />
            </Form.Item>
            <Form.Item name="status" label="状态">
              <Select>
                <Option value="在线">在线</Option>
                <Option value="离线">离线</Option>
                <Option value="维护中">维护中</Option>
              </Select>
            </Form.Item>
          </>
        )
        
      default:
        return null
    }
  }

  // 获取详情描述项
  const getDetailDescriptions = () => {
    switch (selectedTab) {
      case "drainage-areas":
        return (
          <Descriptions title="排水分区详情" column={2} bordered>
            <Descriptions.Item label="分区编号">{detailRecord?.id}</Descriptions.Item>
            <Descriptions.Item label="分区名称">{detailRecord?.name}</Descriptions.Item>
            <Descriptions.Item label="分区类型">{detailRecord?.type}</Descriptions.Item>
            <Descriptions.Item label="面积">{detailRecord?.area} km²</Descriptions.Item>
            <Descriptions.Item label="服务人口">{detailRecord?.population}</Descriptions.Item>
            <Descriptions.Item label="状态">{detailRecord?.status}</Descriptions.Item>
          </Descriptions>
        )
        
      case "pipeline-network":
        return (
          <Descriptions title="管网设施详情" column={2} bordered>
            <Descriptions.Item label="管线编号">{detailRecord?.id}</Descriptions.Item>
            <Descriptions.Item label="管线名称">{detailRecord?.name}</Descriptions.Item>
            <Descriptions.Item label="管线类型">{detailRecord?.type}</Descriptions.Item>
            <Descriptions.Item label="管径">{detailRecord?.diameter}</Descriptions.Item>
            <Descriptions.Item label="长度">{detailRecord?.length}</Descriptions.Item>
            <Descriptions.Item label="材质">{detailRecord?.material}</Descriptions.Item>
            <Descriptions.Item label="状态">{detailRecord?.status}</Descriptions.Item>
          </Descriptions>
        )
        
      case "engineering-facilities":
        return (
          <Descriptions title="工程设施详情" column={2} bordered>
            <Descriptions.Item label="设施编号">{detailRecord?.id}</Descriptions.Item>
            <Descriptions.Item label="设施名称">{detailRecord?.name}</Descriptions.Item>
            <Descriptions.Item label="设施类型">{detailRecord?.type}</Descriptions.Item>
            <Descriptions.Item label="处理能力">{detailRecord?.capacity}</Descriptions.Item>
            <Descriptions.Item label="功率/当前液位">{detailRecord?.power || detailRecord?.currentLevel}</Descriptions.Item>
            <Descriptions.Item label="状态">{detailRecord?.status}</Descriptions.Item>
          </Descriptions>
        )
        
      case "waterlogging-points":
        return (
          <Descriptions title="易积水点详情" column={2} bordered>
            <Descriptions.Item label="点位编号">{detailRecord?.id}</Descriptions.Item>
            <Descriptions.Item label="点位名称">{detailRecord?.name}</Descriptions.Item>
            <Descriptions.Item label="位置">{detailRecord?.location}</Descriptions.Item>
            <Descriptions.Item label="风险等级">{detailRecord?.riskLevel}</Descriptions.Item>
            <Descriptions.Item label="历史最大积水深度">{detailRecord?.historicalDepth}</Descriptions.Item>
            <Descriptions.Item label="状态">{detailRecord?.status}</Descriptions.Item>
          </Descriptions>
        )
        
      case "monitoring-devices":
        return (
          <Descriptions title="监测设备详情" column={2} bordered>
            <Descriptions.Item label="设备编号">{detailRecord?.id}</Descriptions.Item>
            <Descriptions.Item label="设备名称">{detailRecord?.name}</Descriptions.Item>
            <Descriptions.Item label="设备类型">{detailRecord?.type}</Descriptions.Item>
            <Descriptions.Item label="安装位置">{detailRecord?.location}</Descriptions.Item>
            <Descriptions.Item label="安装日期">{detailRecord?.installDate}</Descriptions.Item>
            <Descriptions.Item label="最后维护">{detailRecord?.lastMaintenance}</Descriptions.Item>
            <Descriptions.Item label="状态">{detailRecord?.status}</Descriptions.Item>
          </Descriptions>
        )
        
      default:
        return null
    }
  }

  // 生成图表选项
  const generateChartOption = () => {
    switch (selectedTab) {
      case "drainage-areas":
        return {
          title: {
            text: '排水分区统计',
            left: 'center'
          },
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            left: 'left'
          },
          series: [
            {
              name: '分区类型',
              type: 'pie',
              radius: '50%',
              data: [
                { value: drainageAreas.filter(item => item.type === '雨水分区').length, name: '雨水分区' },
                { value: drainageAreas.filter(item => item.type === '污水分区').length, name: '污水分区' }
              ],
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        }
        
      case "pipeline-network":
        return {
          title: {
            text: '管网长度统计',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            data: pipelineData.map(item => item.name)
          },
          yAxis: {
            type: 'value',
            name: '长度(km)'
          },
          series: [
            {
              data: pipelineData.map(item => parseFloat(item.length?.replace('km', '') || '0')),
              type: 'bar'
            }
          ]
        }
        
      case "engineering-facilities":
        return {
          title: {
            text: '设施状态统计',
            left: 'center'
          },
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            left: 'left'
          },
          series: [
            {
              name: '设施状态',
              type: 'pie',
              radius: '50%',
              data: [
                { value: engineeringFacilities.filter(item => item.status === '运行中').length, name: '运行中' },
                { value: engineeringFacilities.filter(item => item.status === '待命').length, name: '待命' },
                { value: engineeringFacilities.filter(item => item.status === '维护中').length, name: '维护中' }
              ],
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        }
        
      case "waterlogging-points":
        return {
          title: {
            text: '积水点风险等级统计',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            data: ['高', '中', '低']
          },
          yAxis: {
            type: 'value',
            name: '数量(个)'
          },
          series: [
            {
              data: [
                waterloggingPoints.filter(item => item.riskLevel === '高').length,
                waterloggingPoints.filter(item => item.riskLevel === '中').length,
                waterloggingPoints.filter(item => item.riskLevel === '低').length
              ],
              type: 'bar',
              itemStyle: {
                color: (params: any) => {
                  const colors = ['#ff4d4f', '#faad14', '#52c41a']
                  return colors[params.dataIndex]
                }
              }
            }
          ]
        }
        
      case "monitoring-devices":
        return {
          title: {
            text: '设备状态统计',
            left: 'center'
          },
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            left: 'left'
          },
          series: [
            {
              name: '设备状态',
              type: 'pie',
              radius: '50%',
              data: [
                { value: monitoringDevices.filter(item => item.status === '在线').length, name: '在线' },
                { value: monitoringDevices.filter(item => item.status === '离线').length, name: '离线' },
                { value: monitoringDevices.filter(item => item.status === '维护中').length, name: '维护中' }
              ],
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        }
        
      default:
        return {}
    }
  }

  return (
    <div className="space-y-6">
      {/* 统计概览 */}
      <Row gutter={[16, 16]}>
        <Col span={6}>
          <Card>
            <Statistic title="排水分区" value={drainageAreas.length} suffix="个" />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="管网长度" value={pipelineData.reduce((sum, item) => {
              const length = parseFloat(item.length?.replace('km', '') || '0')
              return sum + length
            }, 0).toFixed(1)} suffix="km" />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="工程设施" value={engineeringFacilities.length} suffix="座" />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="监测设备" value={monitoringDevices.length} suffix="台" />
          </Card>
        </Col>
      </Row>

      <Tabs activeKey={selectedTab} onChange={setSelectedTab}>
        <TabPane tab="排水分区" key="drainage-areas">
          <Row gutter={[16, 16]}>
            <Col span={16}>{renderTabContent()}</Col>
            <Col span={8}>
              <Card title="分区统计图" className="h-96">
                <EChart option={generateChartOption()} style={{ height: '20rem' }} />
              </Card>
            </Col>
          </Row>
        </TabPane>

        <TabPane tab="管网设施" key="pipeline-network">
          <Row gutter={[16, 16]}>
            <Col span={16}>{renderTabContent()}</Col>
            <Col span={8}>
              <Card title="管网统计图" className="h-96">
                <EChart option={generateChartOption()} style={{ height: '20rem' }} />
              </Card>
            </Col>
          </Row>
        </TabPane>

        <TabPane tab="工程设施" key="engineering-facilities">
          <Row gutter={[16, 16]}>
            <Col span={16}>{renderTabContent()}</Col>
            <Col span={8}>
              <Card title="设施统计图" className="h-96">
                <EChart option={generateChartOption()} style={{ height: '20rem' }} />
              </Card>
            </Col>
          </Row>
        </TabPane>

        <TabPane tab="易积水点" key="waterlogging-points">
          <Row gutter={[16, 16]}>
            <Col span={16}>{renderTabContent()}</Col>
            <Col span={8}>
              <Card title="积水点统计图" className="h-96">
                <EChart option={generateChartOption()} style={{ height: '20rem' }} />
              </Card>
            </Col>
          </Row>
        </TabPane>

        <TabPane tab="监测设备" key="monitoring-devices">
          {renderTabContent()}
        </TabPane>
      </Tabs>

      {/* 编辑/新增模态框 */}
      <Modal
        title={editingRecord ? "编辑" : "新增"}
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false)
          setEditingRecord(null)
          form.resetFields()
        }}
        onOk={handleSave}
        width={600}
      >
        <Form form={form} layout="vertical">
          {getFormFields()}
        </Form>
      </Modal>

      {/* 详情模态框 */}
      <Modal
        title="详情信息"
        open={detailModalVisible}
        onCancel={() => {
          setDetailModalVisible(false)
          setDetailRecord(null)
        }}
        onOk={() => {
          setDetailModalVisible(false)
          setDetailRecord(null)
        }}
        width={800}
      >
        {getDetailDescriptions()}
        {selectedTab !== "monitoring-devices" && (
          <div className="mt-6" style={{ height: 300 }}>
            <EChart option={generateChartOption()} style={{ height: '20rem' }} />
          </div>
        )}
      </Modal>
    </div>
  )
}
