<template>
  <PageContainer title="平台会话管理">
    <el-form :inline="true">
      <el-form-item label="Scope">
        <el-select v-model="query.scope" clearable class="w-input-sm">
          <el-option label="租户会话" value="TENANT" />
          <el-option label="平台会话" value="PLATFORM" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="query.status" clearable class="w-input-sm">
          <el-option label="ACTIVE" value="ACTIVE" />
          <el-option label="ROTATED" value="ROTATED" />
          <el-option label="REVOKED" value="REVOKED" />
          <el-option label="EXPIRED" value="EXPIRED" />
        </el-select>
      </el-form-item>
      <el-form-item label="用户ID">
        <el-input-number v-model="query.userId" :min="1" :controls="false" class="w-input-sm" />
      </el-form-item>
      <el-form-item label="租户ID">
        <el-input-number v-model="query.tenantId" :min="1" :controls="false" class="w-input-sm" />
      </el-form-item>
      <el-form-item>
        <el-button v-if="canRead" @click="load">查询</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="rows" v-loading="loading">
      <el-table-column prop="id" label="会话ID" width="100" />
      <el-table-column prop="scope" label="Scope" width="100" />
      <el-table-column prop="status" label="状态" width="100" />
      <el-table-column prop="userId" label="用户ID" width="100" />
      <el-table-column prop="userName" label="用户名" width="140" />
      <el-table-column prop="phone" label="手机号" width="130" />
      <el-table-column prop="tenantId" label="租户ID" width="100" />
      <el-table-column prop="tenantName" label="租户名称" width="180" />
      <el-table-column prop="issuedAt" label="签发时间" width="180" />
      <el-table-column prop="expiresAt" label="过期时间" width="180" />
      <el-table-column prop="lastUsedAt" label="最近使用" width="180" />
      <el-table-column label="操作" width="100" fixed="right">
        <template #default="{ row }">
          <el-button
            v-if="canManage && row.status === 'ACTIVE'"
            size="small"
            type="danger"
            @click="handleRevokePrincipal(row)"
          >
            下线会话
          </el-button>
          <!-- <el-button
            v-if="canManage && row.userId"
            size="small"
            @click="handleRevokePrincipal(row)"
          >
            下线该主体全部
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>
  </PageContainer>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from "vue";
import PageContainer from "../../components/PageContainer.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  fetchPlatformAuthSessions,
  revokePlatformAuthSession,
  revokePlatformPrincipalSessions,
} from "../../api/modules";
import { PERMS } from "../../constants/permissions";
import { useAuthStore } from "../../stores/auth";

const authStore = useAuthStore();
const canRead = computed(() => authStore.hasPermission(PERMS.platform.sessionRead));
const canManage = computed(() => authStore.hasPermission(PERMS.platform.sessionManage));
const loading = ref(false);
const rows = ref<any[]>([]);
const query = reactive<{
  scope?: "TENANT" | "PLATFORM";
  status?: "ACTIVE" | "ROTATED" | "REVOKED" | "EXPIRED";
  userId?: number;
  tenantId?: number;
}>({
  scope: undefined,
  status: "ACTIVE",
  userId: undefined,
  tenantId: undefined,
});

const load = async () => {
  if (!canRead.value) {
    rows.value = [];
    return;
  }
  loading.value = true;
  try {
    const resp = await fetchPlatformAuthSessions({
      scope: query.scope,
      status: query.status,
      userId: query.userId,
      tenantId: query.tenantId,
    });
    rows.value = resp?.data || [];
  } finally {
    loading.value = false;
  }
};

const handleRevoke = async (row: any) => {
  await ElMessageBox.confirm(`确认下线会话 #${row.id} 吗？`, "提示", { type: "warning" });
  await revokePlatformAuthSession(Number(row.id));
  ElMessage.success("会话已下线");
  await load();
};

const handleRevokePrincipal = async (row: any) => {
  const scope = String(row?.scope || "") as "TENANT" | "PLATFORM";
  const userId = Number(row?.userId || 0);
  if (!userId || (scope !== "TENANT" && scope !== "PLATFORM")) {
    ElMessage.error("主体信息不完整，无法下线");
    return;
  }
  await ElMessageBox.confirm("确认下线该主体的全部会话吗？", "提示", { type: "warning" });
  await revokePlatformPrincipalSessions({
    userId,
    scope,
    tenantId: scope === "TENANT" ? Number(row?.tenantId || 0) : undefined,
  });
  ElMessage.success("该主体会话已全部下线");
  await load();
};

onMounted(load);
</script>
