<template>
  <div class="role-management-container">
    <!-- 头部：标题和创建按钮 -->
    <div class="header-section">
      <h2 class="page-title">角色管理</h2>
      <el-button type="primary" :icon="Plus" @click="handleCreateRole"> 创建角色 </el-button>
    </div>

    <!-- 角色卡片列表 -->
    <div v-if="roleList.length > 0" class="role-cards">
      <div
        v-for="(role, index) in roleList"
        :key="role.id"
        class="role-card"
        :class="{ 'role-card-active': selectedRoleId === role.id }"
        @click="handleCardClick(role)"
      >
        <div class="role-card-header">
          <h3 class="role-type-title">
            {{ role.roleName || "角色类型" }}
          </h3>
        </div>
        <div class="role-card-body">
          <div class="role-info-item">
            <span class="info-label">关联子账号</span>
            <span class="info-value">{{ role.subAccountCount || 0 }}个</span>
          </div>
          <div class="role-info-item">
            <span class="info-label">关联权限</span>
            <span class="info-value">{{ role.permissionCount || 0 }}个</span>
          </div>
        </div>
        <div class="role-card-divider" />
        <div class="role-card-actions">
          <el-button link type="primary" @click.stop="handleView(role)"> 查看 </el-button>
          <el-button link type="primary" @click.stop="handleEdit(role)"> 编辑 </el-button>
          <el-button link type="primary" @click.stop="handleDelete(role)"> 删除 </el-button>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-state">
      <el-empty description="暂无角色数据" :image-size="100" />
    </div>

    <!-- 删除确认对话框 -->
    <el-dialog v-model="deleteDialogVisible" title="删除确认" width="400px" :close-on-click-modal="false">
      <div class="delete-content">
        <p>确定要删除角色"{{ currentRole?.roleName }}"吗？</p>
        <p class="delete-warning">如果角色关联的子账号 就无法删除！</p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteDialogVisible = false"> 取消 </el-button>
          <el-button type="danger" @click="handleConfirmDelete" :loading="deleteLoading"> 确定删除 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="roleManagement">
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { getRolePage, deleteRoleWithCheck } from "@/api/modules/accountRoleManagement";
import { localGet } from "@/utils";
// 角色数据类型
interface RoleItem {
  id: number;
  roleName: string;
  description?: string;
  subAccountCount: number;
  permissionCount: number;
  createTime?: string;
  updateTime?: string;
}

// 路由
const router = useRouter();

// 选中的角色ID
const selectedRoleId = ref<number | null>(null);

// 角色列表（假数据）
const roleList = ref<RoleItem[]>([]);

// 删除相关
const deleteDialogVisible = ref(false);
const deleteLoading = ref(false);
const currentRole = ref<RoleItem | null>(null);

// 从缓存中获取 createdId，如果没有则从用户信息中获取 storeId
const createdId = localGet("createdId") || localGet("geeker-user")?.userInfo?.storeId || "";

const handleGetRolePage = async () => {
  const res = await getRolePage(1, 10, Number(createdId));
  const code = typeof res.code === "string" ? parseInt(res.code) : res.code;
  if (code === 200) {
    const responseData = res.data as any;
    roleList.value = responseData.records || [];
  }
};

// 初始化：默认选中第一个角色
onMounted(() => {
  handleGetRolePage();
});

// 创建角色
const handleCreateRole = () => {
  router.push("/accountRoleManagement/roleManagement/create");
};

// 查看角色
const handleView = (role: RoleItem) => {
  router.push({
    path: "/accountRoleManagement/roleManagement/view",
    query: {
      roleId: role.roleId,
      roleName: role.roleName
    }
  });
};

// 编辑角色
const handleEdit = (role: RoleItem) => {
  router.push({
    path: "/accountRoleManagement/roleManagement/create",
    query: {
      roleId: role.roleId,
      roleName: role.roleName,
      type: "edit"
    }
  });
};

// 删除角色
const handleDelete = (role: RoleItem) => {
  currentRole.value = role;
  deleteDialogVisible.value = true;
};

// 确认删除
const handleConfirmDelete = async () => {
  if (!currentRole.value) return;

  deleteLoading.value = true;
  try {
    const res = await deleteRoleWithCheck(currentRole.value.roleId);
    const code = typeof res.code === "string" ? parseInt(res.code) : res.code;
    if (code === 200) {
      ElMessage.success("删除成功");
      handleGetRolePage();
    }
    deleteDialogVisible.value = false;
    currentRole.value = null;
  } catch (error) {
  } finally {
    deleteLoading.value = false;
  }
};

// 卡片点击
const handleCardClick = (role: RoleItem) => {
  selectedRoleId.value = role.id;
};
</script>

<style lang="scss" scoped>
.role-management-container {
  min-height: calc(100vh - 84px);
  padding: 20px;
  background: #ffffff;
}

// 头部区域
.header-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 16px;
  margin-bottom: 24px;
  border-bottom: 1px solid #e4e7ed;
  .page-title {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
}

// 角色卡片容器
.role-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 20px;

  @media (width <= 768px) {
    grid-template-columns: repeat(1, 1fr);
  }
}

// 角色卡片
.role-card {
  padding: 20px;
  cursor: pointer;
  background: #ffffff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  transition: all 0.3s;
  &:hover {
    box-shadow: 0 2px 12px rgb(0 0 0 / 10%);
    transform: translateY(-2px);
  }
  &.role-card-active {
    border: 2px solid #409eff;
    box-shadow: 0 2px 12px rgb(64 158 255 / 20%);
  }
  .role-card-header {
    margin-bottom: 16px;
    .role-type-title {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }
  }
  .role-card-body {
    margin-bottom: 16px;
    .role-info-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 12px;
      &:last-child {
        margin-bottom: 0;
      }
      .info-label {
        font-size: 14px;
        color: var(--el-text-color-regular);
      }
      .info-value {
        font-size: 14px;
        font-weight: 500;
        color: var(--el-text-color-primary);
      }
    }
  }
  .role-card-divider {
    height: 1px;
    margin: 16px 0;
    background: #e4e7ed;
  }
  .role-card-actions {
    display: flex;
    gap: 8px;
    align-items: center;
    justify-content: space-around;
    :deep(.el-button) {
      flex: 1;
    }
  }
}

// 空状态
.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  padding: 40px 20px;
}

// 删除对话框内容
.delete-content {
  p {
    margin: 0 0 12px;
    font-size: 14px;
    color: var(--el-text-color-primary);
    &:last-child {
      margin-bottom: 0;
    }
  }
  .delete-warning {
    font-weight: 500;
    color: #e6a23c;
  }
}

// 对话框底部
.dialog-footer {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}
</style>
