<template>
  <view class="profile-page">
    <!-- 用户信息区域 -->
    <view class="user-section">
      <view class="user-info">
        <view class="avatar">
          <view class="avatar-circle"></view>
        </view>
        <view class="user-detail">
          <view class="user-name">{{ userInfo.name || '用户' }}</view>
          <view class="user-id">ID: {{ userInfo.id }}</view>
        </view>
      </view>
    </view>

    <!-- 我的报名卡片 -->
    <view class="my-registration-card" @click="goToMyRegistration">
      <image class="card-icon-img" src="/static/images/我的报名@3x.png" mode="aspectFit"></image>
      <view class="card-text">我的报名</view>
    </view>

    <!-- 菜单列表 -->
    <view class="menu-list">
      <view class="menu-item" @click="goToCommonInfo">
        <text class="menu-text">常用信息</text>
        <text class="arrow">›</text>
      </view>
      <view class="menu-item" @click="handleChangePassword">
        <text class="menu-text">修改密码</text>
        <text class="arrow">›</text>
      </view>
      <view class="menu-item" @click="handleContactUs">
        <text class="menu-text">联系我们</text>
        <text class="arrow">›</text>
      </view>
      <view class="menu-item" @click="handleLogout">
        <text class="menu-text">退出登录</text>
        <text class="arrow">›</text>
      </view>
    </view>

    <!-- 版本号 -->
    <view class="version">版本号: V 2.0</view>

    <!-- 占位，避免tabbar遮挡 -->
    <view style="height: 100rpx;"></view>
  </view>
</template>

<script>
import userAPI from '@/api/user.js'
import { getUserInfo as getStoredUserInfo, isLogin, clearAuth } from '@/utils/auth.js'

export default {
  data() {
    return {
      userInfo: {
        name: '',
        id: '',
        phone: '',
        username: ''
      }
    };
  },
  onLoad() {
    this.checkLoginAndLoadInfo()
  },
  onShow() {
    // 每次显示时刷新用户信息
    this.checkLoginAndLoadInfo()
  },
  methods: {
    /**
     * 检查登录状态并加载用户信息
     */
    checkLoginAndLoadInfo() {
      if (!isLogin()) {
        // 未登录，跳转到登录页
        uni.reLaunch({
          url: '/pages/login/login'
        })
        return
      }

      // 先从本地存储加载用户信息
      const storedInfo = getStoredUserInfo()
      if (storedInfo) {
        this.userInfo = {
          name: storedInfo.userName || storedInfo.account || '用户',
          id: storedInfo.userId || '',
          phone: storedInfo.phone || '',
          username: storedInfo.account || ''
        }
      }

      // 然后从服务器刷新用户信息
      this.loadUserInfo()
    },

    /**
     * 加载用户信息
     */
    async loadUserInfo() {
      try {
        const res = await userAPI.getUserInfo()

        this.userInfo = {
          name: res.name || res.username || res.realName || '用户',
          id: res.id || res.userId || '',
          phone: res.phone || res.mobile || '',
          username: res.username || res.account || ''
        }
      } catch (err) {
        console.error('加载用户信息失败:', err)
        // 如果是401错误，说明token过期，跳转到登录页
        if (err.statusCode === 401) {
          clearAuth()
          uni.reLaunch({
            url: '/pages/login/login'
          })
        }
      }
    },

    goToMyRegistration() {
      uni.navigateTo({
        url: '/pages/my-registration/my-registration'
      });
    },
    goToCommonInfo() {
      uni.navigateTo({
        url: '/pages/common-info/common-info'
      });
    },
    handleChangePassword() {
      uni.navigateTo({
        url: '/pages/change-password/change-password'
      });
    },
    handleContactUs() {
      uni.showToast({
        title: '联系我们',
        icon: 'none'
      });
    },
    async handleLogout() {
      const confirmRes = await new Promise((resolve) => {
        uni.showModal({
          title: '提示',
          content: '确定要退出登录吗？',
          success: (res) => resolve(res)
        })
      })

      if (confirmRes.confirm) {
        try {
          // 调用退出登录接口
          await userAPI.logout()
        } catch (err) {
          console.error('退出登录接口调用失败:', err)
          // 即使接口失败也继续清除本地数据
        }

        // 清除本地认证信息
        clearAuth()

        uni.showToast({
          title: '退出成功',
          icon: 'success'
        })

        // 延迟跳转到登录页
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/login/login'
          })
        }, 1500)
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.profile-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.user-section {
  background-color: #C93639;
  padding: 50rpx 30rpx 80rpx;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 30rpx;
}

.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-circle {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background-color: #fff;
}

.user-detail {
  flex: 1;
}

.user-name {
  font-size: 36rpx;
  font-weight: bold;
  color: #fff;
  margin-bottom: 10rpx;
}

.user-id {
  font-size: 26rpx;
  color: rgba(255, 255, 255, 0.9);
}

.my-registration-card {
  background: linear-gradient(135deg, #FFE8E8 0%, #FFD4D4 100%);
  margin: -50rpx 30rpx 30rpx;
  border-radius: 24rpx;
  padding: 40rpx;
  display: flex;
  align-items: center;
  gap: 20rpx;
  box-shadow: 0 8rpx 20rpx rgba(201, 54, 57, 0.15);
}

.card-icon {
  width: 80rpx;
  height: 80rpx;
  background-color: #C93639;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40rpx;
}

.card-icon-img {
  width: 80rpx;
  height: 80rpx;
}

.card-text {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.menu-list {
  background-color: #fff;
  margin: 0 30rpx;
  border-radius: 16rpx;
  overflow: hidden;
}

.menu-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 35rpx 30rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

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

.menu-text {
  font-size: 30rpx;
  color: #333333;
}

.arrow {
  font-size: 40rpx;
  color: #cccccc;
}

.version {
  text-align: center;
  font-size: 24rpx;
  color: #999999;
  margin-top: 50rpx;
}
</style>
