  <template>
    <div class="app-container">
      <!-- 查询表单 -->
      <el-card class="search-card" shadow="never">
        <el-form :model="lightingQuery" ref="lightingQueryRef" :inline="true" label-width="80px">
          <el-form-item label="所属网关" prop="gateway_id">
            <el-select
                v-model="lightingQuery.gateway_id"
                placeholder="请选择网关"
                clearable
                style="width: 280px;"
                @change="handleGatewayChange"
            >
              <el-option
                  v-for="item in gatewayList"
                  :key="item.gateway_id"
                  :label="item.gateway_name"
                  :value="item.gateway_id"
              >
                <div class="gateway-option">
                  <span class="gateway-name">{{ item.gateway_name }}</span>
                  <el-tag
                      size="small"
                      :type="item.gateway_status === 1 ? 'success' : 'danger'"
                      class="gateway-status"
                  >
                    {{ item.gateway_status === 1 ? '在线' : '离线' }}
                  </el-tag>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备名称" prop="query">
            <el-input
                v-model="lightingQuery.query"
                placeholder="请输入设备名称"
                clearable
                style="width: 200px;"
                @keyup.enter="getLightingList"
                @input="handleQueryInput"
                @clear="handleQueryClear"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="getLightingList">搜索</el-button>
            <el-button icon="Refresh" @click="resetLightingQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 数据表格 -->
      <el-card class="table-card" shadow="never">
        <el-table
            v-loading="lightingLoading"
            :data="lightingList"
            stripe
            border
            :row-class-name="tableRowClassName"
            height="745"
        >
          <el-table-column label="设备信息" min-width="250" fixed="left">
            <template #default="scope">
              <div class="device-info">
                <div class="device-name">
                  <el-icon class="device-icon"><Monitor /></el-icon>
                  {{ scope.row.devices_name }}
                </div>
                <div class="device-code">{{ scope.row.devices_udid }}</div>
                <div class="device-type">
                  <el-tag size="small" type="info">{{ scope.row.devices_type_name }}</el-tag>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="位置信息" min-width="200">
            <template #default="scope">
              <div class="location-info">
                <div class="building">
                  <el-icon><OfficeBuilding /></el-icon>
                  {{ scope.row.building_name }}
                </div>
                <div class="region">
                  <el-icon><Location /></el-icon>
                  {{ scope.row.full_region_name }}
                </div>
                <div class="room" v-if="scope.row.room_name">
                  <el-icon><House /></el-icon>
                  {{ scope.row.room_name }}
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="网关信息" width="150">
            <template #default="scope">
              <div class="gateway-info">
                <div class="gateway-name">{{ scope.row.gateway_name }}</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="设备状态" width="120" align="center">
            <template #default="scope">
              <div class="device-status" style="padding: 10px 2px;">
                <el-tag :type="getDeviceOnlineStatus(scope.row) ? 'success' : 'danger'" class="status-tag">
                  <el-icon><CircleCheck v-if="getDeviceOnlineStatus(scope.row)" /><CircleClose v-else /></el-icon>
                  {{ getDeviceOnlineStatus(scope.row) ? '在线' : '离线' }}
                </el-tag>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="回路状态" min-width="300" align="center">
            <template #default="scope">
              <div class="circuit-status" :style="getCircuitGridStyle(scope.row)">
                <div
                    v-for="i in getCircuitCount(scope.row)"
                    :key="i"
                    class="circuit-item"
                    :class="{ 'clickable': getDeviceOnlineStatus(scope.row) && scope.row.devices_enabled === 1 }"
                >
                  <div class="circuit-name">{{ getCircuitName(scope.row.devices_json_object, i) }}</div>
                  <el-tag
                      size="small"
                      :type="getCircuitStatus(scope.row.devices_json_object, i) ? 'success' : 'info'"
                      class="circuit-tag"
                  >
                    <el-icon><Lightning v-if="getCircuitStatus(scope.row.devices_json_object, i)" /><Close v-else /></el-icon>
                    {{ i }}
                  </el-tag>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="最后通信" width="160" align="center">
            <template #default="scope">
              <div class="time-info">
                <el-icon><Clock /></el-icon>
                <span>{{ formatTime(scope.row.devices_last_request_time) }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" fixed="right" width="180" align="center">
            <template #default="scope">
              <div class="action-buttons">
                <el-button
                    type="primary"
                    size="small"
                    icon="Setting"
                    @click="handleDeviceControl(scope.row)"
                    :disabled="!getDeviceOnlineStatus(scope.row)"
                    class="action-btn control-btn"
                >
                  控制
                </el-button>
                <el-button
                    type="info"
                    size="small"
                    icon="View"
                    @click="handleDeviceDetail(scope.row)"
                    class="action-btn detail-btn"
                >
                  详情
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
              v-show="lightingTotal > 0"
              :total="lightingTotal"
              v-model:current-page="lightingQuery.currentPage"
              v-model:page-size="lightingQuery.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handlePageSizeChange"
              @current-change="handleCurrentPageChange"
          />
        </div>
      </el-card>

      <!-- 设备控制对话框 -->
      <el-dialog v-model="controlVisible" title="设备控制" width="800px" append-to-body>
        <el-form ref="controlFormRef" :model="controlForm" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="设备名称">
                <el-input v-model="controlForm.deviceName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备类型">
                <el-input v-model="controlForm.deviceType" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="所属位置">
            <el-input v-model="controlForm.location" disabled />
          </el-form-item>

          <el-divider content-position="left">回路控制</el-divider>

          <el-form-item label="快捷操作">
            <el-button-group>
              <el-button type="success" size="small" @click="setAllCircuits(1)">
                <el-icon><Lightning /></el-icon>
                全部开启
              </el-button>
              <el-button type="warning" size="small" @click="setAllCircuits(0)">
                <el-icon><Close /></el-icon>
                全部关闭
              </el-button>
              <el-button type="info" size="small" @click="resetToOriginal">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-button-group>

            <!-- 变更提示 -->
            <div v-if="hasChanges()" class="change-indicator">
              <el-tag type="warning" size="small">
                <el-icon><Warning /></el-icon>
                检测到 {{ Object.keys(getChangedCircuits()).length }} 个回路有变更
              </el-tag>
            </div>
          </el-form-item>

          <el-form-item label="回路控制">
            <div class="circuit-control-grid" :style="getControlGridStyle()">
              <div v-for="i in controlForm.circuitCount" :key="i" class="circuit-control-item"
                   :class="{ 'has-changes': controlForm.circuits[`tag${i}`] !== controlForm.originalCircuits[`tag${i}`] }">
                <div class="circuit-label">
                  <div class="circuit-number">
                    回路 {{ i }}
                    <el-icon v-if="controlForm.circuits[`tag${i}`] !== controlForm.originalCircuits[`tag${i}`]"
                             class="change-icon" color="#e6a23c">
                      <Warning />
                    </el-icon>
                  </div>
                  <div class="circuit-desc">{{ getCircuitName(controlForm.deviceJsonObject, i) }}</div>
                </div>
                <el-switch
                    v-model="controlForm.circuits[`tag${i}`]"
                    :active-value="1"
                    :inactive-value="0"
                    size="large"
                    active-text="开"
                    inactive-text="关"
                />
              </div>
            </div>

          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="controlVisible = false">取消</el-button>
            <el-button type="primary" @click="submitControl" :loading="controlLoading">
              <el-icon><Check /></el-icon>
              确定控制
            </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 设备详情对话框 -->
      <el-dialog v-model="detailVisible" title="设备详情" width="900px" append-to-body>
        <el-descriptions :column="2" border size="large">
          <el-descriptions-item label="设备名称">
            <el-tag type="primary">{{ deviceDetail.devices_name }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="设备编码">
            <el-text class="device-code-text">{{ deviceDetail.devices_udid }}</el-text>
          </el-descriptions-item>
          <el-descriptions-item label="设备类型">{{ deviceDetail.devices_type_name }}</el-descriptions-item>
          <el-descriptions-item label="设备型号">{{ deviceDetail.devices_type_code }}</el-descriptions-item>
          <el-descriptions-item label="所属建筑">{{ deviceDetail.building_name }}</el-descriptions-item>
          <el-descriptions-item label="所属区域">{{ deviceDetail.full_region_name }}</el-descriptions-item>
          <el-descriptions-item label="所属房间">{{ deviceDetail.room_name || '未分配' }}</el-descriptions-item>
          <el-descriptions-item label="所属网关">
            <span>{{ deviceDetail.gateway_name }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="在线状态">
            <el-tag :type="getDeviceOnlineStatus(deviceDetail) ? 'success' : 'danger'">
              <el-icon><CircleCheck v-if="getDeviceOnlineStatus(deviceDetail)" /><CircleClose v-else /></el-icon>
              {{ getDeviceOnlineStatus(deviceDetail) ? '在线' : '离线' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="设备状态">
            <el-tag :type="deviceDetail.devices_enabled === 1 ? 'success' : 'danger'">
              {{ deviceDetail.devices_enabled === 1 ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatTime(deviceDetail.devices_created) }}</el-descriptions-item>
          <el-descriptions-item label="最后通信">{{ formatTime(deviceDetail.devices_last_request_time) }}</el-descriptions-item>
          <el-descriptions-item label="设备描述" :span="2">
            {{ deviceDetail.devices_description || '暂无描述' }}
          </el-descriptions-item>
          <el-descriptions-item label="当前回路状态" :span="2">
            <div class="circuit-detail-status" :style="getDetailGridStyle()">
              <div v-for="i in getCircuitCount(deviceDetail)" :key="i" class="circuit-detail-item">
                <div class="circuit-detail-info">
                  <div class="circuit-detail-name">{{ getCircuitName(deviceDetail.devices_json_object, i) }}</div>
                  <el-tag
                      size="large"
                      :type="getCircuitStatus(deviceDetail.devices_json_object, i) ? 'success' : 'info'"
                      class="circuit-detail-tag"
                  >
                    <el-icon><Lightning v-if="getCircuitStatus(deviceDetail.devices_json_object, i)" /><Close v-else /></el-icon>
                    回路{{ i }}: {{ getCircuitStatus(deviceDetail.devices_json_object, i) ? '开启' : '关闭' }}
                  </el-tag>
                </div>
              </div>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </el-dialog>
    </div>
  </template>

  <script setup name="Zm">
  import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
  import {
    Monitor, OfficeBuilding, Location, House,
    CircleCheck, CircleClose, Lightning, Close, Clock,
    Check, Search, Refresh
  } from '@element-plus/icons-vue'

  const { proxy } = getCurrentInstance()

  // 照明监控查询相关
  const lightingQuery = reactive({
    currentPage: 1,
    pageSize: 20,
    gateway_id: null,
    query: '',
    devices_enabled: -1
  })

  const lightingList = ref([])
  const lightingTotal = ref(0)
  const lightingLoading = ref(false)
  const gatewayList = ref([])

  // 防抖定时器
  let searchTimer = null

  // 设备控制相关
  const controlVisible = ref(false)
  const controlLoading = ref(false)
  const controlForm = reactive({
    deviceId: null,
    deviceName: '',
    deviceType: '',
    location: '',
    deviceJsonObject: '',
    deviceUdid: '', // 添加设备UDID
    circuitCount: 0,
    circuits: {},
    originalCircuits: {} // 添加原始状态跟踪(修改回路 提交修改的回路其余的不提交)
  })

  // 设备详情相关
  const detailVisible = ref(false)
  const deviceDetail = ref({})

  // 生成UUID
  function generateUUID() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      const r = Math.random() * 16 | 0
      const v = c === 'x' ? r : (r & 0x3 | 0x8)
      return v.toString(16)
    })
  }

  // 判断设备在线状态
  function getDeviceOnlineStatus(device) {
    if (!device.devices_last_request_time) return false
    const lastRequestTime = new Date(device.devices_last_request_time)
    const now = new Date()
    const diffMinutes = (now - lastRequestTime) / (1000 * 60)
    return diffMinutes <= 10
  }

  // 获取设备回路数量
  function getCircuitCount(device) {
    try {
      if (!device.devices_json_object) return 0
      const obj = JSON.parse(device.devices_json_object)
      let count = 0
      // 查找最大的tag数字
      for (let key in obj) {
        if (key.startsWith('tag')) {
          const num = parseInt(key.replace('tag', ''))
          if (!isNaN(num) && num > count) {
            count = num
          }
        }
      }
      return count
    } catch (error) {
      return 0
    }
  }

  // 获取回路网格样式
  function getCircuitGridStyle(device) {
    const count = getCircuitCount(device)
    if (count <= 4) {
      return { gridTemplateColumns: `repeat(${count}, 1fr)` }
    } else if (count <= 8) {
      return { gridTemplateColumns: 'repeat(4, 1fr)' }
    } else if (count <= 12) {
      return { gridTemplateColumns: 'repeat(4, 1fr)' }
    } else {
      return { gridTemplateColumns: 'repeat(5, 1fr)' }
    }
  }

  // 获取控制对话框网格样式
  function getControlGridStyle() {
    const count = controlForm.circuitCount
    if (count <= 4) {
      return { gridTemplateColumns: `repeat(${count}, 1fr)` }
    } else if (count <= 8) {
      return { gridTemplateColumns: 'repeat(4, 1fr)' }
    } else if (count <= 12) {
      return { gridTemplateColumns: 'repeat(4, 1fr)' }
    } else if (count <= 16) {
      return { gridTemplateColumns: 'repeat(4, 1fr)' }
    } else {
      return { gridTemplateColumns: 'repeat(5, 1fr)' }
    }
  }

  // 获取详情对话框网格样式
  function getDetailGridStyle() {
    const count = getCircuitCount(deviceDetail.value)
    if (count <= 2) {
      return { gridTemplateColumns: `repeat(${count}, 1fr)` }
    } else if (count <= 4) {
      return { gridTemplateColumns: 'repeat(2, 1fr)' }
    } else if (count <= 8) {
      return { gridTemplateColumns: 'repeat(2, 1fr)' }
    } else {
      return { gridTemplateColumns: 'repeat(3, 1fr)' }
    }
  }

  // 获取网关列表
  async function getGatewayList() {
    try {
      const res = await request({
        url: `${__LOCAL_API__}/illuminating/gatewayFind`,
        method: 'get'
      })
      if (res.code === 200) {
        gatewayList.value = res.data.gatewayAndBacnet || []
      } else {
        proxy.$modal.msgError('获取网关列表失败')
      }
    } catch (error) {
      proxy.$modal.msgError('获取网关列表失败')
    }
  }

  // 查询照明设备列表
  async function getLightingList() {
    lightingLoading.value = true
    try {
      const formData = new FormData()
      formData.append('currentPage', lightingQuery.currentPage)
      formData.append('pageSize', lightingQuery.pageSize)
      formData.append('devices_enabled', lightingQuery.devices_enabled)

      if (lightingQuery.gateway_id !== null && lightingQuery.gateway_id !== '') {
        formData.append('gateway_id', lightingQuery.gateway_id)
      }

      if (lightingQuery.query && lightingQuery.query.trim() !== '') {
        formData.append('query', lightingQuery.query.trim())
      }

      const res = await request({
        url: `${__LOCAL_API__}/illuminating/getBaseecic`,
        method: 'post',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })

      if (res.code === 200) {
        lightingList.value = res.data.devices || []
        lightingTotal.value = res.data.count || 0
      } else {
        proxy.$modal.msgError(res.message || '获取设备列表失败')
      }
    } catch (error) {
      proxy.$modal.msgError('获取设备列表失败')
    } finally {
      lightingLoading.value = false
    }
  }

  // 网关变化处理
  function handleGatewayChange() {
    lightingQuery.currentPage = 1
    getLightingList()
  }

  // 搜索输入处理（防抖）
  function handleQueryInput() {
    if (searchTimer) {
      clearTimeout(searchTimer)
    }
    searchTimer = setTimeout(() => {
      lightingQuery.currentPage = 1
      getLightingList()
    }, 500)
  }

  // 清空搜索处理
  function handleQueryClear() {
    lightingQuery.currentPage = 1
    getLightingList()
  }

  // 页码变化处理
  function handleCurrentPageChange() {
    getLightingList()
  }

  // 页大小变化处理
  function handlePageSizeChange() {
    lightingQuery.currentPage = 1
    getLightingList()
  }

  // 重置查询条件
  function resetLightingQuery() {
    Object.assign(lightingQuery, {
      currentPage: 1,
      pageSize: 20,
      gateway_id: null,
      query: '',
      devices_enabled: -1
    })
    getLightingList()
  }

  // 解析JSON对象获取回路状态
  function getCircuitStatus(jsonStr, index) {
    try {
      if (!jsonStr) return 0
      const obj = JSON.parse(jsonStr)
      return obj[`tag${index}`] === 1 ? 1 : 0
    } catch (error) {
      return 0
    }
  }

  // 获取回路名称
  function getCircuitName(jsonStr, index) {
    try {
      if (!jsonStr) return `回路${index}`
      const obj = JSON.parse(jsonStr)
      return obj[`name${index}`] || `回路${index}`
    } catch (error) {
      return `回路${index}`
    }
  }

  // 设备控制
  function handleDeviceControl(row) {
    controlForm.deviceId = row.devices_id
    controlForm.deviceName = row.devices_name
    controlForm.deviceType = row.devices_type_name
    controlForm.deviceUdid = row.devices_udid
    controlForm.location = `${row.building_name} / ${row.full_region_name}${row.room_name ? ' / ' + row.room_name : ''}`
    controlForm.deviceJsonObject = row.devices_json_object
    controlForm.circuitCount = getCircuitCount(row)

    // 重置circuits对象
    controlForm.circuits = {}
    controlForm.originalCircuits = {} // 重置原始状态

    try {
      const deviceStatus = JSON.parse(row.devices_json_object || '{}')
      for (let i = 1; i <= controlForm.circuitCount; i++) {
        const status = deviceStatus[`tag${i}`] || 0
        controlForm.circuits[`tag${i}`] = status
        controlForm.originalCircuits[`tag${i}`] = status // 保存原始状态
      }
    } catch (error) {
      for (let i = 1; i <= controlForm.circuitCount; i++) {
        controlForm.circuits[`tag${i}`] = 0
        controlForm.originalCircuits[`tag${i}`] = 0 // 保存原始状态
      }
    }

    controlVisible.value = true
  }

  // 检测变更的回路
  function getChangedCircuits() {
    const changedCircuits = {}
    for (let i = 1; i <= controlForm.circuitCount; i++) {
      const tagKey = `tag${i}`
      if (controlForm.circuits[tagKey] !== controlForm.originalCircuits[tagKey]) {
        changedCircuits[tagKey] = controlForm.circuits[tagKey]
      }
    }
    return changedCircuits
  }

  // 检查是否有变更
  function hasChanges() {
    for (let i = 1; i <= controlForm.circuitCount; i++) {
      const tagKey = `tag${i}`
      if (controlForm.circuits[tagKey] !== controlForm.originalCircuits[tagKey]) {
        return true
      }
    }
    return false
  }

  // 设置所有回路
  function setAllCircuits(value) {
    for (let i = 1; i <= controlForm.circuitCount; i++) {
      controlForm.circuits[`tag${i}`] = value
    }
  }

  // 添加重置到原始状态的函数
  function resetToOriginal() {
    for (let i = 1; i <= controlForm.circuitCount; i++) {
      const tagKey = `tag${i}`
      controlForm.circuits[tagKey] = controlForm.originalCircuits[tagKey]
    }
  }

  // 提交控制
  async function submitControl() {
    // 检查是否有变更
    if (!hasChanges()) {
      proxy.$modal.msgWarning('没有检测到任何变更')
      return
    }

    // 获取变更的回路
    const changedCircuits = getChangedCircuits()
    const changedCount = Object.keys(changedCircuits).length

    // 确认提交
    const confirmResult = await proxy.$modal.confirm(
        `检测到 ${changedCount} 个回路状态发生变更，是否确认提交？`,
        '确认控制',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
    ).catch(() => false)

    if (!confirmResult) return

    controlLoading.value = true
    try {
      const requestData = {
        udid: controlForm.deviceUdid,
        source: 1,
        agreement_json: JSON.stringify(changedCircuits) // 只提交变更的回路
      }

      console.log('提交的变更回路:', changedCircuits)

      const res = await request({
        url: `${__LOCAL_API__}/illuminating/devicesControl`,
        method: 'post',
        data: requestData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })

      if (res.code === 200) {
        proxy.$modal.msgSuccess(`控制指令已发送，变更了 ${changedCount} 个回路`)
        controlVisible.value = false
        // 延迟刷新列表，给设备一些响应时间
        setTimeout(() => {
          getLightingList()
        }, 1000)
      } else {
        proxy.$modal.msgError(res.message || '控制失败')
      }
    } catch (error) {
      console.error('设备控制失败:', error)
      proxy.$modal.msgError('控制失败')
    } finally {
      controlLoading.value = false
    }
  }

  // 查看设备详情
  function handleDeviceDetail(row) {
    deviceDetail.value = { ...row }
    detailVisible.value = true
  }

  // 表格行样式
  function tableRowClassName({ row }) {
    if (!getDeviceOnlineStatus(row)) {
      return 'offline-row'
    }
    if (row.devices_enabled === 0) {
      return 'disabled-row'
    }
    return ''
  }

  // 时间格式化
  function formatTime(time) {
    if (!time) return '-'
    try {
      const date = new Date(time)
      const Y = date.getFullYear()
      const M = (date.getMonth() + 1).toString().padStart(2, '0')
      const D = date.getDate().toString().padStart(2, '0')
      const h = date.getHours().toString().padStart(2, '0')
      const m = date.getMinutes().toString().padStart(2, '0')
      const s = date.getSeconds().toString().padStart(2, '0')
      return `${Y}-${M}-${D} ${h}:${m}:${s}`
    } catch (error) {
      return '-'
    }
  }

  // 导入request工具
  import request from '@/utils/request'

  // 初始化
  onMounted(async () => {
    await getGatewayList()
    await getLightingList()

    // 设置定时刷新
    /*setInterval(() => {
      getLightingList()
    }, 60000)*/
  })
  </script>

  <style scoped>

  .change-indicator {
    margin-top: 8px;
    display: flex;
    align-items: center;
    gap: 4px;
  }

  .change-indicator .el-tag {
    display: flex;
    align-items: center;
    gap: 4px;
  }
  .app-container {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: 90vh;
  }

  /* 卡片样式 */
  .search-card, .table-card {
    margin-bottom: 20px;
    border-radius: 12px;
    border: none;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  }

  .search-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
  }

  .search-card :deep(.el-form-item__label) {
    color: white;
    font-weight: 500;
  }

  .search-card :deep(.el-input__wrapper) {
    box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.3) inset;
  }

  .search-card :deep(.el-select .el-input__wrapper) {
    box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.3) inset;
  }

  .table-card {
    padding: 0;
    background: white;
  }

  /* 网关选择器样式 */
  .gateway-option {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
  }

  .gateway-name {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .gateway-status {
    margin-left: 8px;
  }

  /* 设备信息样式 */
  .device-info {
    padding: 12px 0;
  }

  .device-name {
    display: flex;
    align-items: center;
    font-weight: 600;
    color: #303133;
    margin-bottom: 6px;
    font-size: 15px;
  }

  .device-icon {
    margin-right: 8px;
    color: #409eff;
    font-size: 16px;
  }

  .device-code {
    font-size: 12px;
    color: #909399;
    font-family: 'Courier New', monospace;
    margin-bottom: 6px;
    background: #f5f7fa;
    padding: 2px 6px;
    border-radius: 4px;
    display: inline-block;
  }

  /* 位置信息样式 */
  .location-info {
    padding: 12px 0;
  }

  .location-info > div {
    display: flex;
    align-items: center;
    margin-bottom: 6px;
    font-size: 13px;
    color: #606266;
  }

  .location-info .el-icon {
    margin-right: 8px;
    color: #909399;
    font-size: 14px;
  }

  .building {
    font-weight: 600;
    color: #303133;
  }

  /* 网关信息样式 */
  .gateway-info {
    padding: 12px 0;
    text-align: center;
  }

  .gateway-name {
    font-weight: 500;
    color: #303133;
    font-size: 14px;
  }

  /* 设备状态样式 */
  .device-status {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
  }

  .status-tag {
    display: flex;
    align-items: center;
    font-weight: 500;
  }

  .status-tag .el-icon {
    margin-right: 4px;
  }

  .device-switch {
    margin-top: 6px;
  }

  /* 回路状态样式 */
  .circuit-status {
    display: grid;
    gap: 8px;
    padding: 12px;
    min-height: 80px;
    max-height: 200px;
    overflow-y: auto;
  }

  .circuit-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 6px;
    background: #f8f9fa;
    border-radius: 6px;
    transition: all 0.3s;
    cursor: default;
    min-width: 50px;
    min-height: 60px;
  }

  .circuit-item.clickable {
    cursor: pointer;
    border: 2px solid transparent;
  }

  .circuit-item.clickable:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    border-color: #409eff;
    background: white;
  }

  .circuit-name {
    font-size: 10px;
    color: #666;
    margin-bottom: 3px;
    text-align: center;
    line-height: 1.1;
    max-width: 70px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .circuit-tag {
    display: flex;
    align-items: center;
    min-width: 35px;
    justify-content: center;
    font-weight: 500;
    font-size: 11px;
    padding: 2px 4px;
  }

  .circuit-tag .el-icon {
    margin-right: 2px;
    font-size: 10px;
  }

  /* 时间信息样式 */
  .time-info {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    color: #606266;
  }

  .time-info .el-icon {
    margin-right: 6px;
    color: #909399;
  }

  /* 操作按钮样式 */
  .action-buttons {
    display: flex;
    gap: 8px;
    justify-content: center;
    align-items: center;
  }

  .action-btn {
    min-width: 60px;
    height: 32px;
    border-radius: 6px;
    font-weight: 500;
    font-size: 12px;
    transition: all 0.3s ease;
    border: 1px solid transparent;
  }

  .control-btn {
    background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
    color: white;
    border: none;
  }

  .control-btn:hover:not(:disabled) {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
  }

  .control-btn:disabled {
    background: #c0c4cc;
    color: #ffffff;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
  }

  .detail-btn {
    background: linear-gradient(135deg, #909399 0%, #a6a9ad 100%);
    color: white;
    border: none;
  }

  .detail-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(144, 147, 153, 0.4);
  }

  /* 表格样式 */
  :deep(.el-table) {
    border-radius: 12px;
    overflow: hidden;
    border: none;
  }

  :deep(.el-table th) {
    background: linear-gradient(135deg, #f8f9fa 100%, #e9ecef 100%);
    color: #303133;
    font-weight: 600;
    border: none;
    padding: 12px 12px;
  }

  :deep(.el-table td) {
    border-bottom: 1px solid #f0f2f5;
  }

  :deep(.el-table tr:hover > td) {
    background-color: #f8f9fa;
  }

  :deep(.el-table .offline-row) {
    background-color: #fef0f0;
  }

  :deep(.el-table .offline-row:hover > td) {
    background-color: #fde2e2;
  }

  :deep(.el-table .disabled-row) {
    background-color: #f5f5f5;
  }

  :deep(.el-table .disabled-row:hover > td) {
    background-color: #eeeeee;
  }

  /* 控制对话框样式 */
  .circuit-control-grid {
    display: grid;
    gap: 16px;
    padding: 16px;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-radius: 12px;
    border: 1px solid #e4e7ed;
    max-height: 500px;
    overflow-y: auto;
  }

  .circuit-control-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 16px;
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
    border: 2px solid transparent;
    min-height: 120px;
  }

  .circuit-control-item:hover {
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
    border-color: #409eff;
  }

  .circuit-label {
    text-align: center;
    margin-bottom: 10px;
  }

  .circuit-number {
    font-size: 14px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 3px;
  }

  .circuit-desc {
    font-size: 11px;
    color: #666;
    line-height: 1.2;
    max-width: 80px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  /* 设备详情样式 */
  .device-code-text {
    font-family: 'Courier New', monospace;
    font-size: 12px;
    color: #606266;
    background-color: #f5f7fa;
    padding: 6px 10px;
    border-radius: 6px;
    border: 1px solid #e4e7ed;
  }

  .circuit-detail-status {
    display: grid;
    gap: 10px;
    padding: 12px;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-radius: 8px;
    max-height: 500px;
    overflow-y: auto;
  }

  .circuit-detail-item {
    background: white;
    padding: 10px;
    border-radius: 6px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  .circuit-detail-info {
    display: flex;
    flex-direction: column;
    gap: 6px;
  }

  .circuit-detail-name {
    font-size: 12px;
    color: #666;
    font-weight: 500;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .circuit-detail-tag {
    display: flex;
    align-items: center;
    padding: 6px 10px;
    border-radius: 5px;
    font-weight: 500;
    font-size: 12px;
  }

  .circuit-detail-tag .el-icon {
    margin-right: 4px;
    font-size: 12px;
  }

  /* 分页样式 */
  .pagination-container {
    display: flex;
    justify-content: flex-end;
    padding: 20px;
    background-color: #fff;
    border-top: 1px solid #f0f2f5;
  }

  /* 对话框样式 */
  :deep(.el-dialog) {
    border-radius: 12px;
    overflow: hidden;
  }

  :deep(.el-dialog__header) {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 20px;
  }

  :deep(.el-dialog__title) {
    color: white;
    font-weight: 600;
  }

  :deep(.el-dialog__headerbtn .el-dialog__close) {
    color: white;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding: 20px;
    background: #f8f9fa;
    margin: 0 -20px -20px -20px;
  }

  /* 按钮样式优化 */
  .el-button {
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.3s ease;
  }

  .el-button:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }

  .el-button--primary {
    background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
    border: none;
  }

  .el-button--success {
    background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
    border: none;
  }

  .el-button--warning {
    background: linear-gradient(135deg, #e6a23c 0%, #ebb563 100%);
    border: none;
  }

  .el-button--info {
    background: linear-gradient(135deg, #909399 0%, #a6a9ad 100%);
    border: none;
  }

  /* 标签样式优化 */
  .el-tag {
    border: none;
    font-weight: 500;
    border-radius: 6px;
    padding: 4px 8px;
  }

  .el-tag--success {
    background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
    color: #059669;
    border: 1px solid #a7f3d0;
  }

  .el-tag--danger {
    background: linear-gradient(135deg, #fef2f2 0%, #fee2e2 100%);
    color: #dc2626;
    border: 1px solid #fca5a5;
  }

  .el-tag--info {
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    color: #64748b;
    border: 1px solid #cbd5e1;
  }

  .el-tag--primary {
    background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
    color: #2563eb;
    border: 1px solid #93c5fd;
  }

  /* 开关样式优化 */
  :deep(.el-switch) {
    --el-switch-on-color: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
    --el-switch-off-color: #dcdfe6;
  }

  :deep(.el-switch.is-checked .el-switch__core) {
    background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
    border-color: #67c23a;
  }

  /* 描述列表样式优化 */
  :deep(.el-descriptions) {
    border-radius: 8px;
    overflow: hidden;
  }

  :deep(.el-descriptions__label) {
    font-weight: 600;
    color: #374151;
    background: linear-gradient(135deg, #f9fafb 0%, #f3f4f6 100%);
  }

  :deep(.el-descriptions__content) {
    color: #111827;
    background: white;
  }

  /* 表单样式优化 */
  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #374151;
  }

  :deep(.el-input__wrapper) {
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    transition: all 0.3s;
  }

  :deep(.el-input__wrapper:hover) {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  }

  :deep(.el-input__wrapper.is-focus) {
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  }

  :deep(.el-select .el-input__wrapper) {
    border-radius: 8px;
  }

  /* 响应式设计 */
  @media (max-width: 1200px) {
    .circuit-control-grid {
      grid-template-columns: repeat(3, 1fr) !important;
      gap: 12px;
    }

    .circuit-status {
      grid-template-columns: repeat(3, 1fr) !important;
      gap: 6px;
    }
  }

  @media (max-width: 768px) {
    .app-container {
      padding: 10px;
    }

    .circuit-control-grid {
      grid-template-columns: repeat(2, 1fr) !important;
      gap: 10px;
      padding: 12px;
    }

    .circuit-status {
      grid-template-columns: repeat(2, 1fr) !important;
      gap: 4px;
      padding: 8px;
    }

    .circuit-detail-status {
      grid-template-columns: 1fr !important;
    }

    .action-buttons {
      flex-direction: column;
      gap: 4px;
    }

    .action-btn {
      width: 100%;
      min-width: auto;
    }

    .circuit-control-item {
      padding: 12px;
      min-height: 100px;
    }

    .circuit-item {
      padding: 4px;
      min-width: 40px;
      min-height: 50px;
    }

    .circuit-name {
      font-size: 9px;
      max-width: 60px;
    }

    .circuit-tag {
      font-size: 10px;
      min-width: 30px;
    }
  }

  @media (max-width: 480px) {
    .circuit-control-grid {
      grid-template-columns: 1fr !important;
    }

    .circuit-status {
      grid-template-columns: repeat(2, 1fr) !important;
    }
  }

  /* 为12路及以上设备添加特殊样式 */
  .circuit-status[style*="repeat(4, 1fr)"] .circuit-item {
    min-width: 45px;
    padding: 5px;
  }

  .circuit-status[style*="repeat(4, 1fr)"] .circuit-name {
    font-size: 9px;
    max-width: 65px;
  }

  .circuit-status[style*="repeat(4, 1fr)"] .circuit-tag {
    font-size: 10px;
    min-width: 32px;
  }

  /* 控制对话框滚动条样式 */
  .circuit-control-grid::-webkit-scrollbar,
  .circuit-detail-status::-webkit-scrollbar,
  .circuit-status::-webkit-scrollbar {
    width: 6px;
  }

  .circuit-control-grid::-webkit-scrollbar-track,
  .circuit-detail-status::-webkit-scrollbar-track,
  .circuit-status::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
  }

  .circuit-control-grid::-webkit-scrollbar-thumb,
  .circuit-detail-status::-webkit-scrollbar-thumb,
  .circuit-status::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
  }

  .circuit-control-grid::-webkit-scrollbar-thumb:hover,
  .circuit-detail-status::-webkit-scrollbar-thumb:hover,
  .circuit-status::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
  }

  /* 滚动条样式 */
  ::-webkit-scrollbar {
    width: 8px;
    height: 8px;
  }

  ::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
  }

  ::-webkit-scrollbar-thumb {
    background: linear-gradient(135deg, #c1c1c1 0%, #a8a8a8 100%);
    border-radius: 4px;
  }

  ::-webkit-scrollbar-thumb:hover {
    background: linear-gradient(135deg, #a8a8a8 0%, #909090 100%);
  }

  /* 加载动画优化 */
  :deep(.el-loading-mask) {
    border-radius: 12px;
    background: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(4px);
  }

  /* 动画效果 */
  .el-card {
    transition: all 0.3s ease;
  }

  .el-card:hover {
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  }

  /* 分页器样式优化 */
  :deep(.el-pagination) {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  :deep(.el-pagination .btn-prev),
  :deep(.el-pagination .btn-next) {
    border-radius: 8px;
    border: 1px solid #e4e7ed;
    transition: all 0.3s;
  }

  :deep(.el-pagination .btn-prev:hover),
  :deep(.el-pagination .btn-next:hover) {
    border-color: #409eff;
    color: #409eff;
    box-shadow: 0 2px 4px rgba(64, 158, 255, 0.2);
  }

  :deep(.el-pager li) {
    border-radius: 8px;
    margin: 0 2px;
    transition: all 0.3s;
  }

  :deep(.el-pager li:hover) {
    background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
    color: #409eff;
  }

  :deep(.el-pager li.is-active) {
    background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
    color: white;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
  }

  /* 表格选择框样式 */
  :deep(.el-table .el-checkbox) {
    transform: scale(1.1);
  }

  :deep(.el-table .el-checkbox__input.is-checked .el-checkbox__inner) {
    background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
    border-color: #409eff;
  }

  /* 下拉菜单样式 */
  :deep(.el-select-dropdown) {
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    border: none;
  }

  :deep(.el-select-dropdown__item) {
    border-radius: 4px;
    margin: 2px 8px;
    transition: all 0.3s;
  }

  :deep(.el-select-dropdown__item:hover) {
    background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
    color: #409eff;
  }

  /* 分割线样式 */
  :deep(.el-divider) {
    border-color: #e4e7ed;
    margin: 24px 0;
  }

  :deep(.el-divider__text) {
    background: white;
    color: #303133;
    font-weight: 500;
    padding: 0 20px;
  }

  /* 脉冲动画（用于在线状态指示） */
  @keyframes pulse {
    0% {
      box-shadow: 0 0 0 0 rgba(103, 194, 58, 0.7);
    }
    70% {
      box-shadow: 0 0 0 10px rgba(103, 194, 58, 0);
    }
    100% {
      box-shadow: 0 0 0 0 rgba(103, 194, 58, 0);
    }
  }

  .status-tag.el-tag--success {
    animation: pulse 2s infinite;
  }

  /* 控制成功提示样式 */
  .control-success {
    background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
    border: 1px solid #93c5fd;
    color: #1e40af;
  }

  /* 控制失败提示样式 */
  .control-error {
    background: linear-gradient(135deg, #fef2f2 0%, #fee2e2 100%);
    border: 1px solid #fca5a5;
    color: #dc2626;
  }

  /* 加载状态样式 */
  .loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 8px;
    z-index: 10;
  }

  /* 控制按钮加载状态 */
  .control-btn.is-loading {
    pointer-events: none;
    opacity: 0.6;
  }

  /* 回路项点击反馈 */
  .circuit-item.clickable:active {
    transform: translateY(0);
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  }

  /* 设备离线时的样式 */
  .device-offline .circuit-item {
    opacity: 0.5;
    cursor: not-allowed;
  }

  .device-offline .circuit-item:hover {
    transform: none;
    box-shadow: none;
    border-color: transparent;
  }

  /* 设备禁用时的样式 */
  .device-disabled .circuit-item {
    opacity: 0.3;
    cursor: not-allowed;
  }

  .device-disabled .circuit-item:hover {
    transform: none;
    box-shadow: none;
    border-color: transparent;
  }
  </style>
