<template>
  <div class="dashboard">
    <div class="header">
      <div class="logo">
        <div class="logo-icon">
          <i class="fas fa-microchip"></i>
          <UngroupOutlined />
        </div>
        <div class="logo-text">{{ communityName }} 设备树</div>
      </div>

      <div class="stats">
        <div class="stat-card online">
          <div class="stat-value">{{ onlineCount }}</div>
          <div class="stat-label">在线设备</div>
        </div>
        <div class="stat-card offline">
          <div class="stat-value">{{ offlineCount }}</div>
          <div class="stat-label">离线设备</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{ totalDevices }}</div>
          <div class="stat-label">设备总数</div>
        </div>
      </div>
    </div>

    <div class="content">
      <div class="treebar tree-panel">
        <div class="head">
          <div class="head-title">{{ communityName }}</div>
          <div class="head-extra">
            <a-space :size="0">
              <a-button type="link" size="small" @click="addBulidingHandler">新增楼栋</a-button>
            </a-space>
          </div>
        </div>

        <div class="search-box">
          <input v-model="searchValue" placeholder="请输入关键字搜索" />
        </div>

        <a-skeleton :loading="loading">
          <a-tree
            v-if="hasBuilding"
            block-node
            :expanded-keys="expandedKeys"
            :auto-expand-parent="autoExpandParent"
            :tree-data="treeData"
            @expand="onExpand"
            @select="onSelect"
          >
            <template #title="{ title, parentId, tenantId, tinfoId }">
              <div class="treeItem">
                <div class="treeItem-title">
                  <span v-if="title.indexOf(searchValue) > -1">
                    {{ title.substring(0, title.indexOf(searchValue)) }}
                    <span style="color: #f50">{{ searchValue }}</span>
                    {{ title.substring(title.indexOf(searchValue) + searchValue.length) }}
                  </span>
                  <span v-else>{{ title }}</span>
                </div>
                <div
                  v-if="!parentId"
                  class="treeItem-extra"
                  @click.stop="addFloorHandler(tenantId, tinfoId, title)"
                  >新增楼层</div
                >
              </div>
            </template>
          </a-tree>

          <div v-else class="tips">
            <div class="text">
              该小区暂无楼栋
              <span
                >，立即<a-button type="link" size="small" @click="addBulidingHandler"
                  >新增楼栋></a-button
                ></span
              >
            </div>
          </div>
        </a-skeleton>
      </div>

      <div class="devices-panel">
        <div class="panel-header">
          <div class="panel-title">
            <i class="fas fa-server"></i>
            <span>设备列表 ({{ filteredDevices.length }})</span>
          </div>

          <div class="filters">
            <div
              class="filter-btn"
              :class="{ active: currentFilter === 'all' }"
              @click="currentFilter = 'all'"
            >
              全部设备
            </div>
            <div
              class="filter-btn"
              :class="{ active: currentFilter === 'online' }"
              @click="currentFilter = 'online'"
            >
              在线设备
            </div>
            <div
              class="filter-btn"
              :class="{ active: currentFilter === 'offline' }"
              @click="currentFilter = 'offline'"
            >
              离线设备
            </div>
          </div>
        </div>

        <div class="devices-grid">
          <div
            v-for="device in filteredDevices"
            :key="device.id"
            class="device-card"
            :class="device.status"
            @click="selectDeviceView(device.devId, device.clientId)"
          >
            <div class="status-indicator"></div>

            <div class="device-icon">
              <i :class="device.icon"></i>
              <HddOutlined />
            </div>

            <div class="device-name">{{ device.name }}</div>
            <div class="device-tag">{{ device.location }}</div>

            <div class="device-info">
              <div class="info-row">
                <span class="info-label">设备ID：</span>
                <span class="info-value">{{ device.id }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">IP地址：</span>
                <span class="info-value">{{ device.ip }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">最后活动：</span>
                <span class="info-value">{{ device.lastActive }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">CPU使用：</span>
                <span
                  class="info-value"
                  :style="{
                    color:
                      device.status === 'online'
                        ? device.cpu > 70
                          ? '#f87171'
                          : '#4ade80'
                        : '#94a3b8',
                  }"
                >
                  {{ device.status === 'online' ? `${device.cpu}%` : '--' }}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <add-build-modal
      v-model:open="addBuildOpen"
      :type="buildType"
      :query="buildQuery"
      @success="getCommunityDetail"
    ></add-build-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import * as tenantApi from '@/api/tenant'
import type { TenantInfoData } from '@/api/tenant/types'
import { message, type TreeProps } from 'ant-design-vue'
import type { DataNode } from 'ant-design-vue/es/tree'
import { HddOutlined, UngroupOutlined } from '@ant-design/icons-vue'
import addBuildModal from './components/addBuild/index.vue'

defineOptions({
  name: 'CommunityDetail',
})
const route = useRoute()
const router = useRouter()
const expandedKeys = ref<(string | number)[]>([])
const searchValue = ref<string>('')
const autoExpandParent = ref<boolean>(true)
const treeData = ref<TreeProps['treeData']>([])
const communityName = ref<string>((route.query.name as string) || '')

const onExpand = (keys: string[]) => {
  console.log('onExpand', keys)
  expandedKeys.value = keys
  autoExpandParent.value = false
}

const onSelect = (selectedKeys: string[], options: any) => {
  console.log(
    'onSelect',
    selectedKeys,
    options,
    options.node?.dataRef,
    options.node?.parent?.node?.title
  )
  const buildName = options.node?.parent?.node?.title || ''
  const unitName = options.node?.dataRef?.title || ''
  message.info(`选中了:${buildName} ${unitName}`)
}

// 设备数据
const devices = ref([
  {
    id: 'DEV-001',
    name: '核心路由器',
    status: 'online',
    icon: 'fas fa-route',
    location: '网络设备区',
    ip: '192.168.1.1',
    lastActive: '2分钟前',
    cpu: 24,
    nodeId: '1-1-1',
  },
  {
    id: 'DEV-002',
    name: '数据库服务器',
    status: 'online',
    icon: 'fas fa-database',
    location: '服务器区',
    ip: '192.168.2.10',
    lastActive: '1分钟前',
    cpu: 65,
    nodeId: '1-2-1',
  },
  {
    id: 'DEV-003',
    name: '防火墙主节点',
    status: 'offline',
    icon: 'fas fa-fire',
    location: '安全设备区',
    ip: '192.168.3.5',
    lastActive: '3小时前',
    cpu: 0,
    nodeId: '1-3-1',
  },
  {
    id: 'DEV-004',
    name: '负载均衡器',
    status: 'online',
    icon: 'fas fa-balance-scale',
    location: '网络设备区',
    ip: '192.168.1.15',
    lastActive: '30秒前',
    cpu: 42,
    nodeId: '1-1-2',
  },
  {
    id: 'DEV-005',
    name: '应用服务器集群',
    status: 'online',
    icon: 'fas fa-server',
    location: '服务器区',
    ip: '192.168.2.20',
    lastActive: '5分钟前',
    cpu: 78,
    nodeId: '1-2-2',
  },
  {
    id: 'DEV-006',
    name: '备份存储设备',
    status: 'offline',
    icon: 'fas fa-hard-drive',
    location: '服务器区',
    ip: '192.168.2.30',
    lastActive: '12小时前',
    cpu: 0,
    nodeId: '1-2-3',
  },
  {
    id: 'DEV-007',
    name: '入侵检测系统',
    status: 'online',
    icon: 'fas fa-shield-alt',
    location: '安全设备区',
    ip: '192.168.3.10',
    lastActive: '1分钟前',
    cpu: 18,
    nodeId: '1-3-1',
  },
  {
    id: 'DEV-008',
    name: 'VPN网关',
    status: 'online',
    icon: 'fas fa-user-shield',
    location: '安全设备区',
    ip: '192.168.3.15',
    lastActive: '10分钟前',
    cpu: 32,
    nodeId: '1-3-2',
  },
])

// 将接口数据进行转换，符合antd tree组件的格式
const convertTreeData = (node: TenantInfoData): DataNode => {
  const result = {
    title: node.tinfoName,
    key: node.tinfoId,
    tinfoId: node.tinfoId,
    tenantId: node.tenantId,
    parentId: node.parentId,
    children: node.children?.map((child: TenantInfoData) => convertTreeData(child)) || null,
  }
  return result
}

// 是否存在楼栋
const hasBuilding = computed(() => treeData.value && treeData.value.length > 0)

const loading = ref(false)
// 获取小区详情
const getCommunityDetail = async () => {
  loading.value = true
  try {
    const res = await tenantApi.queryTenantInfo({
      tenantId: route.query.tenantId as string,
    })
    treeData.value = res.data.map((item) => {
      return convertTreeData(item)
    })
    console.log(res)
  } catch (error) {
    console.log(error)
  }
  loading.value = false
}
getCommunityDetail()

const addBuildOpen = ref(false)
const buildType = ref<'build' | 'floor'>('build')
const buildQuery = ref({
  tenantId: route.query.tenantId as string,
  parentId: '',
})
// 添加楼栋
const addBulidingHandler = () => {
  console.log('添加楼栋', { tenantId: route.query.tenantId })
  buildType.value = 'build'
  buildQuery.value = {
    tenantId: route.query.tenantId as string,
    parentId: '',
  }
  addBuildOpen.value = true
}

// 添加楼层
const addFloorHandler = (tenantId: string, parentId: string, title: string) => {
  console.log(`为 ${title}(tenantId:${tenantId}) 添加楼层`, { tenantId, parentId })
  buildType.value = 'floor'
  buildQuery.value = {
    tenantId,
    parentId,
  }
  addBuildOpen.value = true
}

// 当前过滤状态
const currentFilter = ref('all')

// 计算设备统计
const onlineCount = computed(() => devices.value.filter((d) => d.status === 'online').length)
const offlineCount = computed(() => devices.value.filter((d) => d.status === 'offline').length)
const totalDevices = computed(() => devices.value.length)

// 过滤设备
const filteredDevices = computed(() => {
  // 首先根据当前选中的节点过滤
  let result = devices.value

  if (currentFilter.value === 'online') {
    result = result.filter((d) => d.status === 'online')
  } else if (currentFilter.value === 'offline') {
    result = result.filter((d) => d.status === 'offline')
  }

  return result
})

// 点击某个设备，跳转到设备详情
const selectDeviceView = (devId: string, clientId: string) => {
  console.log('selectDeviceView', devId, clientId)
  router.push({
    name: 'deviceDetail',
    query: {
      devId,
      clientId,
    },
  })
}
</script>

<style scoped lang="less">
@primary: #4e9af1;
@online: #4ade80;
@offline: #f87171;
@bg-dark: #0c162d;
@bg-medium: #1a2a4a;
@bg-card: rgba(16, 24, 48, 0.7);
@text-primary: #e0e7ff;
@text-secondary: #94a3b8;
@border-color: rgba(64, 128, 255, 0.3);
@glow-blue: rgba(78, 154, 241, 0.2);
@glow-purple: rgba(138, 111, 255, 0.2);

.dashboard {
  background: linear-gradient(135deg, @bg-dark 0%, @bg-medium 100%);
  color: @text-primary;
  min-height: 100vh;
  overflow-x: hidden;
  padding: 20px;
  border-radius: 8px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: @bg-card;
  border-bottom: 1px solid @border-color;
  border-radius: 16px;
  backdrop-filter: blur(10px);
  margin-bottom: 25px;
  box-shadow: 0 8px 32px rgba(0, 5, 20, 0.4);
}

.logo {
  display: flex;
  align-items: center;
  gap: 15px;
}

.logo-icon {
  font-size: 28px;
  color: @primary;
  background: rgba(78, 154, 241, 0.15);
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.logo-text {
  font-size: 24px;
  font-weight: 700;
  background: linear-gradient(90deg, @primary, #8a6fff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  letter-spacing: 1px;
}

.stats {
  display: flex;
  gap: 25px;
}

.stat-card {
  background: rgba(20, 30, 60, 0.6);
  border: 1px solid @border-color;
  border-radius: 12px;
  padding: 15px 25px;
  min-width: 150px;
  text-align: center;
  backdrop-filter: blur(5px);
  transition: all 0.3s ease;
}

.stat-card:hover {
  box-shadow: 0 10px 20px rgba(64, 128, 255, 0.2);
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 5px;
}

.online .stat-value {
  color: @online;
  text-shadow: 0 0 10px rgba(74, 222, 128, 0.3);
}

.offline .stat-value {
  color: @offline;
  text-shadow: 0 0 10px rgba(248, 113, 113, 0.3);
}

.stat-label {
  font-size: 14px;
  color: @text-secondary;
}

.content {
  display: flex;
  gap: 25px;
  flex: 1;
}

.tree-panel {
  width: 300px;
  background: @bg-card;
  border-radius: 16px;
  padding: 20px;
  border: 1px solid @border-color;
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0, 5, 20, 0.4);
  height: fit-content;
}

.tree-title {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 18px;
  margin-bottom: 15px;
  color: #a3bffa;
}

.tree-container {
  max-height: 600px;
  overflow-y: auto;
  padding-right: 10px;
}

.tree-container::-webkit-scrollbar {
  width: 6px;
}

.tree-container::-webkit-scrollbar-track {
  background: rgba(16, 24, 48, 0.3);
  border-radius: 10px;
}

.tree-container::-webkit-scrollbar-thumb {
  background: @primary;
  border-radius: 10px;
}

.tree-node {
  padding: 10px 15px;
  margin: 5px 0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 10px;
}

.tree-node:hover {
  background: rgba(64, 128, 255, 0.15);
}

.tree-node.active {
  background: rgba(64, 128, 255, 0.3);
}

.tree-node i {
  color: @primary;
  width: 20px;
  text-align: center;
}

.tree-children {
  padding-left: 25px;
}

.devices-panel {
  flex: 1;
  background: @bg-card;
  border-radius: 16px;
  padding: 25px;
  border: 1px solid @border-color;
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0, 5, 20, 0.4);
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}

.panel-title {
  font-size: 22px;
  font-weight: 600;
  background: linear-gradient(90deg, #a3bffa, #7dd3fc);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  display: flex;
  align-items: center;
  gap: 12px;
}

.filters {
  display: flex;
  gap: 15px;
}

.filter-btn {
  background: rgba(30, 41, 85, 0.6);
  border: 1px solid rgba(64, 128, 255, 0.3);
  color: #a3bffa;
  padding: 8px 16px;
  border-radius: 30px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 6px;
}

.filter-btn.active {
  background: rgba(64, 128, 255, 0.3);
  color: #fff;
  border-color: @primary;
}

.filter-btn:hover {
  background: rgba(64, 128, 255, 0.4);
}

.devices-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 25px;
}

.device-card {
  background: linear-gradient(145deg, rgba(22, 32, 65, 0.8), rgba(12, 20, 45, 0.8));
  border: 1px solid rgba(64, 128, 255, 0.2);
  border-radius: 16px;
  padding: 25px;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
  box-shadow: 0 4px 20px rgba(0, 5, 20, 0.3);
  cursor: pointer;
}

.device-card:hover {
  box-shadow: 0 20px 40px rgba(64, 128, 255, 0.25);
  border-color: rgba(64, 128, 255, 0.4);
}

.device-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  border-radius: 16px 16px 0 0;
}

.device-card.online::before {
  background: linear-gradient(90deg, @online), #22d3ee;
}

.device-card.offline::before {
  background: linear-gradient(90deg, @offline), #fbbf24;
}

.status-indicator {
  position: absolute;
  top: 15px;
  right: 15px;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  box-shadow: 0 0 10px currentColor;
}

.online .status-indicator {
  background-color: @online;
  color: @online;
}

.offline .status-indicator {
  background-color: @offline;
  color: @offline;
}

.device-icon {
  font-size: 42px;
  margin-bottom: 15px;
  background: linear-gradient(135deg, #a3bffa, #7dd3fc);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.online .device-icon {
  background: linear-gradient(135deg, @online), #22d3ee;
  -webkit-background-clip: text;
}

.offline .device-icon {
  background: linear-gradient(135deg, @offline), #fbbf24;
  -webkit-background-clip: text;
}

.device-name {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 8px;
  color: @text-primary;
}

.device-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid rgba(64, 128, 255, 0.1);
}

.info-row {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
}

.info-label {
  color: @text-secondary;
}

.info-value {
  color: @text-primary;
  font-weight: 500;
}

.device-tag {
  display: inline-block;
  background: rgba(64, 128, 255, 0.15);
  color: #a3bffa;
  padding: 4px 10px;
  border-radius: 20px;
  font-size: 12px;
  margin-top: 12px;
}

.online .device-tag {
  background: rgba(74, 222, 128, 0.15);
  color: @online;
}

.offline .device-tag {
  background: rgba(248, 113, 113, 0.15);
  color: @offline;
}

.search-box {
  background: rgba(20, 30, 60, 0.6);
  border: 1px solid @border-color;
  border-radius: 30px;
  padding: 10px 20px;
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.search-box input {
  background: transparent;
  border: none;
  color: @text-primary;
  width: 100%;
  font-size: 14px;
  outline: none;
}

.search-box i {
  color: @primary;
}

@media (max-width: 1200px) {
  .devices-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  }
}

@media (max-width: 992px) {
  .content {
    flex-direction: column;
  }

  .tree-panel {
    width: 100%;
  }
}

@media (max-width: 768px) {
  .devices-grid {
    grid-template-columns: 1fr;
  }

  .stats {
    flex-wrap: wrap;
    justify-content: center;
  }

  .header {
    flex-direction: column;
    gap: 20px;
  }

  .filters {
    flex-wrap: wrap;
  }
}

.treebar {
  flex-shrink: 0;
  width: 300px;
  margin-right: 20px;

  .tips {
    padding: 16px;
    border-radius: 8px;
    .ant-btn-link {
      color: #7dd3fc;
    }
  }

  .head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;

    &-title {
      font-size: 16px;
      font-weight: 600;
    }

    .ant-button {
      padding: 0;
    }
    .ant-btn-link {
      color: #7dd3fc;
    }
  }
}
.treeItem {
  display: flex;
  justify-content: space-between;
  align-items: center;
  &-title {
    flex-grow: 1;
  }
  &-extra {
    color: #7dd3fc;
    cursor: pointer;
    display: none;
  }
  &:hover {
    .treeItem-extra {
      display: block;
    }
  }
}

:deep(.ant-tree) {
  background-color: rgba(16, 24, 48, 0.7);
  color: #e0e7ff;

  .ant-tree-node-content-wrapper {
    font-size: 14px;
  }

  .ant-tree-node-content-wrapper.ant-tree-node-selected,
  :where(.css-dev-only-do-not-override-1p3hq3p).ant-tree
    .ant-tree-checkbox
    + span.ant-tree-node-selected {
    background-color: transparent;
    color: #7dd3fc;
  }
}
</style>
