<template>
  <div class="page">
    <section class="page-hero">
      <div>
        <h1>角色权限</h1>
        <p>通过角色聚合菜单、按钮/API 权限和区域数据范围。</p>
      </div>
      <el-tag type="primary" effect="light">角色 {{ total }}</el-tag>
    </section>
    <div class="toolbar">
      <span></span>
      <el-button type="primary" round @click="openCreate">新增角色</el-button>
    </div>
    <el-card class="modern-card" shadow="never">
      <el-table :data="roles" class="modern-table">
        <el-table-column prop="name" label="角色名称" />
        <el-table-column prop="code" label="角色编码" />
        <el-table-column prop="description" label="说明" />
        <el-table-column label="权限" min-width="220">
          <template #default="{ row }">
            <el-tag v-for="item in row.permissions" :key="item.permissionId" class="permission-tag">
              {{ item.permission.name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="区域数据权限" min-width="220">
          <template #default="{ row }">
            <el-tag v-for="item in row.regionScopes" :key="item.regionId" type="success" class="permission-tag">
              {{ item.region.name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button link type="primary" @click="openEdit(row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination"
        layout="total, sizes, prev, pager, next"
        :total="total"
        :current-page="page"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
      />
    </el-card>
    <el-dialog v-model="dialogVisible" :title="form.id ? '编辑角色' : '新增角色'" width="720px">
      <el-form :model="form" label-width="90px">
        <el-form-item label="名称"><el-input v-model="form.name" /></el-form-item>
        <el-form-item label="编码"><el-input v-model="form.code" /></el-form-item>
        <el-form-item label="说明"><el-input v-model="form.description" /></el-form-item>
        <el-form-item label="功能权限">
          <el-checkbox-group v-model="selectedPermissionIds" class="permission-options">
            <el-checkbox v-for="permission in permissions" :key="permission.id" :label="permission.id">
              {{ permission.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="区域权限">
          <div class="region-scope-box">
            <div class="scope-help">勾选全国/省/市/区县后，该角色只能查看对应区域及其下级区域的路灯和报警数据。</div>
            <el-tree
              ref="regionTreeRef"
              :data="regions"
              node-key="id"
              show-checkbox
              default-expand-all
              check-strictly
              :props="{ label: 'name', children: 'children' }"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from 'vue';
import { regionApi, systemApi } from '../../api/modules';

const roles = ref<any[]>([]);
const permissions = ref<any[]>([]);
const regions = ref<any[]>([]);
const dialogVisible = ref(false);
const selectedPermissionIds = ref<string[]>([]);
const regionTreeRef = ref<any>();
const page = ref(1);
const pageSize = ref(20);
const total = ref(0);
const form = reactive<{ id?: string; name: string; code: string; description: string }>({
  id: undefined,
  name: '',
  code: '',
  description: '',
});

async function load() {
  const [roleData, permissionData, regionData] = await Promise.all([
    systemApi.roles({ page: page.value, pageSize: pageSize.value }),
    systemApi.permissions(),
    regionApi.tree(),
  ]);
  roles.value = roleData.items ?? [];
  total.value = roleData.total ?? 0;
  permissions.value = permissionData as any[];
  regions.value = regionData as any[];
}

function handlePageChange(value: number) {
  page.value = value;
  void load();
}

function handleSizeChange(value: number) {
  pageSize.value = value;
  page.value = 1;
  void load();
}

function resetForm() {
  form.id = undefined;
  form.name = '';
  form.code = '';
  form.description = '';
  selectedPermissionIds.value = [];
  regionTreeRef.value?.setCheckedKeys([]);
}

function openCreate() {
  resetForm();
  dialogVisible.value = true;
}

function openEdit(row: any) {
  form.id = row.id;
  form.name = row.name;
  form.code = row.code;
  form.description = row.description ?? '';
  selectedPermissionIds.value = row.permissions?.map((item: any) => item.permissionId) ?? [];
  dialogVisible.value = true;
  void nextTick(() => {
    regionTreeRef.value?.setCheckedKeys(row.regionScopes?.map((item: any) => item.regionId) ?? []);
  });
}

async function save() {
  const payload = {
    ...form,
    permissionIds: selectedPermissionIds.value,
    regionIds: regionTreeRef.value?.getCheckedKeys() ?? [],
  };
  if (form.id) {
    await systemApi.updateRole(form.id, payload);
  } else {
    await systemApi.createRole(payload);
  }
  dialogVisible.value = false;
  resetForm();
  await load();
}

onMounted(load);
</script>

<style scoped>
.permission-tag {
  margin: 2px 4px 2px 0;
}

.pagination {
  margin-top: 16px;
  justify-content: flex-end;
}

.permission-options {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 4px 12px;
}

.region-scope-box {
  width: 100%;
  padding: 12px;
  border: 1px solid #e5e7eb;
  border-radius: 14px;
  background: #f8fafc;
}

.scope-help {
  margin-bottom: 10px;
  color: #64748b;
  font-size: 13px;
  line-height: 1.6;
}
</style>
