<template>
  <div class="access-control-container">
    <el-row :gutter="20">
      <!-- 左侧门禁设备树 -->
      <el-col :span="6">
        <vab-card title="门禁设备列表" class="h-full">
          <el-input v-model="filterText" placeholder="搜索设备" prefix-icon="search-line" class="mb-10" />
          <el-tree
            ref="treeRef"
            :data="deviceTree"
            :props="defaultProps"
            default-expand-all
            :filter-node-method="filterNode"
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <vab-icon :icon="data.icon" :class="data.online ? 'text-success' : 'text-gray'" />
                <span class="ml-5">{{ node.label }}</span>
                <span v-if="!data.children" class="status-dot" :class="data.online ? 'online' : 'offline'"></span>
              </span>
            </template>
          </el-tree>
        </vab-card>
      </el-col>

      <!-- 右侧权限管理 -->
      <el-col :span="18">
        <vab-card>
          <template #header>
            <div class="card-header">
              <span>{{ currentDevice?.label || '所有设备' }} - 通行权限管理</span>
              <div>
                <el-button type="success" :disabled="!currentDevice?.id" @click="handleRemoteOpen"> <vab-icon icon="remote-control-line" /> 远程开门</el-button>
                <el-button type="primary" @click="handleAuth"> <vab-icon icon="user-add-line" /> 授权下发</el-button>
              </div>
            </div>
          </template>

          <vab-query-form>
            <vab-query-form-left-panel>
              <el-form :inline="true" :model="queryForm" @submit.prevent>
                <el-form-item label="人员信息">
                  <el-input v-model="queryForm.keyword" placeholder="姓名/学号" clearable />
                </el-form-item>
                <el-form-item label="授权状态">
                  <el-select v-model="queryForm.status" placeholder="全部" clearable style="width: 120px">
                    <el-option label="正常" value="valid" />
                    <el-option label="过期" value="expired" />
                    <el-option label="冻结" value="forbidden" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleQuery"> <vab-icon icon="search-line" /> 查询</el-button>
                </el-form-item>
              </el-form>
            </vab-query-form-left-panel>
          </vab-query-form>

          <el-table v-loading="loading" :data="tableData" border stripe height="400px">
            <el-table-column prop="name" label="姓名" width="100" />
            <el-table-column prop="id" label="学号/工号" width="120" />
            <el-table-column prop="type" label="人员类型" width="100">
              <template #default="{ row }">
                <el-tag :type="row.type === 'student' ? '' : 'warning'">{{ row.type === 'student' ? '学生' : '教工' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="authType" label="认证方式" show-overflow-tooltip>
              <template #default="{ row }">
                <el-tag v-if="row.face" size="small" type="success" class="mr-5">人脸</el-tag>
                <el-tag v-if="row.card" size="small" type="primary" class="mr-5">校园卡</el-tag>
                <el-tag v-if="row.app" size="small" type="info">APP</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="validPeriod" label="有效期" width="200" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)">{{ getStatusLabel(row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" text size="small" @click="handleEdit(row)"> <vab-icon icon="time-line" /> 延期</el-button>
                <el-popconfirm title="确定冻结该人员通行权限吗？" @confirm="handleFreeze(row)">
                  <template #reference>
                    <el-button type="danger" text size="small" :disabled="row.status === 'forbidden'"> <vab-icon icon="freeze-line" /> 冻结</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>

          <vab-pagination
            :current-page="queryForm.pageNo"
            :page-size="queryForm.pageSize"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </vab-card>
      </el-col>
    </el-row>

    <!-- 授权弹窗 -->
    <AuthDialog ref="authDialogRef" />
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import AuthDialog from './components/AuthDialog.vue'

defineOptions({
  name: 'AccessControl',
})

// --- Tree Data ---
const filterText = ref('')
const treeRef = ref(null)
const currentDevice = ref(null)

const deviceTree = [
  {
    id: 'zone1',
    label: '北区生活区',
    icon: 'community-line',
    children: [
      { id: 'gate1', label: '北区大门闸机', icon: 'door-lock-box-line', online: true },
      { id: 'b1', label: '1号楼门禁', icon: 'building-2-line', online: true },
      { id: 'b2', label: '2号楼门禁', icon: 'building-2-line', online: true },
    ]
  },
  {
    id: 'zone2',
    label: '南区生活区',
    icon: 'community-line',
    children: [
      { id: 'gate2', label: '南区大门闸机', icon: 'door-lock-box-line', online: true },
      { id: 'a1', label: 'A栋门禁', icon: 'building-2-line', online: false }, // 模拟离线
    ]
  }
]

const defaultProps = {
  children: 'children',
  label: 'label',
}

watch(filterText, (val) => {
  treeRef.value.filter(val)
})

const filterNode = (value, data) => {
  if (!value) return true
  return data.label.includes(value)
}

const handleNodeClick = (data) => {
  currentDevice.value = data
  handleQuery()
}

// --- Table Data ---
const queryForm = reactive({
  keyword: '',
  status: '',
  pageNo: 1,
  pageSize: 10,
})

const loading = ref(false)
const total = ref(100)
const tableData = ref([])
const authDialogRef = ref(null)

const getStatusLabel = (status) => {
  const map = { valid: '正常', expired: '过期', forbidden: '冻结' }
  return map[status]
}
const getStatusType = (status) => {
  const map = { valid: 'success', expired: 'info', forbidden: 'danger' }
  return map[status]
}

const generateMockData = () => {
  return [
    {
      name: '梁健',
      id: '31901001',
      type: 'student',
      face: true,
      card: true,
      app: true,
      validPeriod: '2025-09-01 至 2026-07-01',
      status: 'valid'
    },
    {
      name: '鲁永波',
      id: '31901002',
      type: 'student',
      face: true,
      card: false,
      app: true,
      validPeriod: '2025-09-01 至 2026-07-01',
      status: 'valid'
    },
    {
      name: '陈老师',
      id: '100234',
      type: 'staff',
      face: true,
      card: true,
      app: true,
      validPeriod: '长期有效',
      status: 'valid'
    },
    {
      name: '杨勇捷',
      id: '31901004',
      type: 'student',
      face: false,
      card: true,
      app: false,
      validPeriod: '2024-09-01 至 2025-07-01',
      status: 'expired'
    }
  ]
}

const handleQuery = () => {
  loading.value = true
  setTimeout(() => {
    tableData.value = generateMockData()
    loading.value = false
  }, 500)
}

const handleRemoteOpen = () => {
  ElMessageBox.confirm(
    `确定要远程开启 [${currentDevice.value.label}] 吗？`,
    '高风险操作警告',
    {
      confirmButtonText: '确定开启',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    ElMessage.success('指令已发送，门禁将在5秒后自动关闭')
  })
}

const handleAuth = () => {
  authDialogRef.value.open(currentDevice.value)
}

const handleEdit = (row) => {
  ElMessage.success('延期设置成功')
}

const handleFreeze = (row) => {
  row.status = 'forbidden'
  ElMessage.success('权限已冻结')
}

const handleCurrentChange = (val) => {
  queryForm.pageNo = val
  handleQuery()
}
const handleSizeChange = (val) => {
  queryForm.pageSize = val
  handleQuery()
}

handleQuery()
</script>

<style lang="scss" scoped>
.access-control-container {
  .h-full { height: 100%; min-height: 600px; }
  .mb-10 { margin-bottom: 10px; }
  .mr-5 { margin-right: 5px; }
  .ml-5 { margin-left: 5px; }
  .card-header { display: flex; justify-content: space-between; align-items: center; width: 100%; }

  .custom-tree-node {
    display: flex;
    align-items: center;
    font-size: 14px;
    
    .text-success { color: var(--el-color-success); }
    .text-gray { color: #909399; }

    .status-dot {
      width: 6px;
      height: 6px;
      border-radius: 50%;
      margin-left: 8px;
      
      &.online { background-color: var(--el-color-success); }
      &.offline { background-color: var(--el-color-danger); }
    }
  }
}
</style>