<template>
  <div class="background-container">
    <div class="login-container">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="用户登录" name="userLogin">
        <el-form
          :model="userLoginForm"
          ref="userLoginForm"
          :rules="userLoginRules"
          label-width="120px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userLoginForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="userLoginForm.password" type="password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="login('user')">登录</el-button>
            <el-button @click="resetUserLoginForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="管理员登录" name="adminLogin">
        <el-form
          :model="adminLoginForm"
          ref="adminLoginForm"
          :rules="adminLoginRules"
          label-width="120px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="adminLoginForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="adminLoginForm.password" type="password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="login('admin')">登录</el-button>
            <el-button @click="resetAdminLoginForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="注册" name="register">
        <el-form
          :model="registerForm"
          ref="registerForm"
          :rules="registerRules"
          label-width="120px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="registerForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="registerForm.password" type="password"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="registerForm.confirmPassword" type="password"></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="role">
            <el-select v-model="registerForm.role">
              <el-option label="用户" value="user"></el-option>
              <el-option label="管理员" value="admin"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="register">注册</el-button>
            <el-button @click="resetRegisterForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
  </div>
  
</template>

<script>
import { MessageBox } from "element-ui";
import axios from "axios";
// 引入事件总线
import Vue from "vue";
const bus = new Vue();

export default {
  data() {
    return {
      activeTab: "userLogin",
      userLoginForm: {
        username: "",
        password: ""
      },
      userLoginRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }]
      },
      adminLoginForm: {
        username: "",
        password: ""
      },
      adminLoginRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }]
      },
      registerForm: {
        username: "",
        password: "",
        confirmPassword: "",
        role: "user"
      },
      registerRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, message: "密码长度至少为 6 位", trigger: "blur" }
        ],
        confirmPassword: [
          { required: true, message: "请再次输入密码", trigger: "blur" },
          { validator: this.validateConfirmPassword, trigger: "blur" }
        ],
        role: [{ required: true, message: "请选择角色", trigger: "change" }]
      }
    };
  },
  methods: {
    performLogin(role) {
      let loginData =
        role === "admin"? this.adminLoginForm : this.userLoginForm;
      return axios.post(`/user/login`, loginData);
    },
    login(role) {
      this.$refs[`${role}LoginForm`].validate(valid => {
        if (valid) {
          this.performLogin(role)
          .then(response => {
              console.log("登录成功:", response);
              MessageBox.alert(response.data.message, "登录成功");
              this.resetUserLoginForm();
              if (role === "admin" && response.data.success) {
                localStorage.setItem("adminname", this.adminLoginForm.username);
                // 触发事件传递用户名给 UserDashboard.vue
                bus.$emit("login-success", this.adminLoginForm.username);
                this.adminname = this.adminLoginForm.username;
                this.$router.push("/First");
              } else if (role === "user" && response.data.success) {
                localStorage.setItem("username", this.userLoginForm.username);
                // 触发事件传递用户名给 UserDashboard.vue
                bus.$emit("login-success", this.userLoginForm.username);
                this.username = this.userLoginForm.username;
                this.$router.push("/second");
              } else {
                MessageBox.alert("用户名或密码错误，请重试", "错误");
              }
            })
          .catch(error => {
              console.error("Login error:", error);
              MessageBox.alert("登录失败，请检查用户名和密码", "错误");
              localStorage.removeItem("userRole");
            });
        }
      });
    },
    register() {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          axios
          .post("/user/register", this.registerForm)
          .then(response => {
              MessageBox.alert(response.data.message, "注册成功");
              this.resetRegisterForm();
              this.activeTab = "userLogin";
            })
          .catch(error => {
              console.error(error);
              MessageBox.alert("注册失败，请稍后重试", "错误");
            });
        }
      });
    },
    validateConfirmPassword(rule, value, callback) {
      if (value === this.registerForm.password) {
        callback();
      } else {
        callback(new Error("两次输入密码不一致"));
      }
    },
    resetUserLoginForm() {
      this.$refs.userLoginForm.resetFields();
    },
    resetAdminLoginForm() {
      this.$refs.adminLoginForm.resetFields();
    },
    resetRegisterForm() {
      this.$refs.registerForm.resetFields();
    }
  }
};
</script>

<style scoped>
.background-container {
  background-color: red; /* 红色 */
  height: 100vh; /* 让容器占据整个视口高度 */
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-container {
  width: 100%;
  max-width: 280px; /* 设置最大宽度 */
  padding: 20px;
  background-color: white; /* 给表单区域设置白色背景 */
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
  border-radius: 8px; /* 圆角边框 */
}

.el-tabs__content {
  padding: 20px;
}
/* 使用深度选择器来覆盖Element UI的内部样式 */
::v-deep .el-form-item__label {
  width: auto !important; /* 标签宽度自动适应内容 */
  margin-right: 10px; /* 添加右边距以保持适当的间距 */
}

::v-deep .el-form-item__content {
  margin-left: 0 !important; /* 移除默认的左边距 */
  text-align: center;
}
</style>
为什么我用用户的用户名密码也可以登录管理员