<template>
  <div class="user-page-container">
    <div class="left-container">
      <div class="user-info-card">
        <div class="user-avatar">
          <img 
            :src="userInfo.avatar || defaultAvatar" 
            :onerror="handleAvatarError" 
            alt="用户头像" 
            class="avatar"
          />
        </div>
        <div class="user-details">
          <h2 class="username">{{ userInfo.username }}</h2>
          
          <div class="user-info-list">
            <div class="user-info-item" v-if="userInfo.college && (isCurrentUser || privacySettings.showCollege)">
              <span class="info-icon"><i class="el-icon-school"></i></span>
              <span class="info-label">学院：</span>
              <span class="info-value">{{ userInfo.college || '未设置' }}</span>
              <el-switch
                v-if="isCurrentUser"
                v-model="privacySettings.showCollege"
                active-text="公开"
                inactive-text="隐藏"
                @change="updatePrivacy"
                class="privacy-switch"
              />
            </div>
            <div class="user-info-item" v-if="isCurrentUser || privacySettings.showGender">
              <span class="info-icon"><i class="el-icon-user"></i></span>
              <span class="info-label">性别：</span>
              <span class="info-value">
                <span v-if="userInfo.gender === 1">男</span>
                <span v-else-if="userInfo.gender === 2">女</span>
                <span v-else>未知</span>
              </span>
              <el-switch
                v-if="isCurrentUser"
                v-model="privacySettings.showGender"
                active-text="公开"
                inactive-text="隐藏"
                @change="updatePrivacy"
                class="privacy-switch"
              />
            </div>
            <div class="user-info-item" v-if="userInfo.phone && (isCurrentUser || privacySettings.showPhone)">
              <span class="info-icon"><i class="el-icon-phone"></i></span>
              <span class="info-label">电话：</span>
              <span class="info-value">{{ userInfo.phone || '未设置' }}</span>
              <el-switch
                v-if="isCurrentUser"
                v-model="privacySettings.showPhone"
                active-text="公开"
                inactive-text="隐藏"
                @change="updatePrivacy"
                class="privacy-switch"
              />
            </div>
            <div class="user-info-item" v-if="userInfo.email && (isCurrentUser || privacySettings.showEmail)">
              <span class="info-icon"><i class="el-icon-message"></i></span>
              <span class="info-label">邮箱：</span>
              <span class="info-value">{{ userInfo.email || '未设置' }}</span>
              <el-switch
                v-if="isCurrentUser"
                v-model="privacySettings.showEmail"
                active-text="公开"
                inactive-text="隐藏"
                @change="updatePrivacy"
                class="privacy-switch"
              />
            </div>
          </div>
          
          <div class="social-actions" v-if="!isCurrentUser">
            <el-button 
              type="primary" 
              :plain="isFollowing" 
              size="small"
              @click="toggleFollow"
            >
              {{ isFollowing ? '已关注' : '关注' }}
            </el-button>
            <el-button type="primary" plain size="small" @click="openChat">发送消息</el-button>
          </div>
        </div>
      </div>

      <div class="user-posts">
        <h3>{{ isCurrentUser ? '我的帖子' : `${userInfo.username}的帖子` }}</h3>
        <div v-if="userPosts.length === 0" class="no-posts">
          暂无帖子
        </div>
        <div 
          class="post-item" 
          v-for="post in userPosts" 
          :key="post.id" 
          @click="goToPostDetail(post.id)"
        >
          <div class="post-header">
            <h4 class="post-title">{{ post.title }}</h4>
            <span class="post-time">{{ formatDate(post.createTime) }}</span>
          </div>
          <p class="post-summary">{{ post.summary }}</p>
          <div class="post-stats">
            <span><i class="icon-view"></i> 热度 {{ post.viewCount || 0 }}</span>
            <span><i class="icon-comment"></i> 评论 {{ post.commentCount || 0 }}</span>
            <span><i class="icon-like"></i> 赞 {{ post.likeCount || 0 }}</span>
            <span v-if="isCurrentUser" class="delete-btn" @click.stop="deletePost(post.id)">删除</span>
          </div>
        </div>
      </div>
      
      <!-- 加载更多 -->
      <div v-if="loading" class="loading-more">加载中...</div>
      <div v-if="!loading && !finished" class="load-more" @click="loadMorePosts">加载更多</div>
      <div v-if="finished" class="no-more">没有更多了</div>
    </div>

    <div class="right-container">
      <div class="user-stats-card">
        <h3>{{ userInfo.username }} 的统计数据</h3>
        <div class="stats">
          <div class="stat-item">
            <div class="stat-value">{{ userStats.postCount || 0 }}</div>
            <div class="stat-label">发帖数</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ userStats.followers || 0 }}</div>
            <div class="stat-label">粉丝</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ userStats.following || 0 }}</div>
            <div class="stat-label">关注</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ userStats.likes || 0 }}</div>
            <div class="stat-label">获赞</div>
          </div>
        </div>
      </div>
      
      <!-- 可能感兴趣的用户或帖子推荐 -->
      <div class="recommendations" v-if="recommendations.length > 0">
        <h3>推荐关注</h3>
        <div class="recommendation-list">
          <div 
            v-for="user in recommendations" 
            :key="user.id" 
            class="recommendation-item"
            @click="viewUser(user.id)"
          >
            <img :src="user.avatar" alt="用户头像" class="recommendation-avatar" />
            <div class="recommendation-info">
              <div class="recommendation-name">{{ user.username }}</div>
              <div class="recommendation-followers">{{ user.followers }}位粉丝</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="js" name="UserPage">
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useUserStore } from '@/stores/user.js';
import request from '@/utils/request';
import { ElMessage } from 'element-plus';


