<template>
  <div class="change-info-container">
    <h2 class="title">修改个人信息</h2>

    <!-- 头像区域 -->
    <div class="avatar-section">
      <p class="section-title">头像</p>
      <div class="avatar-preview">
        <img 
          :src="currentAvatar || defaultAvatar" 
          :onerror="handleAvatarError"
          alt="当前头像" 
          class="current-avatar"
        >
        <img v-if="previewAvatar" :src="previewAvatar" alt="新头像预览" class="new-avatar">
      </div>
      <label class="upload-btn">
        <span class="plus-icon">+</span>
        选择新头像
        <input type="file" accept="image/*" @change="handleAvatarChange" class="file-input">
      </label>
      <p v-if="errors.avatar" class="error-tip">{{ errors.avatar }}</p>
    </div>

    <!-- 表单 -->
    <form @submit.prevent="handleSubmit" class="form">
      <div class="form-row">
        <!-- 用户名 -->
        <div class="form-item half">
          <label class="label">用户名</label>
          <input
            type="text"
            v-model.trim="formData.username"
            class="input"
            :class="{ 'input-error': errors.username }"
            maxlength="20"
            placeholder="请输入用户名"
          >
          <p v-if="errors.username" class="error-tip">{{ errors.username }}</p>
        </div>
        <!-- 手机号 -->
        <div class="form-item half">
          <label class="label">手机号</label>
          <input
            type="text"
            v-model.trim="formData.phone"
            class="input"
            :class="{ 'input-error': errors.phone }"
            maxlength="11"
            placeholder="请输入11位手机号"
          >
          <p v-if="errors.phone" class="error-tip">{{ errors.phone }}</p>
        </div>
      </div>

      <div class="form-row">
        <!-- 邮箱 -->
        <div class="form-item half">
          <label class="label">邮箱</label>
          <input
            type="email"
            v-model.trim="formData.email"
            class="input"
            :class="{ 'input-error': errors.email }"
            placeholder="请输入邮箱"
          >
          <p v-if="errors.email" class="error-tip">{{ errors.email }}</p>
        </div>
        <!-- 学号 -->
        <div class="form-item half">
          <label class="label">学号</label>
          <input
            type="text"
            v-model.trim="formData.studentId"
            class="input"
            :class="{ 'input-error': errors.studentId }"
            maxlength="20"
            placeholder="请输入学号"
          >
          <p v-if="errors.studentId" class="error-tip">{{ errors.studentId }}</p>
        </div>
      </div>

      <div class="form-row">
        <!-- 性别 -->
        <div class="form-item half">
          <label class="label">性别</label>
          <select v-model="formData.gender" class="input" :class="{ 'input-error': errors.gender }">
            <option value="0">未知</option>
            <option value="1">男</option>
            <option value="2">女</option>
          </select>
          <p v-if="errors.gender" class="error-tip">{{ errors.gender }}</p>
        </div>
        <!-- 学院 -->
        <div class="form-item half">
          <label class="label">学院</label>
          <input
            type="text"
            v-model.trim="formData.college"
            class="input"
            :class="{ 'input-error': errors.college }"
            maxlength="30"
            placeholder="请输入学院"
          >
          <p v-if="errors.college" class="error-tip">{{ errors.college }}</p>
        </div>
      </div>

      <!-- 个人简介 -->
      <div class="form-item">
        <label class="label">个人简介</label>
        <textarea
          v-model.trim="formData.moto"
          rows="4"
          class="textarea"
          :class="{ 'input-error': errors.moto }"
          maxlength="100"
          placeholder="请输入个人简介（最多100字）"
        ></textarea>
        <p v-if="errors.moto" class="error-tip">{{ errors.moto }}</p>
      </div>

      <!-- 密码 -->
      <div class="form-item">
        <label class="label">新密码</label>
        <input
          type="password"
          v-model.trim="formData.password"
          class="input"
          :class="{ 'input-error': errors.password }"
          placeholder="如需修改请输入新密码"
        >
        <p v-if="errors.password" class="error-tip">{{ errors.password }}</p>
      </div>

      <button type="submit" class="submit-btn">保存修改</button>
    </form>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useUserStore } from '@/stores/user';
import request from '@/utils/request';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';

const userStore = useUserStore();
const userInfo = computed(() => userStore.userInfo);
const router = useRouter();

// 默认头像
const defaultAvatar = require('@/assets/default-avatar/boy_1.png');

// 处理头像加载错误
const handleAvatarError = "this.onerror=null;this.src='" + defaultAvatar + "'";

// 初始化表单数据
const formData = ref({
  username: '',
  phone: '',
  email: '',
  studentId: '',
  gender: '0',
  college: '',
  moto: '',
  password: ''
});

