<template>
  <el-card shadow="never" class="box">
    <div class="toolbar">
      <el-button type="primary" @click="openEdit()">新增角色</el-button>
    </div>
    <el-table v-loading="loading" :data="list" stripe>
      <el-table-column prop="id" label="ID" width="70" />
      <el-table-column prop="name" label="名称" width="160" />
      <el-table-column prop="code" label="编码" width="140" />
      <el-table-column prop="remark" label="备注" min-width="160" />
      <el-table-column label="状态" width="90">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status === 1 ? "正常" : "禁用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="openEdit(row)">编辑</el-button>
          <el-button type="warning" link @click="openPerm(row)">分配权限</el-button>
          <el-button
            v-if="row.id !== 1"
            type="danger"
            link
            @click="onDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      v-model="visible"
      :title="form.id ? '编辑角色' : '新增角色'"
      width="480px"
      align-center
      destroy-on-close
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="88px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model="form.code" placeholder="英文标识" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" rows="2" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :value="1">正常</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="submit">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="permVisible"
      title="菜单权限"
      width="520px"
      align-center
      destroy-on-close
      @opened="onPermOpen"
    >
      <el-tree
        ref="treeRef"
        :data="menuTree"
        show-checkbox
        node-key="id"
        :props="{ label: 'name', children: 'children' }"
        default-expand-all
      />
      <template #footer>
        <el-button @click="permVisible = false">取消</el-button>
        <el-button type="primary" :loading="permSaving" @click="savePerm">保存</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import type { ElTree } from "element-plus";
import { ElMessageBox } from "element-plus";
import {
  deleteRole,
  fetchMenuTree,
  fetchRoleMenuIds,
  fetchRoles,
  saveRole,
  saveRoleMenus,
  type MenuNode,
  type RoleRow,
} from "@/api/admin";

const loading = ref(false);
const list = ref<RoleRow[]>([]);
const visible = ref(false);
const saving = ref(false);
const formRef = ref<FormInstance>();

const form = reactive({
  id: 0,
  name: "",
  code: "",
  remark: "",
  status: 1,
});

const rules: FormRules = {
  name: [{ required: true, message: "必填", trigger: "blur" }],
};

const permVisible = ref(false);
const permSaving = ref(false);
const permRoleId = ref(0);
const menuTree = ref<MenuNode[]>([]);
const treeRef = ref<InstanceType<typeof ElTree>>();

async function load() {
  loading.value = true;
  try {
    const res = await fetchRoles();
    list.value = res.data.list;
  } finally {
    loading.value = false;
  }
}

function openEdit(row?: RoleRow) {
  if (row) {
    form.id = row.id;
    form.name = row.name;
    form.code = row.code;
    form.remark = row.remark;
    form.status = row.status;
  } else {
    form.id = 0;
    form.name = "";
    form.code = "";
    form.remark = "";
    form.status = 1;
  }
  visible.value = true;
}

async function submit() {
  if (!formRef.value) return;
  await formRef.value.validate(async (ok) => {
    if (!ok) return;
    saving.value = true;
    try {
      await saveRole({
        id: form.id,
        name: form.name.trim(),
        code: form.code.trim(),
        remark: form.remark.trim(),
        status: form.status,
      });
      visible.value = false;
      await load();
    } finally {
      saving.value = false;
    }
  });
}

async function onDelete(row: RoleRow) {
  await ElMessageBox.confirm(`确定删除角色「${row.name}」？`, "提示", {
    type: "warning",
  });
  await deleteRole(row.id);
  await load();
}

async function openPerm(row: RoleRow) {
  permRoleId.value = row.id;
  const tree = await fetchMenuTree();
  menuTree.value = tree.data.list;
  permVisible.value = true;
}

async function onPermOpen() {
  const res = await fetchRoleMenuIds(permRoleId.value);
  const ids = res.data.menu_ids;
  await nextTick();
  treeRef.value?.setCheckedKeys(ids);
}

async function savePerm() {
  const keys = treeRef.value?.getCheckedKeys(false) as number[];
  const half = treeRef.value?.getHalfCheckedKeys() as number[];
  const all = [...new Set([...keys, ...half])];
  permSaving.value = true;
  try {
    await saveRoleMenus(permRoleId.value, all);
    permVisible.value = false;
  } finally {
    permSaving.value = false;
  }
}

onMounted(() => void load());
</script>

<style scoped>
.box {
  border-radius: 12px;
}

.toolbar {
  margin-bottom: 16px;
}
</style>