const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

// 用户基本信息
const userInfo = ref({});
const userId = computed(() => route.params.userId || userStore.userInfo.userid);
const isCurrentUser = computed(() => String(userId.value) === String(userStore.userInfo.userid));


// 用户帖子列表
const userPosts = ref([]);
const loading = ref(false);
const finished = ref(false);
const error = ref(null);
const pageParams = reactive({
  lastVal: Date.now(),
  offset: 0,
  size: 10
});

// 用户统计数据
const userStats = ref({
  postCount: 0,
  followers: 0,
  following: 0,
  likes: 0
});

// 是否已关注
const isFollowing = ref(false);

// 隐私设置
const privacySettings = ref({
  showPhone: true,
  showEmail: true,
  showCollege: true,
  showGender: true
});

// 推荐用户
const recommendations = ref([]);

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

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

// 加载用户信息
const loadUserInfo = async () => {
  try {
    // 如果是当前用户，先从localStorage恢复基本信息
    if (isCurrentUser.value) {
      const storedUsername = localStorage.getItem('username');
      const storedAvatar = localStorage.getItem('avatar');
      
      if (storedUsername) {
        userInfo.value = {
          username: storedUsername,
          avatar: storedAvatar || '',
          role: localStorage.getItem('role') || 1,
          userId: localStorage.getItem('userId')
        };
        console.log('从localStorage恢复用户基本信息:', storedUsername);
      }
    }
    
    // 使用正确的API路径获取用户信息
    const response = await request.get('/user/info/getuserinfo', { 
      params: { userId: userId.value },
      // 设置超时，避免长时间等待
      timeout: 5000
    });
    
    console.log('获取用户信息响应:', response);
    if (response && response.code === 200) {
      userInfo.value = response.data;
      console.log('加载到的用户信息:', userInfo.value);
      
      // 加载隐私设置
      if (isCurrentUser.value) {
        loadPrivacySettings();
      }
    }
  } catch (error) {
    console.error('加载用户信息失败:', error);
    
    // 如果是网络错误，但已经从localStorage恢复了基本信息，则继续使用
    if ((!error.response || error.code === 'ECONNABORTED') && userInfo.value.username) {
      console.log('网络错误，但已恢复基本用户信息，继续使用');
      // 不做处理，继续使用已恢复的信息
    } else if (isCurrentUser.value) {
      // 如果是当前用户但未能恢复信息，尝试从userStore获取
      userInfo.value = {
        username: userStore.userInfo.username || '用户',
        avatar: userStore.userInfo.avatar || '',
        userId: userStore.userInfo.userid
      };
    } else {
      // 如果是查看其他用户但加载失败
      ElMessage.warning('加载用户信息失败，请稍后再试');
    }
  }
};

