<template>
  <div class="user-management">
    <el-card class="box-card">
      <h2>用户管理</h2>

      <el-table :data="users" style="width: 100%" border v-loading="tableLoading">
        <el-table-column prop="name" label="用户名" width="180" />
        <el-table-column prop="userType" label="用户类型" width="120" :formatter="typeFormatter" />
        <el-table-column prop="created_at" label="注册时间" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" type="primary" @click="onEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="onDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      title="编辑用户"
      v-model="showDialog"
      :modal-append-to-body="false"
      :style="{ top: '120px' }"
      :before-close="handleDialogClose"
    >
      <el-form :model="form" ref="formRef" label-width="100px">
        <el-form-item label="用户名" prop="name" :rules="[{ required: true, message: '用户名不能为空', trigger: 'blur' }]">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="密码" prop="password" :rules="[
          { min: 3, message: '密码长度至少为3个字符', trigger: 'blur' }
        ]">
          <el-input type="password" v-model="form.password" placeholder="留空则不修改密码" />
        </el-form-item>
        <el-form-item label="用户类型" prop="userType" :rules="[{ required: true, message: '请选择用户类型', trigger: 'change' }]">
          <el-select v-model="form.userType" placeholder="请选择">
            <el-option label="普通用户" value="user" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="onSubmit" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from "vue";
import { ElMessage, ElForm, ElMessageBox } from "element-plus";
import { getUsers, updateUser, deleteUser } from "@/API/users";

interface User {
  id: number;
  name: string;
  userType: string;
  created_at: string;
}

const users = ref<User[]>([]);
const showDialog = ref(false);
const editUser = ref<User | null>(null);

const formRef = ref<InstanceType<typeof ElForm> | null>(null);
const form = reactive({
  name: "",
  password: "",
  userType: "user",
});

const tableLoading = ref(false);
const submitLoading = ref(false);

const typeFormatter = (row: any, column: any, cellValue: string) => {
  if (cellValue === "admin") return "管理员";
  if (cellValue === "user") return "普通用户";
  return cellValue;
};

const formatTime = (timeStr: string) => {
  const date = new Date(timeStr);
  const yyyy = date.getFullYear();
  const MM = String(date.getMonth() + 1).padStart(2, "0");
  const dd = String(date.getDate()).padStart(2, "0");
  const hh = String(date.getHours()).padStart(2, "0");
  const mm = String(date.getMinutes()).padStart(2, "0");
  const ss = String(date.getSeconds()).padStart(2, "0");
  return `${yyyy}-${MM}-${dd} ${hh}:${mm}:${ss}`;
};

const loadUsers = async () => {
  tableLoading.value = true;
  try {
    const res = await getUsers();
    users.value = res.data.users.map((u: User) => ({
      ...u,
      created_at: formatTime(u.created_at),
    }));
  } catch (err: any) {
    ElMessage.error("加载用户失败: " + (err.message || err.response?.data?.detail || '未知错误'));
    console.error("加载用户失败:", err);
  } finally {
    tableLoading.value = false;
  }
};

const onEdit = (user: User) => {
  editUser.value = user;
  form.name = user.name;
  form.userType = user.userType;
  form.password = "";

  nextTick(() => {
    showDialog.value = true;
    if (formRef.value) {
       formRef.value.clearValidate();
    }
  });
};

const onDelete = async (user: User) => {
  ElMessageBox.confirm(
    `确定要删除用户 "${user.name}" 吗？此操作不可恢复。`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    try {
      await deleteUser(user.id);
      ElMessage.success("用户删除成功");
      loadUsers();
    } catch (err: any) {
      ElMessage.error(err.response?.data?.detail || "删除失败");
      console.error("删除用户失败:", err);
    }
  })
  .catch(() => {
  });
};

const onSubmit = async () => {
  if (!editUser.value || !formRef.value) return;

  formRef.value.validate(async (valid) => {
    if (valid) {

      const changed = form.name !== editUser.value!.name ||
                      form.password.trim() !== '' ||
                      form.userType !== editUser.value!.userType;

      if (!changed) {
        ElMessage.warning("请至少修改用户名、密码或用户类型中的一项");
        return;
      }

      submitLoading.value = true;
      try {
        const data: any = {};
        if (form.name !== editUser.value!.name) data.name = form.name.trim();
        if (form.password.trim()) data.password = form.password.trim();
        if (form.userType !== editUser.value!.userType) data.userType = form.userType;

        await updateUser(editUser.value!.id, data);
        ElMessage.success("用户更新成功");
        showDialog.value = false;
        editUser.value = null;
        loadUsers();
      } catch (err: any) {
        ElMessage.error(err.response?.data?.detail || "操作失败");
        console.error("更新用户失败:", err);
      } finally {
        submitLoading.value = false;
      }
    } else {
      console.log('表单校验失败!');
    }
  });
};

const handleDialogClose = (done: () => void) => {
    resetForm();
    done();
};

const resetForm = () => {
    form.name = '';
    form.password = '';
    form.userType = 'user';

    nextTick(() => {
        if (formRef.value) {
            formRef.value.resetFields();
            formRef.value.clearValidate();
        }
    });
};

onMounted(loadUsers);
</script>

<style scoped>
.user-management .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.dialog-footer {
  text-align: right;
}
</style>



