<template>
  <ManageLayout>
    <div class="user-manage-page">
      <!-- 搜索和操作按钮 -->
      <div class="mb-6 flex justify-between items-center">
        <div class="flex items-center">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索用户名、邮箱或手机号"
            style="width: 300px; margin-right: 16px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <i class="fa fa-search"></i>
            </template>
          </el-input>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </div>
        <el-button type="success" @click="showAddUserDialog = true">
          <i class="fa fa-plus mr-1"></i> 添加用户
        </el-button>
      </div>

      <!-- 用户表格 -->
      <el-table
        :data="paginatedUsers"
        style="width: 100%"
        v-loading="loading"
        border
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="nickname" label="昵称" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="{ row }">
            {{ row.gender === 1 ? "男" : row.gender === 0 ? "女" : "未知" }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? "启用" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isAdmin" label="管理员" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isAdmin === 1 ? 'warning' : 'info'">
              {{ row.isAdmin === 1 ? "是" : "否" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="380">
          <template #default="{ row }">
            <el-button size="small" @click="editUser(row)">编辑</el-button>
            <el-button
              size="small"
              :type="row.status === 1 ? 'warning' : 'success'"
              @click="toggleUserStatus(row)"
            >
              {{ row.status === 1 ? "禁用" : "启用" }}
            </el-button>
            <el-button
              size="small"
              :type="row.isAdmin === 1 ? 'info' : 'primary'"
              @click="toggleAdminStatus(row)"
            >
              {{ row.isAdmin === 1 ? "取消管理员" : "设为管理员" }}
            </el-button>
            <el-button size="small" type="danger" @click="deleteUser(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-6 flex justify-center">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredUsers.length"
        />
      </div>

      <!-- 添加/编辑用户对话框 -->
      <el-dialog
        :title="isEditing ? '编辑用户' : '添加用户'"
        v-model="showAddUserDialog"
        width="500px"
      >
        <el-form
          :model="userForm"
          :rules="userFormRules"
          ref="userFormRef"
          label-width="80px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userForm.username" :disabled="isEditing" />
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="userForm.nickname" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="userForm.phone" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userForm.email" />
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="userForm.gender">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="0">女</el-radio>
              <el-radio :label="2">未知</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="密码" prop="password" :required="!isEditing">
            <el-input
              v-model="userForm.password"
              type="password"
              :placeholder="isEditing ? '不填写则不修改密码' : '请输入密码'"
            />
          </el-form-item>
          <el-form-item label="头像">
            <el-input v-model="userForm.avatar" placeholder="头像URL" />
          </el-form-item>
          <el-form-item label="管理员">
            <el-switch
              v-model="userForm.isAdmin"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="showAddUserDialog = false">取消</el-button>
            <el-button type="primary" @click="submitUserForm">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </ManageLayout>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getUserList, updateUserProfile, userRegister } from "@/apis/user";
import { UserDTO } from "@/types/user";
import ManageLayout from "@/layouts/ManageLayout.vue";
import { useRouter } from "vue-router";
import { useUserStore } from "@/stores/UserStore";

// 获取用户存储和路由
const userStore = useUserStore();
const router = useRouter();

// 响应式数据
const loading = ref(false);
const searchKeyword = ref("");
const showAddUserDialog = ref(false);
const isEditing = ref(false);
const userFormRef = ref();

// 分页数据
const currentPage = ref(1);
const pageSize = ref(10);

// 用户表单
const userForm = ref<UserDTO>({
  id: undefined,
  username: "",
  password: "",
  phone: "",
  email: "",
  avatar: "",
  nickname: "",
  gender: 2,
  status: 1,
  isAdmin: 0,
});

// 所有用户数据
const users = ref<UserDTO[]>([]);

// 用户表单验证规则
const userFormRules = reactive({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      min: 3,
      max: 20,
      message: "用户名长度应在3-20个字符之间",
      trigger: "blur",
    },
  ],
  password: [
    { required: !isEditing.value, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度应在6-20个字符之间", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号格式",
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" },
  ],
});

// 计算属性：根据搜索关键词过滤用户
const filteredUsers = computed(() => {
  if (!searchKeyword.value) return users.value;

  return users.value.filter(
    (user) =>
      user.username?.includes(searchKeyword.value) ||
      user.email?.includes(searchKeyword.value) ||
      user.phone?.includes(searchKeyword.value) ||
      user.nickname?.includes(searchKeyword.value),
  );
});

// 计算属性：当前页的用户数据
const paginatedUsers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredUsers.value.slice(start, end);
});

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true;
  try {
    const response = await getUserList();
    users.value = response.data || [];
  } catch (error) {
    console.error("获取用户列表错误:", error);
    ElMessage.error("获取用户列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1; // 重置到第一页
};

// 分页大小改变
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
};

// 当前页改变
const handleCurrentChange = (page: number) => {
  currentPage.value = page;
};