// 加载用户帖子
const loadUserPosts = async () => {
  if (loading.value || finished.value) return;
  loading.value = true;
  try {
    const response = await request.get('/post/user', {
      params: {
        userId: userId.value,
        ...pageParams
      }
    });
    console.log('加载用户帖子响应:', response.data.records);
    if (response && response.code === 200) {
      const newPosts = response.data.records || [];
      userPosts.value = [...userPosts.value, ...newPosts];
      
      if (newPosts.length < pageParams.size) {
        finished.value = true;
      } else {
        pageParams.offset += newPosts.length;
        pageParams.lastVal = newPosts[newPosts.length - 1].createTime;
      }
    }
  } catch (err) {
    error.value = '加载帖子失败，请重试';
    console.error(err);
  } finally {
    loading.value = false;
  }
};


//删除帖子
const deletePost = async (postId) => {
  if (!postId) return;
  if (!confirm('确定要删除这条帖子吗？')) return;
  try {
    const res = await request.delete('/post', { params: { id: postId } });
    if (res && res.code === 200) {
      // 删除本地列表中的帖子
      userPosts.value = userPosts.value.filter(post => post.id !== postId);
      ElMessage.success('删除成功');
    } else {
      ElMessage.error(res.message || '删除失败');
    }
  } catch (e) {
    ElMessage.error(e.response?.message || '删除失败');
  }
};


// 加载更多帖子
const loadMorePosts = () => {
  loadUserPosts();
};

// 加载用户统计数据
const loadUserStats = async () => {
  try {
    const response = await request.get('/user/stats', { params: { id: userId.value } });
    if (response && response.code === 200) {
      userStats.value = response.data;
    }
  } catch (error) {
    console.error('加载用户统计数据失败:', error);
  }
};

// 检查是否已关注该用户
const checkFollowStatus = async () => {
  if (!isCurrentUser.value && userStore.isLoggedIn) {
    try {
      const response = await request.get('/follow/check', { params: { followUserId: userId.value } });
      if (response && response.code === 200) {
        isFollowing.value = response.data;
      }
    } catch (error) {
      console.error('检查关注状态失败:', error);
    }
  }
};

// 关注/取消关注
const toggleFollow = async () => {
  if (!userStore.isLoggedIn) {
    router.push('/');
    return;
  }
  
  try {
    const url = isFollowing.value 
      ? '/follow/cancel'
      : '/follow/add';
      
    const response = await request.post(url, { followUserId: userId.value });
    
    if (response && response.code === 200) {
      isFollowing.value = !isFollowing.value;
      // 更新统计数据
      loadUserStats();
    }
  } catch (error) {
    console.error('操作关注失败:', error);
  }
};

// 打开聊天窗口
const openChat = () => {
  // 实现打开聊天功能
  console.log('打开与用户', userId.value, '的聊天');
};

// 加载隐私设置
const loadPrivacySettings = async () => {
  try {
    const response = await request.get('/user/privacy');
    if (response && response.code === 200) {
      privacySettings.value = response.data;
    }
  } catch (error) {
    console.error('加载隐私设置失败:', error);
  }
};

// 更新隐私设置
const updatePrivacy = async () => {
  try {
    await request.post('/user/privacy', privacySettings.value);
  } catch (error) {
    console.error('更新隐私设置失败:', error);
  }
};

// 加载推荐用户
const loadRecommendations = async () => {
  if (!userStore.isLoggedIn) return;
  
  try {
    const response = await request.get('/user/recommend', { params: { limit: 5 } });
    
    if (response && response.code === 200) {
      recommendations.value = response.data || [];
    }
  } catch (error) {
    console.error('加载推荐失败:', error);
  }
};

// 查看用户
const viewUser = (id) => {
  router.push({ name: 'UserPage', params: { userId: id } });
};

