<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="username" label="账号" width="140" />
      <el-table-column prop="nickname" label="昵称" width="120" />
      <el-table-column prop="role_id" label="角色ID" width="90" />
      <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 prop="create_time" label="创建时间" min-width="160" />
      <el-table-column label="操作" width="160" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="openEdit(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="username">
          <el-input v-model="form.username" :disabled="!!form.id" placeholder="登录账号" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="显示名称" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="form.password"
            type="password"
            show-password
            :placeholder="form.id ? '留空则不修改' : '必填'"
          />
        </el-form-item>
        <el-form-item label="角色" prop="role_id">
          <el-input-number v-model="form.role_id" :min="0" />
        </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-card>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessageBox } from "element-plus";
import {
  deleteAdminUser,
  fetchAdminUsers,
  saveAdminUser,
  type SysAdminRow,
} from "@/api/admin";

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

const form = reactive({
  id: 0,
  username: "",
  nickname: "",
  password: "",
  role_id: 1,
  status: 1,
});

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

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

function openEdit(row?: SysAdminRow) {
  if (row) {
    form.id = row.id;
    form.username = row.username;
    form.nickname = row.nickname;
    form.password = "";
    form.role_id = row.role_id;
    form.status = row.status;
  } else {
    form.id = 0;
    form.username = "";
    form.nickname = "";
    form.password = "";
    form.role_id = 1;
    form.status = 1;
  }
  visible.value = true;
}

async function submit() {
  if (!formRef.value) return;
  await formRef.value.validate(async (ok) => {
    if (!ok) return;
    if (!form.id && !form.password.trim()) {
      formRef.value?.validateField("password");
      return;
    }
    saving.value = true;
    try {
      const payload: Record<string, unknown> = {
        id: form.id,
        username: form.username.trim(),
        nickname: form.nickname.trim(),
        role_id: form.role_id,
        status: form.status,
      };
      if (form.password.trim()) {
        payload.password = form.password;
      }
      await saveAdminUser(payload);
      visible.value = false;
      await load();
    } finally {
      saving.value = false;
    }
  });
}

async function onDelete(row: SysAdminRow) {
  await ElMessageBox.confirm(`确定删除管理员「${row.username}」？`, "提示", {
    type: "warning",
  });
  await deleteAdminUser(row.id);
  await load();
}

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

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

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