const avatarFile = ref(null);
const previewAvatar = ref('');
const currentAvatar = ref('');
const errors = ref({});
const loading = ref(false);

// 加载用户详细信息
const loadUserInfo = async () => {
  loading.value = true;
  
  try {
    // 先从store中获取基本信息
    formData.value.username = userStore.userInfo.username || '';
    currentAvatar.value = userStore.userInfo.avatar || '';
    
    // 从localStorage恢复基本信息
    if (!formData.value.username) {
      formData.value.username = localStorage.getItem('username') || '';
      currentAvatar.value = localStorage.getItem('avatar') || '';
    }
    
    // 从API获取详细信息
    const response = await request.get('/user/info/getuserinfo', {
      params: { userId: userStore.userInfo.userid || localStorage.getItem('userId') }
    });
    
    if (response && response.code === 200 && response.data) {
      // 填充表单数据
      formData.value = {
        username: response.data.username || formData.value.username,
        phone: response.data.phone || '',
        email: response.data.email || '',
        studentId: response.data.studentId || '',
        gender: response.data.gender !== undefined ? String(response.data.gender) : '0',
        college: response.data.college || '',
        moto: response.data.moto || '',
        password: ''  // 密码不从API获取
      };
      
      // 更新头像
      if (response.data.avatar) {
        currentAvatar.value = response.data.avatar;
      }
      
      console.log('成功加载用户信息:', formData.value);
    } else {
      console.warn('获取用户信息失败或返回数据为空');
    }
  } catch (error) {
    console.error('加载用户信息失败:', error);
    ElMessage.warning('获取用户信息失败，请稍后再试');
  } finally {
    loading.value = false;
  }
};

// 处理头像选择
const handleAvatarChange = (e) => {
  const file = e.target.files[0];
  if (!file) return;

  if (!file.type.startsWith('image/')) {
    errors.value.avatar = '请选择图片文件（jpg/png等）';
    return;
  }
  if (file.size > 5 * 1024 * 1024) {
    errors.value.avatar = '图片大小不能超过5MB';
    return;
  }

  errors.value.avatar = null;
  const reader = new FileReader();
  reader.onload = (e) => previewAvatar.value = e.target.result;
  reader.readAsDataURL(file);
  avatarFile.value = file;
};

// 表单验证（根据接口文档规则）
const validateForm = () => {
  const newErrors = {};

  // 昵称验证（接口要求：必填，≤20字符）
  if (!formData.value.username) {
    newErrors.username = '用户名不能为空';
  } else if (formData.value.username.length > 20) {
    newErrors.username = '用户名最多20字符';
  }

  // 手机号
  if (!formData.value.phone) {
    newErrors.phone = '手机号不能为空';
  } else if (!/^\d{11}$/.test(formData.value.phone)) {
    newErrors.phone = '手机号格式不正确';
  }

  // 邮箱
  if (!formData.value.email) {
    newErrors.email = '邮箱不能为空';
  } else if (!/^[\w.-]+@[\w.-]+\.\w+$/.test(formData.value.email)) {
    newErrors.email = '邮箱格式不正确';
  }

  // 学号
  if (!formData.value.studentId) {
    newErrors.studentId = '学号不能为空';
  } else if (formData.value.studentId.length > 20) {
    newErrors.studentId = '学号最多20字符';
  }

  // 性别
  if (!['0', '1', '2'].includes(formData.value.gender)) {
    newErrors.gender = '请选择性别';
  }

  // 学院
  if (!formData.value.college) {
    newErrors.college = '学院不能为空';
  } else if (formData.value.college.length > 30) {
    newErrors.college = '学院最多30字符';
  }

  // 简介
  if (formData.value.moto && formData.value.moto.length > 100) {
    newErrors.moto = '简介最多100字符';
  }

  // 密码
  if (formData.value.password && formData.value.password.length < 6) {
    newErrors.password = '密码长度不能少于6位';
  }

  errors.value = newErrors;
  return Object.keys(newErrors).length === 0;
};