// 跳转到帖子详情
const goToPostDetail = (postId) => {
  console.log('跳转到帖子详情:', postId);
  router.push({ 
    name: 'PostDetail', 
    params: { id: postId }
  });
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  
  const date = new Date(dateString);
  const now = new Date();
  const diff = now - date;
  
  // 如果小于1天
  if (diff < 24 * 60 * 60 * 1000) {
    const hours = Math.floor(diff / (60 * 60 * 1000));
    if (hours < 1) {
      const minutes = Math.floor(diff / (60 * 1000));
      return minutes <= 0 ? '刚刚' : `${minutes}分钟前`;
    }
    return `${hours}小时前`;
  }
  
  // 如果小于7天
  if (diff < 7 * 24 * 60 * 60 * 1000) {
    const days = Math.floor(diff / (24 * 60 * 60 * 1000));
    return `${days}天前`;
  }
  
  // 否则显示完整日期
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

onMounted(async () => {
  await loadUserInfo();
  loadUserPosts();
  loadUserStats();
  checkFollowStatus();
  loadRecommendations();
});

onUnmounted(() => {
  // 如果需要，可以在这里重置列表
  // postListStore.resetList();
});
</script>

<style scoped>
.user-page-container {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding: 20px;
  background-color: #f5f5f5;
  max-width: 1200px;
  margin: 80px auto 0; /* 顶部边距，避免被导航栏遮挡 */
  box-sizing: border-box;
}

.left-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  flex: 3;
}

.right-container {
  flex: 1;
}

.user-info-card {
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 24px;
  display: flex;
  margin-bottom: 20px;
}

.user-avatar {
  margin-right: 24px;
}

.user-avatar img {
  width: 120px;
  height: 120px;
  border-radius: 60px;
  object-fit: cover;
  border: 4px solid #f0f5ff;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.user-details {
  flex: 1;
}

.username {
  font-size: 24px;
  margin: 0 0 5px 0;
  color: #333;
  font-weight: 600;
}

.user-info-list {
  margin-top: 15px;
}

.user-info-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  padding: 8px 10px;
  background-color: #f8f9fa;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.user-info-item:hover {
  background-color: #eef5fe;
}

.info-icon {
  margin-right: 10px;
  color: #409eff;
  width: 20px;
  text-align: center;
}

.info-label {
  width: 60px;
  color: #606266;
  font-weight: 500;
}

.info-value {
  flex: 1;
  color: #303133;
}

.privacy-switch {
  margin-left: 10px;
}

.social-actions {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

/* 用户帖子区域 */
.user-posts {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.user-posts h3 {
  margin-top: 0;
  margin-bottom: 16px;
  color: #333;
  font-size: 18px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.no-posts {
  color: #999;
  text-align: center;
  padding: 20px 0;
}

.post-item {
  padding: 15px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  transition: background-color 0.2s;
}

.post-item:last-child {
  border-bottom: none;
}

.post-item:hover {
  background-color: #f9f9f9;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.post-title {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.post-time {
  font-size: 12px;
  color: #999;
}

.post-summary {
  color: #666;
  font-size: 14px;
  margin: 8px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.post-stats {
  display: flex;
  gap: 15px;
  font-size: 12px;
  color: #999;
}

/* 加载更多 */
.loading-more, .load-more, .no-more {
  text-align: center;
  padding: 15px 0;
  color: #999;
  font-size: 14px;
}

.load-more {
  cursor: pointer;
  color: #54ac52;
}

.load-more:hover {
  text-decoration: underline;
}

/* 用户统计卡片 */
.user-stats-card {
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.user-stats-card h3 {
  margin-top: 0;
  margin-bottom: 16px;
  color: #333;
  font-size: 18px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.stats {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.stat-item {
  text-align: center;
  padding: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #54ac52;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-top: 5px;
}

/* 推荐用户 */
.recommendations {
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.recommendations h3 {
  margin-top: 0;
  margin-bottom: 16px;
  color: #333;
  font-size: 18px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.recommendation-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.recommendation-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.recommendation-item:hover {
  background-color: #f5f5f5;
}

.recommendation-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.recommendation-info {
  flex: 1;
}

.recommendation-name {
  font-size: 14px;
  font-weight: bold;
  color: #333;
}

.recommendation-followers {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.delete-btn {
  right: 16px;
  bottom: 12px;
  color: #fff;
  background: #f56c6c;
  border: none;
  border-radius: 4px;
  padding: 4px 12px;
  cursor: pointer;
  font-size: 12px;
}
</style>