<template>
  <div class="page-container">
    <el-card shadow="hover">
      <el-tabs v-model="activeTab">
        <!-- ============ 设备账号 ============ -->
        <el-tab-pane label="设备账号" name="devices">
          <div class="toolbar">
            <div>
              <span class="text-muted">
                共 {{ devices.length }} 台已激活设备 · 在线 {{ onlineCount }} 台
              </span>
            </div>
            <div class="toolbar-actions">
              <el-input
                v-model="keyword"
                placeholder="搜索设备 UID / 型号"
                clearable
                style="width: 200px"
                @keyup.enter="loadDevices"
                @clear="loadDevices"
              />
              <el-select
                v-model="statusFilter"
                placeholder="全部状态"
                clearable
                style="width: 130px"
              >
                <el-option label="正常" value="ACTIVE" />
                <el-option label="停用" value="SUSPENDED" />
                <el-option label="封禁" value="BANNED" />
              </el-select>
              <el-select
                v-model="onlineFilter"
                placeholder="全部"
                clearable
                style="width: 120px"
              >
                <el-option label="在线" :value="true" />
                <el-option label="离线" :value="false" />
              </el-select>
              <el-button :icon="'Refresh'" :loading="loading" @click="loadDevices">刷新</el-button>
            </div>
          </div>

          <el-table v-loading="loading" :data="devices" stripe>
            <el-table-column prop="deviceUid" label="设备 UID" min-width="200" show-overflow-tooltip />
            <el-table-column prop="sn" label="序列号" min-width="140" />
            <el-table-column prop="model" label="型号" min-width="130">
              <template #default="{ row }">{{ row.model || '—' }}</template>
            </el-table-column>
            <el-table-column label="状态" width="140">
              <template #default="{ row }">
                <el-tag :type="statusTagType(row.status)" effect="dark" size="small">
                  {{ statusText(row.status) }}
                </el-tag>
                <el-tooltip v-if="row.statusReason" :content="row.statusReason" placement="top">
                  <el-icon class="reason-icon"><InfoFilled /></el-icon>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column label="连接" width="90">
              <template #default="{ row }">
                <span class="status-dot" :class="row.online ? 'online' : 'offline'"></span>
                {{ row.online ? '在线' : '离线' }}
              </template>
            </el-table-column>
            <el-table-column label="最后在线" min-width="170">
              <template #default="{ row }">{{ fmtTime(row.lastOnlineAt) }}</template>
            </el-table-column>
            <el-table-column label="激活时间" min-width="170">
              <template #default="{ row }">{{ fmtTime(row.provisionedAt) }}</template>
            </el-table-column>
            <el-table-column label="操作" width="220" fixed="right">
              <template #default="{ row }">
                <el-button
                  v-if="row.status === 'ACTIVE'"
                  link
                  type="warning"
                  @click="handleDisable(row)"
                >
                  禁用
                </el-button>
                <el-button v-else link type="success" @click="handleEnable(row)">启用</el-button>
                <el-button link type="primary" :disabled="!row.online" @click="handleKick(row)">
                  下线
                </el-button>
                <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- ============ SN 白名单 ============ -->
        <el-tab-pane label="SN 白名单" name="allowlist">
          <div class="toolbar">
            <div>
              <span class="text-muted">共 {{ allowlist.length }} 条白名单记录</span>
            </div>
            <div class="toolbar-actions">
              <el-input
                v-model="allowKeyword"
                placeholder="搜索 SN"
                clearable
                style="width: 200px"
              />
              <el-button :icon="'Refresh'" :loading="allowLoading" @click="loadAllowlist">
                刷新
              </el-button>
              <el-button type="primary" :icon="'Plus'" @click="importVisible = true">
                批量导入
              </el-button>
            </div>
          </div>

          <el-table v-loading="allowLoading" :data="filteredAllowlist" stripe>
            <el-table-column type="index" label="#" width="70" />
            <el-table-column prop="sn" label="序列号" min-width="240" />
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="{ row }">
                <el-button link type="danger" @click="handleRemoveAllow(row.sn)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 批量导入白名单 -->
    <el-dialog v-model="importVisible" title="批量导入 SN 白名单" width="480px">
      <el-input
        v-model="importText"
        type="textarea"
        :rows="10"
        placeholder="每行一个 SN，例如：&#10;SN0001&#10;SN0002"
      />
      <template #footer>
        <el-button @click="importVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="submitImport">导入</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { InfoFilled } from '@element-plus/icons-vue';
import {
  getDeviceAccounts,
  disableDevice,
  enableDevice,
  kickDevice,
  deleteDevice,
  getAllowlist,
  importAllowlist,
  removeAllowlist,
} from '@/api/admin';
import type { AccountStatus, DeviceAccountView } from '@/api/admin';

const activeTab = ref('devices');