// 提交表单
const handleSubmit = async () => {
  if (!validateForm()) return;

  try {
    let avatarUrl = userInfo.value.avatar;

    // 如果选择了新头像，先上传头像
    if (avatarFile.value) {
      const formDataObj = new FormData();
      formDataObj.append('file', avatarFile.value);
      console.log('正在上传头像...');
      
      const uploadRes = await request.post('/user/info/avatar', formDataObj, {
        headers: { 'Content-Type': 'multipart/form-data' }
      });
      console.log('头像上传响应:', uploadRes);
      
      if (uploadRes.code !== 200 || !uploadRes.data) {
        throw new Error(uploadRes.msg || '头像上传失败');
      }
      
      avatarUrl = uploadRes.data;
      console.log('获取到的头像URL:', avatarUrl);
      currentAvatar.value = avatarUrl;
    }

    // 修改用户信息
    const updateInfoData = {
      username: formData.value.username,
      phone: formData.value.phone,
      email: formData.value.email,
      studentId: formData.value.studentId,
      avatar: avatarUrl, // 确保使用新上传的头像URL
      gender: Number(formData.value.gender),
      college: formData.value.college,
    };
    
    console.log('提交的用户信息:', updateInfoData);
    const updateInfoRes = await request.post('/user/info/update', updateInfoData);
    
    if (updateInfoRes.code !== 200) {
      throw new Error(updateInfoRes.msg || '修改用户信息失败');
    }
    
    // 更新全局用户状态
    userStore.updateUserInfo({
      ...updateInfoData,
      userid: userInfo.value.userid,
      role: userInfo.value.role,
      status: userInfo.value.status
    });
    
    if (formData.value.password) {
      const passwordRes = await request.post('/user/info/password', null, {
        params: { password: formData.value.password }
      });
      if (passwordRes.code !== 200) {
        throw new Error(passwordRes.msg || '修改密码失败');
      }
    }

    ElMessage.success('修改成功！');
    router.push('/');
 
  } catch (error) {
    console.error('修改失败:', error);
    ElMessage.error(`修改失败：${error.message}`);
  }
};

// 页面加载时获取用户信息
onMounted(() => {
  loadUserInfo();
});
</script>

<style scoped>
.change-info-container {
  max-width: 700px;
  margin: 2rem auto;
  padding: 2.5rem 2rem 2rem 2rem;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  position: relative;
}

.title {
  color: #2c3e50;
  font-size: 1.7rem;
  font-weight: 700;
  margin-bottom: 2.2rem;
  letter-spacing: 1px;
  text-align: center;
  border-bottom: 2px solid #ff88aa;
  padding-bottom: 10px;
}

.section-title {
  color: #34495e;
  font-size: 1.1rem;
  font-weight: 500;
  margin-bottom: 1rem;
}

.avatar-section {
  margin-bottom: 2rem;
  padding-bottom: 2rem;
  border-bottom: 1px solid #e0e0e0;
}

.avatar-preview {
  display: flex;
  align-items: center;
  gap: 1.5rem;
  margin-bottom: 1rem;
}

.current-avatar, .new-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #bdc3c7;
  background: #fff;
}

.new-avatar {
  border-color: #ff88aa;
}

.upload-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 0.5rem 1.2rem;
  background: #ff88aa;
  color: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.95rem;
  font-weight: 500;
  transition: background 0.3s ease;
  margin-top: 0.5rem;
}

.upload-btn:hover {
  background: #ff6699;
}

.plus-icon {
  font-size: 20px;
  font-weight: bold;
}

.file-input {
  display: none;
}

.form {
  margin-top: 1.5rem;
}

.form-row {
  display: flex;
  gap: 2rem;
  margin-bottom: 1.5rem;
}

.form-item {
  margin-bottom: 1.5rem;
  flex: 1;
  min-width: 0;
}

.form-item.half {
  width: 50%;
}

.label {
  display: block;
  color: #34495e;
  font-size: 0.95rem;
  font-weight: 500;
  margin-bottom: 0.5rem;
}

.input, .textarea, select.input {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  font-size: 0.95rem;
  transition: border-color 0.3s ease;
  background: #f9f9f9;
}

.input:focus, .textarea:focus, select.input:focus {
  outline: none;
  border-color: #ff88aa;
  box-shadow: 0 0 0 2px rgba(255, 136, 170, 0.08);
}

.input-error {
  border-color: #e74c3c;
}

.error-tip {
  color: #e74c3c;
  font-size: 0.8rem;
  margin-top: 0.3rem;
}

.textarea {
  resize: vertical;
  min-height: 80px;
}

.submit-btn {
  width: 100%;
  padding: 0.85rem;
  background: #ff88aa;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: background 0.3s ease;
  margin-top: 0.5rem;
  letter-spacing: 1px;
}

.submit-btn:hover {
  background: #ff6699;
}

/* 花瓣动画（与背景呼应） */
@keyframes fall {
  0% { transform: translateY(-100vh) rotate(0deg); opacity: 1; }
  100% { transform: translateY(100vh) rotate(360deg); opacity: 0.5; }
}

.petal {
  position: absolute;
  width: 10px;
  height: 15px;
  background: pink;
  border-radius: 50% 50% 0 0;
  animation: fall 5s linear infinite;
  z-index: -1;
}

/* 初始化花瓣（可在mounted中动态生成，此处简化） */
.change-info-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  animation: none; /* 避免重复动画 */
}
</style>