<template>
  <div class="module-permissions">
    <div class="permissions-table-wrapper">
      <el-table :data="tableData" border stripe>
        <el-table-column prop="role" label="角色" width="120" />
        <el-table-column
          v-for="module in modules"
          :key="module.key"
          :label="module.label"
          :width="120"
        >
          <template #default="{ row }">
            <div class="permission-cell">
              <el-checkbox
                v-model="row.permissions[module.key].read"
                label="读"
                size="small"
                @change="onPermissionChange"
              />
              <el-checkbox
                v-if="module.writable !== false"
                v-model="row.permissions[module.key].write"
                label="写"
                size="small"
                @change="onPermissionChange"
              />
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from "vue";
import type { ProjectRolePermissionsResponse, ProjectPermissionModule } from "@/types/api";

interface Props {
  project: any;
  matrix: ProjectRolePermissionsResponse | null;
}

interface Emits {
  (e: "update", matrix: ProjectRolePermissionsResponse): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const modules = computed(() => {
  if (!props.matrix) return [];
  return props.matrix.modules || [];
});

const tableData = computed(() => {
  if (!props.matrix) return [];

  return Object.entries(props.matrix.roles).map(([role, permissions]) => ({
    role,
    permissions,
  }));
});

const onPermissionChange = () => {
  if (!props.matrix) return;

  const updatedMatrix = {
    ...props.matrix,
    roles: { ...props.matrix.roles },
  };

  emit("update", updatedMatrix);
};
</script>

<style scoped lang="scss">
.module-permissions {
  padding: 20px 0;
}

.permissions-table-wrapper {
  overflow-x: auto;
}

.permission-cell {
  display: flex;
  gap: 10px;
  align-items: center;

  :deep(.el-checkbox) {
    margin: 0;
  }
}
</style>