// 编辑用户
const editUser = (user: UserDTO) => {
  isEditing.value = true;
  // 复制用户数据，但不包含密码字段（编辑时不需要密码）
  userForm.value = {
    ...user,
    password: "", // 编辑时不显示密码，需要时重新输入
  };
  showAddUserDialog.value = true;
};

// 切换用户状态（启用/禁用）
const toggleUserStatus = async (user: UserDTO) => {
  try {
    await ElMessageBox.confirm(
      `确定要${user.status === 1 ? "禁用" : "启用"}用户 "${user.username}" 吗？`,
      "确认操作",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      },
    );

    // 准备更新数据，只更新状态
    const updateData = {
      ...user,
      status: user.status === 1 ? 0 : 1,
    };

    // 调用更新用户信息API
    await updateUserProfile(updateData);

    // 更新本地数据
    const index = users.value.findIndex((u) => u.id === user.id);
    if (index !== -1) {
      users.value[index] = { ...updateData };
    }
    ElMessage.success(`${user.status === 1 ? "禁用" : "启用"}成功`);
  } catch (error) {
    console.error("切换用户状态错误:", error);
    if (error !== "cancel") {
      ElMessage.error("操作失败");
    }
  }
};

// 切换管理员状态
const toggleAdminStatus = async (user: UserDTO) => {
  try {
    await ElMessageBox.confirm(
      `确定要${user.isAdmin === 1 ? "取消" : "设置"}用户 "${user.username}" 为管理员吗？`,
      "确认操作",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: user.isAdmin === 1 ? "warning" : "primary",
      },
    );

    // 准备更新数据，只更新管理员状态
    const updateData = {
      ...user,
      isAdmin: user.isAdmin === 1 ? 0 : 1,
    };

    // 调用更新用户信息API
    await updateUserProfile(updateData);

    // 更新本地数据
    const index = users.value.findIndex((u) => u.id === user.id);
    if (index !== -1) {
      users.value[index] = { ...updateData };
    }
    ElMessage.success(
      `${user.isAdmin === 1 ? "取消管理员" : "设为管理员"}成功`,
    );
  } catch (error) {
    console.error("切换管理员状态错误:", error);
    if (error !== "cancel") {
      ElMessage.error("操作失败");
    }
  }
};

// 删除用户
const deleteUser = async (user: UserDTO) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.username}" 吗？此操作不可恢复！`,
      "警告",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      },
    );

    // 在实际应用中，这里应该调用删除API
    // 但根据后端设计，我们使用更新状态的方式
    const updateData = {
      ...user,
      status: 0, // 设置为禁用状态
    };

    await updateUserProfile(updateData);

    // 从本地数据中过滤掉已禁用的用户（如果需要完全隐藏的话）
    users.value = users.value.filter((u) => u.id !== user.id);
    ElMessage.success("操作成功");
  } catch (error) {
    console.error("删除用户错误:", error);
    if (error !== "cancel") {
      ElMessage.error("操作失败");
    }
  }
};

// 提交用户表单
const submitUserForm = async () => {
  try {
    // 验证表单
    const form = userFormRef.value;
    if (!form) return;

    await form.validate();

    if (isEditing.value) {
      // 更新用户
      await updateUserProfile(userForm.value);

      // 更新本地数据
      const index = users.value.findIndex((u) => u.id === userForm.value.id);
      if (index !== -1) {
        users.value[index] = { ...userForm.value };
      }
      ElMessage.success("更新成功");
    } else {
      // 添加新用户 - 使用专门的管理员添加用户API
      // 如果后端没有专门的API，我们使用注册API，但需要确保密码字段存在
      if (!userForm.value.password) {
        ElMessage.error("添加用户时必须设置密码");
        return;
      }

      // 调用注册API来添加新用户
      const response = await userRegister({
        username: userForm.value.username,
        password: userForm.value.password,
        phone: userForm.value.phone,
        email: userForm.value.email,
        nickname: userForm.value.nickname || undefined,
        gender: userForm.value.gender,
        avatar: userForm.value.avatar || undefined,
        isAdmin: userForm.value.isAdmin,
      });

      // 检查响应
      if (response.code === 200) {
        ElMessage.success("添加成功");
      } else {
        ElMessage.error(response.message || "添加失败");
        return;
      }
    }

    showAddUserDialog.value = false;
    fetchUsers(); // 重新获取用户列表
  } catch (error) {
    console.error("提交用户表单错误:", error);
    if (error) {
      console.log(error);
    } else {
      ElMessage.error("提交失败");
    }
  }
};

// 初始化
onMounted(() => {
  if (userStore.userInfo?.isAdmin !== 1) {
    ElMessage.error("您没有管理员权限！");
    router.push("/");
  }
  fetchUsers();
});
</script>

<style scoped>
.user-manage-page {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.dialog-footer {
  text-align: right;
}
</style>
