<template>
  <div class="container">
      <div class="box">
    <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) {
  // 在这里打印两个表单的数据到控制台
  console.log("Admin login form data:", this.adminLoginForm);
  console.log("User login form data:", this.userLoginForm);

  let loginData = role === "admin" ?  this.adminLoginForm : this.userLoginForm ;
  
  // 如果需要，也可以在这里打印将要发送的登录数据
  console.log("Sending login data:", loginData);

  return axios.post(`/user/login`, loginData);
},
login(role) {
  console.log("Login as", 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 (response.data.success) {
            if (role === "admin") {
              localStorage.setItem("adminname", this.adminLoginForm.username);
              bus.$emit("login-success", this.adminLoginForm.username);
              this.adminname = this.adminLoginForm.username;
              this.$router.push("/First");
            } else if (role === "user") {
              localStorage.setItem("username", this.userLoginForm.username);
              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");
        });
    } else {
      MessageBox.alert("表单验证失败，请检查输入", "错误");
    }
  });
},
    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>
/* 定义渐变红色 */
.gradient-red {
  background: linear-gradient(135deg, red, #ff4c4c);
}

.container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center;     /* 垂直居中 */
  height: 100vh;           /* 视口高度 */
  width: 100vw;            /* 视口宽度 */
  /* 应用渐变红色到容器 */
  background: linear-gradient(135deg, red, #ff4c4c);
}

.box {
  width: 310px;
  height: 330px;
  padding: 20px; /* 为内容提供一些内边距 */
  box-sizing: border-box; /* 确保padding不会增加元素的总宽度和高度 */
  /* 为 .box 设置非渐变背景 */
  background-color: white; /* 或者其他你想要的颜色 */
  /* 使用Flexbox来让子元素居中 */
  display: flex;
  flex-direction: column;
  justify-content: center; /* 垂直居中 */
  align-items: stretch;    /* 让子元素拉伸以填充整个宽度 */
  /* 添加圆角 */
  border-radius: 10px;     /* 圆角大小，可以根据需要调整 */
}

.el-tabs__content {
  padding: 20px;
  /* 让表单内容也居中 */
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: stretch;    /* 让子元素拉伸以填充整个宽度 */
  width: 100%;
}

/* 确保 el-form-item 内容从左侧开始 */
.el-form-item {
  width: 100%; /* 让每个表单项占据全部宽度 */
  margin-bottom: 16px; /* 保持表单项之间的间距 */
}


/* 自定义的 .el-form-item__label 样式 */
/deep/.el-form-item__label {

  text-align: left;
  vertical-align: middle;
  float: left;
  font-size: 14px;
  color: #606266;
  line-height: 40px;
  padding: 0 30px 0 0;
  box-sizing: border-box;
}

/deep//* 确保输入框和选择器等控件也适应宽度 */
.el-input,
.el-select {
  width: 100%;
}

.button-container {
  /* 使用Flexbox让内容水平居中 */
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center;     /* 垂直居中 */
  gap: 10px;               /* 设置按钮间的间距 */
}

/deep/.el-form-item[data-v-6fb8cde2] {
    width: 100%;
    margin-bottom: 16px;
    justify-content: center;
}</style>
让.el-form-item标签中的登录和重置按钮居中排布