// ---------- 设备账号 ----------
const devices = ref<DeviceAccountView[]>([]);
const loading = ref(false);
const submitting = ref(false);
const keyword = ref('');
const statusFilter = ref('');
const onlineFilter = ref<boolean | ''>('');

const onlineCount = computed(() => devices.value.filter((d) => d.online).length);

async function loadDevices() {
  loading.value = true;
  try {
    devices.value = await getDeviceAccounts({
      keyword: keyword.value || undefined,
      status: statusFilter.value || undefined,
      online: onlineFilter.value === '' ? undefined : onlineFilter.value,
    });
  } finally {
    loading.value = false;
  }
}

watch([statusFilter, onlineFilter], loadDevices);

async function handleDisable(row: DeviceAccountView) {
  const input = await ElMessageBox.prompt('请输入禁用原因', `禁用设备「${row.deviceUid}」`, {
    inputPlaceholder: '例如：设备遗失',
    confirmButtonText: '确定禁用',
    cancelButtonText: '取消',
    type: 'warning',
  }).catch(() => null);
  if (!input) return;
  await disableDevice(row.deviceUid, input.value || '管理员操作');
  ElMessage.success('设备已禁用');
  await loadDevices();
}

async function handleEnable(row: DeviceAccountView) {
  await enableDevice(row.deviceUid);
  ElMessage.success('设备已启用');
  await loadDevices();
}

async function handleKick(row: DeviceAccountView) {
  const ok = await ElMessageBox.confirm(
    `确定强制设备「${row.deviceUid}」下线？其访问令牌将立即失效。`,
    '强制下线',
    { type: 'warning', confirmButtonText: '确定', cancelButtonText: '取消' },
  ).catch(() => false);
  if (!ok) return;
  await kickDevice(row.deviceUid, '管理员强制下线');
  ElMessage.success('已强制下线');
  await loadDevices();
}

async function handleDelete(row: DeviceAccountView) {
  const ok = await ElMessageBox.confirm(
    `确定删除设备「${row.deviceUid}」？该操作不可恢复，设备需重新激活。`,
    '删除设备',
    { type: 'error', confirmButtonText: '确定删除', cancelButtonText: '取消' },
  ).catch(() => false);
  if (!ok) return;
  await deleteDevice(row.deviceUid);
  ElMessage.success('设备已删除');
  await loadDevices();
}

// ---------- SN 白名单 ----------
const allowlist = ref<{ sn: string }[]>([]);
const allowLoading = ref(false);
const allowKeyword = ref('');
const importVisible = ref(false);
const importText = ref('');

const filteredAllowlist = computed(() => {
  const kw = allowKeyword.value.trim().toLowerCase();
  return kw ? allowlist.value.filter((i) => i.sn.toLowerCase().includes(kw)) : allowlist.value;
});

async function loadAllowlist() {
  allowLoading.value = true;
  try {
    const resp = await getAllowlist();
    allowlist.value = (resp.sns || []).map((sn) => ({ sn }));
  } finally {
    allowLoading.value = false;
  }
}

async function submitImport() {
  const sns = importText.value
    .split('\n')
    .map((s) => s.trim())
    .filter(Boolean);
  if (!sns.length) {
    ElMessage.warning('请输入至少一个 SN');
    return;
  }
  submitting.value = true;
  try {
    const resp = await importAllowlist(sns);
    ElMessage.success(`导入成功，新增 ${resp.added} 条，当前共 ${resp.total} 条`);
    importVisible.value = false;
    importText.value = '';
    await loadAllowlist();
  } finally {
    submitting.value = false;
  }
}

async function handleRemoveAllow(sn: string) {
  const ok = await ElMessageBox.confirm(`确定将「${sn}」移出白名单？`, '移除白名单', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).catch(() => false);
  if (!ok) return;
  await removeAllowlist(sn);
  ElMessage.success('已移除');
  await loadAllowlist();
}

watch(activeTab, (tab) => {
  if (tab === 'allowlist' && !allowlist.value.length) loadAllowlist();
});

function statusText(status: AccountStatus) {
  return { ACTIVE: '正常', SUSPENDED: '停用', BANNED: '封禁' }[status] || status;
}

function statusTagType(status: AccountStatus) {
  return { ACTIVE: 'success', SUSPENDED: 'warning', BANNED: 'danger' }[status] || 'info';
}

function fmtTime(ts: number | null) {
  return ts ? new Date(ts).toLocaleString('zh-CN') : '—';
}

onMounted(loadDevices);
</script>

<style scoped>
.toolbar {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  margin-bottom: 16px;
  flex-wrap: wrap;
  gap: 8px;
}
.toolbar-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}
.reason-icon {
  margin-left: 6px;
  color: var(--el-color-warning);
  vertical-align: middle;
}
.status-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 6px;
}
.status-dot.online {
  background: #67c23a;
}
.status-dot.offline {
  background: #f56c6c;
}
</style>
