<template>
  <div class="container-box">
    <div class="header-bar">
      <h2>角色管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          添加角色
        </el-button>
        <el-button @click="refresh">
          <el-icon><Refresh /></el-icon>
          刷新</el-button
        >
      </div>
    </div>
    <el-divider></el-divider>

    <!-- 错误状态 -->
    <div v-if="error" class="error-state">
      <el-alert title="加载失败" :message="error" type="error" show-icon />
      <el-button type="primary" @click="refresh">重试</el-button>
    </div>

    <!-- 角色列表 -->
    <div v-else>
      <el-table :data="roles" stripe style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column
          prop="name"
          label="角色名称"
          min-width="150"
          align="center"
        />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'" size="small">
              {{ row.status === 1 ? "启用" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="rights"
          label="权限"
          min-width="150"
          align="center"
        />
        <el-table-column label="操作" width="220" fixed="right" align="center">
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              link
              @click="handleView(row)"
            >
              <el-icon><View /></el-icon>
              详情
            </el-button>
            <el-button
              v-if="userInfo?.id === 2"
              size="small"
              type="primary"
              link
              @click="handleEdit(row)"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button
              v-if="userInfo?.id === 2"
              size="small"
              type="danger"
              link
              @click="handleDelete(row)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 编辑对话框 -->
    <RoleEditDialog
      v-model="editDialogVisible"
      :role="currentRole"
      @success="handleEditSuccess"
    />

    <!-- 详情对话框 -->
    <RoleDetailDialog
      v-model="detailDialogVisible"
      :roleId="currentRoleId"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, View, Edit, Delete, Refresh } from "@element-plus/icons-vue";
import { getAllRoles, getRoleById, deleteRole } from "@/api/role";
import RoleEditDialog from "./components/edit.vue";
import RoleDetailDialog from "./components/detail.vue";
import { useAuthStore } from "@/stores/auth";

// 使用 auth store 获取用户信息
const authStore = useAuthStore();

const roles = ref<any[]>([]);
const loading = ref(false);
const error = ref("");

const editDialogVisible = ref(false);
const detailDialogVisible = ref(false);
const currentRole = ref<any>(null);
const currentRoleId = ref<number | null>(null);

// 获取用户信息
const userInfo = authStore.user;
if (userInfo && userInfo.id) {
  // console.log('用户名:', userInfo.username || userInfo.nickname);
  // console.log('用户ID:', userInfo.id);
  // console.log('角色:', userInfo.role);
} else {
  // console.log('未找到用户信息或用户未登录');
}

// 获取角色列表
const fetchRoles = async () => {
  loading.value = true;
  error.value = "";
  try {
    const res = await getAllRoles();
    if (res.code === 200) {
      roles.value = res.data || [];
      // console.log('角色列表:', roles.value);
    } else {
      error.value = res.msg || "获取角色列表失败";
      ElMessage.error(error.value);
    }
  } catch (err: any) {
    error.value = err.message || "获取角色列表失败";
    ElMessage.error(error.value);
  } finally {
    loading.value = false;
  }
};

// 刷新界面
async function refresh() {
  await fetchRoles();
  if (!error.value) {
    ElMessage.success("刷新成功");
  }
}

// 添加角色
function handleAdd() {
  currentRole.value = null;
  editDialogVisible.value = true;
}

// 查看详情
function handleView(row: any) {
  currentRoleId.value = row.id;
  detailDialogVisible.value = true;
}

// 编辑角色
function handleEdit(row: any) {
  currentRole.value = { ...row };
  editDialogVisible.value = true;
}

// 删除角色
async function handleDelete(row: any) {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色「${row.name}」吗？删除后不可恢复。`,
      "警告",
      { type: "warning" }
    );

    loading.value = true;
    try {
      const res = await deleteRole(row.id);
      if (res.code === 200) {
        ElMessage.success("删除成功");
        fetchRoles();
      } else {
        ElMessage.error(res.msg || "删除失败");
      }
    } catch (err: any) {
      ElMessage.error(err.message || "删除失败");
    } finally {
      loading.value = false;
    }
  } catch {
    // 取消删除
  }
}

// 编辑成功回调
function handleEditSuccess() {
  fetchRoles();
}

onMounted(() => {
  fetchRoles();
});
</script>

<style scoped>
.error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 220px;
  padding: 32px 0 16px 0;
  background: var(--el-bg-color-page);
  border-radius: 5px;
  gap: 16px;
}
</style>
