<template>
  <el-container style="min-height: 100vh">
    <!-- 左侧导航 -->
    <el-aside :width="sideWidth+'px'" style="background-color: rgb(238, 241, 246); box-shadow: 2px 0 6px rgb(0 21 41 / 35%)">
      <Aside :isCollapse="isCollapse" :logoTextShow="logoTextShow"/>
    </el-aside>

    <el-container>
      <!-- 顶部导航 -->
      <el-header style="border-bottom:1px solid #ccc;">
        <Header :collapseBtnClass="collapseBtnClass" :collapse="collapse"/>
      </el-header>
      <el-main>
        <div class="app-container">
          <el-row :gutter="20" justify="center">
            <!-- 左侧个人信息展示 -->
            <el-col :span="8" :xs="24">
              <el-card class="profile-card">
                <div slot="header" class="clearfix profile-header">
                  <span>个人信息</span>
                </div>
                <div class="text-center">
                </div>
                <ul class="profile-info">
                  <li>
                    <svg-icon icon-class="user" /> 昵称
                    <div class="info-value">{{ user.nickName || "暂无数据" }}</div>
                  </li>
                  <li>
                    <svg-icon icon-class="user" /> 姓名
                    <div class="info-value">{{ user.userName || "暂无数据" }}</div>
                  </li>
                  <li>
                    <svg-icon icon-class="id-card" /> 学号
                    <div class="info-value">{{ user.studentnumber || "暂无数据" }}</div>
                  </li>
                  <li>
                    <svg-icon icon-class="phone" /> 手机号码
                    <div class="info-value">{{ user.phonenumber || "暂无数据" }}</div>
                  </li>
                  <li>
                    <svg-icon icon-class="email" /> 邮箱
                    <div class="info-value">{{ user.email || "暂无数据" }}</div>
                  </li>
                  <li>
                    <svg-icon icon-class="book" /> 年级
                    <div class="info-value">{{ user.grade || "暂无数据" }}</div>
                  </li>
                  <li>
                    <svg-icon icon-class="tree" /> 班级
                    <div class="info-value">{{ user.class1 || "暂无数据" }}</div>
                  </li>
                  <li>
                    <svg-icon icon-class="user-tie" /> 辅导员
                    <div class="info-value">{{ user.teacherName || "暂无数据" }}</div>
                  </li>
                  <li></li>
                  <li></li>
                  <li></li>
                  <li></li>
                </ul>
              </el-card>
            </el-col>

            <!-- 右侧更新个人信息和修改密码 -->
            <el-col :span="8" :xs="24">
              <el-card class="profile-card1">
                <div slot="header" class="clearfix profile-header">
                  <span>账户设置</span>
                </div>
                <!-- 基本资料和修改密码标签 -->
                <el-tabs v-model="activeTab" type="card">
                  <el-tab-pane label="基本资料" name="profile">
                    <el-form :model="userForm" ref="userForm" label-width="100px">
                      <el-form-item label="昵称">
                        <el-input v-model="userForm.nickName" placeholder="请输入昵称"></el-input>
                      </el-form-item>
                      <el-form-item label="姓名">
                        <el-input v-model="userForm.userName" placeholder="请输入姓名"></el-input>
                      </el-form-item>
                      <el-form-item label="学号">
                        <el-input v-model="userForm.studentnumber" placeholder="请输入学号"></el-input>
                      </el-form-item>
                      <el-form-item label="手机号码">
                        <el-input v-model="userForm.phonenumber" placeholder="请输入手机号码"></el-input>
                      </el-form-item>
                      <el-form-item label="邮箱">
                        <el-input v-model="userForm.email" placeholder="请输入邮箱"></el-input>
                      </el-form-item>
                      <el-form-item label="年级">
                        <el-input v-model="userForm.grade" placeholder="请输入年级" :disabled="true"></el-input>
                      </el-form-item>
                      <el-form-item label="班级">
                        <el-input v-model="userForm.class1" placeholder="请输入班级" :disabled="true"></el-input>
                      </el-form-item>
                      <el-form-item label="辅导员">
                        <el-input v-model="userForm.teacherName" placeholder="请输入辅导员" :disabled="true"></el-input>
                      </el-form-item>
                      <el-form-item>
                        <el-button type="primary" @click="saveUserProfile">保存</el-button>
                      </el-form-item>
                    </el-form>
                  </el-tab-pane>

                  <el-tab-pane label="修改密码" name="password">
                    <el-form :model="passwordForm" ref="passwordForm" label-width="100px">
                      <el-form-item label="旧密码">
                        <el-input type="password" v-model="passwordForm.oldPassword" placeholder="请输入旧密码"></el-input>
                      </el-form-item>
                      <el-form-item label="新密码">
                        <el-input type="password" v-model="passwordForm.newPassword" placeholder="请输入新密码"></el-input>
                      </el-form-item>
                      <el-form-item label="确认密码">
                        <el-input type="password" v-model="passwordForm.confirmPassword" placeholder="确认新密码"></el-input>
                      </el-form-item>
                      <el-form-item>
                        <el-button type="primary" @click="updatePassword">更新密码</el-button>
                      </el-form-item>
                    </el-form>
                  </el-tab-pane>
                </el-tabs>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import Header from "@/components/Student/Header.vue";
import Aside from "@/components/Student/Aside.vue";
import axios from "axios";

export default {
  name: "Profile",
  components: { Aside, Header },
  data() {
    return {
      collapseBtnClass: 'el-icon-s-fold',
      isCollapse: false,
      sideWidth: 200,
      logoTextShow: true,
      user: {
        nickName: "",
        userName: "",
        studentnumber: "",
        phonenumber: "",
        email: "",
        class1: "",
        grade: "",
        teacherName: "",
        avatar: ""
      },
      userForm: {
        nickName: "",
        userName: "",
        studentnumber: "",
        phonenumber: "",
        email: "",
        class1: "",
        grade: "",
        teacherName: ""
      },
      defaultAvatar: "https://via.placeholder.com/150",
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      activeTab: 'profile', // 默认显示"基本资料"标签页
    };
  },
  methods: {
    collapse() {
      this.isCollapse = !this.isCollapse;
      if (this.isCollapse) {
        this.sideWidth = 64;
        this.collapseBtnClass = 'el-icon-s-unfold';
        this.logoTextShow = false;
      } else {
        this.sideWidth = 200;
        this.collapseBtnClass = 'el-icon-s-fold';
        this.logoTextShow = true;
      }
    },
    async fetchUserProfile() {
      try {
        const token = this.$store.state.tokens[this.userId];
        if (!token) {
          alert("用户未登录，请重新登录！");
          this.$router.push('/login');
          return false;
        }
        const response = await axios.get(`http://localhost:8080/student/homepage/getUser`, {
          headers: {
            Authorization: `Bearer ${token}`,
            'Content-Type': 'application/json',
          },
        });
        this.user = response.data.data;
        // 初始化右侧表单数据
        this.userForm = { ...this.user };
      } catch (error) {
        this.$message.error("获取个人信息失败");
        console.error(error);
      }
    },
    saveUserProfile() {
      const token = this.$store.state.token[this.userId];
      if (!token) {
        alert("用户未登录，请重新登录！");
        this.$router.push('/login');
        return false;
      }
      // 发起请求更新用户资料
      console.log("保存用户资料:", this.userForm);
      axios.put('http://localhost:8080/system/user/profile', this.userForm,{
        headers: {
          Authorization: `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
      })
          .then(response => {
            console.log(response.data);
            if (response.data.code==200) {
              this.$message.success("更新成功");
              // 成功后更新左侧数据
              this.user = { ...this.userForm };
            } else {
              this.$message.error("更新失败");
            }
          })
          .catch(error => {
            this.$message.error("请求失败");
            console.error(error);
          });
    },
    updatePassword() {
      const token = this.$store.state.token[this.userId];
      if (!token) {
        alert("用户未登录，请重新登录！");
        this.$router.push('/login');
        return false;
      }
      if (this.passwordForm.newPassword !== this.passwordForm.confirmPassword) {
        this.$message.error("新密码和确认密码不一致");
        return;
      }
      // 更新密码的请求处理逻辑
      // console.log("修改密码:", this.passwordForm);
      axios.put('http://localhost:8080/system/user/profile/updatePwd', this.passwordForm,{
        params:{oldPassword:this.passwordForm.oldPassword,
                newPassword: this.passwordForm.newPassword,},
        headers: {
          Authorization: `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
      })
          .then(response => {
            if (response.data.code==200) {
              this.$message.success("密码更新成功，请重新登录");
              this.$store.dispatch("logout"); // 调用 Vuex 登出逻辑
              this.$router.push("/login"); // 跳转到登录页面
            } else {
              this.$message.error("密码更新失败");
            }
          })
          .catch(error => {
            this.$message.error("请求失败");
            console.error(error);
          });
    },
  },
  mounted() {
    this.fetchUserProfile();
  },
  created() {
    this.userId = this.$route.query.userId;
  }
};
</script>

<style scoped lang="scss">
.aside {
  background-color: rgb(238, 241, 246);
  box-shadow: 2px 0 6px rgb(0 21 41 / 35%);
}

.header {
  border-bottom: 1px solid #ccc;
}

.app-container {
  padding: 20px;
}

.profile-card {
  background: linear-gradient(135deg, #ffffff, #f6f9fc);
  border: 1px solid #dfe4ea;
  box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease-in-out;
}

.profile-card:hover {
  transform: translateY(-8px);
  box-shadow: 0px 6px 16px rgba(0, 0, 0, 0.15);
}

.profile-header {
  font-weight: bold;
  font-size: 18px;
  text-align: center;
  color: #2f3542;
  padding: 10px 0;
  border-bottom: 1px solid #ebebeb;
}

.user-avatar {
  margin: 20px 0;
  border: 3px solid #74b9ff;
  transition: all 0.3s ease-in-out;
  cursor: pointer;
}

.user-avatar:hover {
  transform: scale(1.1);
  border-color: #0984e3;
}

.profile-info {
  list-style: none;
  padding: 0;
  margin: 20px 0 0 0;
}

.profile-info li {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px dashed #dfe4ea;
}

.profile-info li:last-child {
  border-bottom: none;
}

.profile-info li svg-icon {
  margin-right: 10px;
}

.info-value {
  font-weight: 600;
  color: #34495e;
  background: #f1f2f6;
  padding: 4px 8px;
  border-radius: 4px;
  text-align: right;
  width: 50%;
}

.update-container {
  display: flex;
  flex-direction: column;
}

.sub-card {
  background: #fff;
  border: 1px solid #dfe4ea;
  box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
  margin-bottom: 20px;
}

.sub-card:hover {
  transform: translateY(-8px);
  box-shadow: 0px 6px 16px rgba(0, 0, 0, 0.15);
}

.profile-card1 {
  width: 800px;
  height: 622.66px;
  background: linear-gradient(135deg, #ffffff, #f6f9fc);
  border: 1px solid #dfe4ea;
  box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease-in-out;
}

.profile-card1:hover {
  transform: translateY(-8px);
  box-shadow: 0px 6px 16px rgba(0, 0, 0, 0.15);
}
</style>
