<template>
  <view class="mine-page">
    <!-- 用户信息区域 -->
    <view class="user-section">
      <view class="user-info">
        <image class="avatar" :src="userInfo.avatar" mode="aspectFill"></image>
        <view class="user-details">
          <view class="nickname-row">
            <text class="nickname">{{ userInfo.nickname }}</text>
            <!-- VIP标志 -->
            <view class="vip-badge" v-if="userInfo.isVip">
              <text class="vip-badge-text">👑</text>
            </view>
            <view class="verify-badge" @click="goVerify" v-if="!userInfo.isVerified">
              <text class="verify-text">未实名，立即认证</text>
            </view>
          </view>

          <!-- 基本信息展示 -->
          <view class="user-basic-info">
            <view class="info-item" v-if="userInfo.gender">
              <text class="info-icon">{{ userInfo.gender === 1 ? '👨' : '👩' }}</text>
              <text class="info-text">{{ userInfo.genderText }}</text>
            </view>
            <view class="info-item" v-if="userInfo.age">
              <text class="info-icon">🎂</text>
              <text class="info-text">{{ userInfo.age }}岁</text>
            </view>
            <view class="info-item" v-if="userInfo.height">
              <text class="info-icon">📏</text>
              <text class="info-text">{{ userInfo.height }}cm</text>
            </view>
            <view class="info-item" v-if="userInfo.educationText">
              <text class="info-icon">🎓</text>
              <text class="info-text">{{ userInfo.educationText }}</text>
            </view>
          </view>

          <view class="progress-row">
            <view class="progress-bar">
              <view class="progress-fill" :style="{ width: userInfo.profileProgress + '%' }"></view>
            </view>
            <text class="progress-text" @click="goCompleteProfile">完善资料 ></text>
          </view>
        </view>
      </view>
    </view>

    <!-- VIP会员卡片 -->
    <view class="vip-card" @click="goVip" v-if="!userInfo.isVip">
      <view class="vip-content">
        <view class="vip-icon">👑</view>
        <view class="vip-info">
          <text class="vip-title">VIP会员未开通</text>
          <text class="vip-subtitle">开通会员可享受尊贵服务哦</text>
        </view>
      </view>
      <view class="vip-button">立即开通</view>
    </view>


    <!-- 快捷入口 -->
    <view class="quick-actions">
      <view class="action-item" @click="goToPage('basicInfo')">
        <view class="action-icon calendar-icon">🆔</view>
        <text class="action-label">基本资料</text>
      </view>
      <view class="action-item" @click="goToPage('partnerRequirement')">
        <view class="action-icon heart-icon">💜</view>
        <text class="action-label">对象要求</text>
      </view>
      <view class="action-item" @click="goToPage('verifyRealName')">
        <view class="action-icon phone-icon">🪪</view>
        <text class="action-label">实名认证</text>
      </view>
      <view class="action-item" @click="goToPage('verifyEducation')">
        <view class="action-icon phone-icon">🎓</view>
        <text class="action-label">学历认证</text>
      </view>
    </view>

    <!-- 签到弹窗 -->
    <uni-popup ref="checkinPopup" type="center" :mask-click="true">
      <view class="checkin-popup">
        <view class="popup-header">
          <text class="popup-title">每日签到</text>
          <view class="close-btn" @click="closeCheckinPopup">
            <text class="close-icon">✕</text>
          </view>
        </view>

        <view class="checkin-info">
          <view class="info-item">
            <text class="info-label">已连续签到</text>
            <text class="info-value">{{ checkinData.continuousDays }} 天</text>
          </view>
          <view class="info-item">
            <text class="info-label">累计签到</text>
            <text class="info-value">{{ checkinData.totalDays }} 天</text>
          </view>
        </view>

        <scroll-view scroll-y class="checkin-content">
          <view class="checkin-calendar">
            <view class="calendar-header">
              <text class="month-text">{{ currentMonth }}</text>
            </view>
            <view class="week-header">
              <text class="week-day" v-for="day in weekDays" :key="day">{{ day }}</text>
            </view>
            <view class="calendar-body">
              <view
                  class="calendar-day"
                  v-for="(day, index) in calendarDays"
                  :key="index"
                  :class="{
									'empty': !day.date,
									'checked': day.checked,
									'today': day.isToday
								}"
              >
                <text class="day-num" v-if="day.date">{{ day.date }}</text>
                <view class="check-mark" v-if="day.checked">✓</view>
              </view>
            </view>
          </view>

          <view class="checkin-rewards">
            <text class="rewards-title">签到奖励</text>
            <view class="rewards-list">
              <view
                  class="reward-item"
                  v-for="(reward, index) in checkinRewards"
                  :key="index"
                  :class="{ 'received': reward.received, 'current': reward.isCurrent }"
              >
                <view class="reward-icon">{{ reward.icon }}</view>
                <text class="reward-day">第{{ reward.day }}天</text>
                <text class="reward-text">{{ reward.reward }}</text>
                <view class="received-mark" v-if="reward.received">✓</view>
              </view>
            </view>
          </view>
        </scroll-view>

        <view class="checkin-button-wrapper">
          <button
              class="checkin-btn"
              :class="{ 'disabled': checkinData.todayChecked }"
              @click="handleCheckin"
              :disabled="checkinData.todayChecked"
          >
            {{ checkinData.todayChecked ? '今日已签到' : '立即签到' }}
          </button>
        </view>
      </view>
    </uni-popup>

    <!-- 功能菜单列表 -->
    <view class="menu-list">
		
		<view class="menu-item" @click="showCheckinPopup">
		  <view class="menu-left">
		    <text class="menu-icon">📅</text>
		    <text class="menu-text">签到</text>
		  </view>
		  <text class="menu-arrow">›</text>
		</view>
		
		<view class="menu-item" @click="goToPage('myDynamics')">
		  <view class="menu-left">
		    <text class="menu-icon">📝</text>
		    <text class="menu-text">我的动态</text>
		  </view>
		  <text class="menu-arrow">›</text>
		</view>
		
		<view class="menu-item" @click="goToPage('myActivity')">
		  <view class="menu-left">
		    <text class="menu-icon">📷</text>
		    <text class="menu-text">我的活动</text>
		  </view>
		  <text class="menu-arrow">›</text>
		</view>
		
		<view class="menu-item" @click="goToPage('partTimeMatchmaker')">
		  <view class="menu-left">
		    <text class="menu-icon">💎</text>
		    <text class="menu-text">兼职红娘</text>
		  </view>
		  <text class="menu-arrow">›</text>
		</view>
		
      <view class="menu-item" @click="goToPage('feedback')">
        <view class="menu-left">
          <text class="menu-icon">💬</text>
          <text class="menu-text">用户反馈</text>
        </view>
        <text class="menu-arrow">›</text>
      </view>

      <view class="menu-item" @click="goToPage('blacklist')">
        <view class="menu-left">
          <text class="menu-icon">📋</text>
          <text class="menu-text">黑名单</text>
        </view>
        <text class="menu-arrow">›</text>
      </view>

      <view class="menu-item" @click="goToPage('settings')">
        <view class="menu-left">
          <text class="menu-icon">⚙️</text>
          <text class="menu-text">设置</text>
        </view>
        <text class="menu-arrow">›</text>
      </view>
    </view>

    <!-- 底部导航栏 -->
    <view class="tabbar">
      <view class="tabbar-item" @click="switchTab('index')">
        <text class="tabbar-icon">🏠</text>
        <text class="tabbar-text">首页</text>
      </view>
      <view class="tabbar-item" @click="switchTab('plaza')">
        <text class="tabbar-icon">💕</text>
        <text class="tabbar-text">广场</text>
      </view>
      <view class="tabbar-item" @click="switchTab('recommend')">
        <text class="tabbar-icon">👍</text>
        <text class="tabbar-text">推荐</text>
      </view>
      <view class="tabbar-item" @click="switchTab('message')">
        <text class="tabbar-icon">💬</text>
        <text class="tabbar-text">消息</text>
        <view v-if="unreadCount > 0" class="tabbar-badge">{{ unreadCount }}</view>
      </view>
      <view class="tabbar-item active" @click="switchTab('mine')">
        <text class="tabbar-icon">👤</text>
        <text class="tabbar-text">我的</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 网关地址
      gatewayURL: 'http://localhost:8083',

      // 用户ID（如果没有登录，默认为1）
      currentUserId: null,

      // 用户信息（从后端获取）
      userInfo: {
        userId: null,
        nickname: '准备加载...',
        avatar: 'https://via.placeholder.com/100',
        phone: '',
        email: '',
        gender: null,
        genderText: '未知',
        birthDate: null,
        age: null,
        isVerified: false,
        profileProgress: 0,
        isVip: false
      },

      stats: {
        myConnection: 0,
        myFavorites: 0,
        whoViewedMe: 0,
        iViewed: 0
      },
      matchmaker: {
        code: 'xxxxx',
        phone: '99*******99'
      },
      // 签到数据
      checkinData: {
        continuousDays: 0,
        totalDays: 0,
        todayChecked: false,
        checkedDates: []
      },
      weekDays: ['日', '一', '二', '三', '四', '五', '六'],
      currentMonth: '',
      calendarDays: [],
      checkinRewards: []
    }
  },
  computed: {
    unreadCount() {
      return this.$store.getters.getTotalUnread || 0;
    }
  },
  onLoad() {
    console.log('=== 我的页面加载开始 ===')

    // 立即检查登录状态
    const token = uni.getStorageSync('token')
    const userInfo = uni.getStorageSync('userInfo')

    if (!token || !userInfo) {
      // 未登录，立即强制跳转到登录页
      console.log('❌ 未登录，强制跳转到登录页')
      uni.showModal({
        title: '需要登录',
        content: '请先登录后查看个人信息',
        showCancel: false,  // 不允许取消
        confirmText: '去登录',
        success: () => {
          uni.navigateTo({
            url: '/pages/page3/page3'
          })
        }
      })
      return
    }

    // 已登录，同步登录状态
    this.syncLoginStatus()

    // 监听VIP购买成功事件
    uni.$on('vipPurchased', this.handleVipPurchased)
  },

  onUnload() {
    // 页面卸载时移除事件监听
    uni.$off('vipPurchased', this.handleVipPurchased)
  },

  onShow() {
    console.log('=== 我的页面显示 ===')

    // 检查登录状态
    const token = uni.getStorageSync('token')
    const userInfo = uni.getStorageSync('userInfo')

    if (!token || !userInfo) {
      // 未登录，直接跳转（不显示弹窗，因为onLoad已经显示过了）
      console.log('❌ 未登录，跳转到登录页')
      uni.navigateTo({
        url: '/pages/page3/page3'
      })
      return
    }

    // 已登录，同步登录状态
    this.syncLoginStatus()
  },
  methods: {
    // 同步登录状态并更新页面数据
    syncLoginStatus() {
      console.log('=== 同步登录状态 ===')

      // 获取最新的登录信息
      const token = uni.getStorageSync('token')
      const userInfo = uni.getStorageSync('userInfo')
      const userId = uni.getStorageSync('userId')

      console.log('最新登录状态:')
      console.log('- token存在:', !!token)
      console.log('- userInfo存在:', !!userInfo)
      console.log('- userId:', userId)

      if (token && userInfo && userId) {
        // 已登录状态 - 立即使用存储的用户信息更新页面
        console.log('✅ 检测到登录状态，立即更新页面数据')

        this.currentUserId = parseInt(userId)

        // 直接使用存储的用户信息更新页面
        this.userInfo = {
          userId: userInfo.userId || userId,
          nickname: userInfo.nickname || '用户',
          avatar: userInfo.avatarUrl || userInfo.avatar || 'https://via.placeholder.com/100',
          phone: this.maskPhone(userInfo.phone) || '',
          email: userInfo.email || '',
          gender: userInfo.gender,
          genderText: this.getGenderText(userInfo.gender),
          birthDate: userInfo.birthDate,
          age: this.calculateAge(userInfo.birthDate),
          isVerified: false,
          profileProgress: userInfo.profileProgress || 0,
          isVip: false
        }

        console.log('✅ 页面用户信息已更新:', this.userInfo.nickname)

        // 强制页面刷新
        this.$forceUpdate()

        // 设置统计数据
        this.stats = {
          myConnection: Math.floor(Math.random() * 8) + 2,
          myFavorites: Math.floor(Math.random() * 15) + 5,
          whoViewedMe: Math.floor(Math.random() * 12) + 3,
          iViewed: Math.floor(Math.random() * 20) + 8
        }

        // 立即加载最新用户信息（不延迟）
        this.loadUserInfo()

      } else {
        // 未登录状态 - 设置空白用户信息
        console.log('❌ 未检测到登录状态')
        this.currentUserId = null

        // 设置未登录状态的用户信息
        this.userInfo = {
          userId: null,
          nickname: '未登录',
          avatar: 'https://via.placeholder.com/100?text=未登录',
          phone: '',
          email: '',
          gender: 0,
          genderText: '未知',
          birthDate: null,
          age: null,
          isVerified: false,
          profileProgress: 0,
          isVip: false
        }

        // 清空统计数据
        this.stats = {
          myConnection: 0,
          myFavorites: 0,
          whoViewedMe: 0,
          iViewed: 0
        }

        // 强制页面更新
        this.$forceUpdate()

        // 提示需要登录
        setTimeout(() => {
          uni.showModal({
            title: '需要登录',
            content: '请先登录后查看完整功能',
            showCancel: false,
            confirmText: '去登录',
            success: () => {
              uni.navigateTo({
                url: '/pages/page3/page3'
              })
            }
          })
        }, 500)
      }
    },

    // 简单的手机号脱敏
    maskPhone(phone) {
      if (!phone || phone.length < 11) return phone
      return phone.substring(0, 3) + '****' + phone.substring(7)
    },

    // 获取性别文字
    getGenderText(gender) {
      switch (gender) {
        case 1:
          return '男'
        case 2:
          return '女'
        default:
          return '未知'
      }
    },

    // 计算年龄
    calculateAge(birthDate) {
      if (!birthDate) return null
      const birth = new Date(birthDate)
      const today = new Date()
      let age = today.getFullYear() - birth.getFullYear()
      const monthDiff = today.getMonth() - birth.getMonth()
      if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
        age--
      }
      return age
    },
    // 从后端加载用户信息（通过网关）
    loadUserInfo() {
      // 检查是否真正登录（必须有token和userInfo）
      const token = uni.getStorageSync('token')
      const userInfo = uni.getStorageSync('userInfo')

      if (!token || !userInfo) {
        console.warn('未登录，不加载用户信息')
        return
      }

      // 检查用户ID是否有效
      if (!this.currentUserId || this.currentUserId <= 0) {
        console.warn('无有效用户ID，无法加载用户信息')
        this.setDefaultUserInfo()
        return
      }

      console.log('加载用户信息，用户ID:', this.currentUserId)

      // 获取用户基本信息
      uni.request({
        url: this.gatewayURL + '/api/user/info?userId=' + this.currentUserId,
        method: 'GET',
        success: (res) => {
          console.log('用户信息API响应:', res.data)

          if (res.data && res.data.code === 200) {
            const data = res.data.data
            console.log('✅ API返回用户数据:', data)

            // 更新用户信息
            this.userInfo = {
              userId: data.userId,
              nickname: data.nickname || '用户',
              avatar: data.avatar || 'https://via.placeholder.com/100',
              phone: data.phone,
              email: data.email,
              gender: data.gender,
              genderText: data.genderText,
              birthDate: data.birthDate,
              age: data.age,
              isVerified: data.isVerified || false,
              profileProgress: data.profileProgress || 0,
              isVip: data.isVip || false,
              // 扩展信息
              height: data.height,
              weight: data.weight,
              star: data.star,
              animal: data.animal,
              educationLevel: data.educationLevel,
              educationText: data.educationText,
              schoolName: data.schoolName,
              company: data.company,
              jobTitle: data.jobTitle,
              salaryRange: data.salaryRange,
              salaryText: data.salaryText,
              maritalStatus: data.maritalStatus,
              maritalText: data.maritalText,
              house: data.house,
              houseText: data.houseText,
              car: data.car,
              carText: data.carText,
              hobby: data.hobby,
              authenticityScore: data.authenticityScore
            }

            console.log('✅ 用户信息更新完成:', this.userInfo.nickname)

            // 强制页面更新
            this.$forceUpdate()

            // 加载签到信息
            this.loadCheckinInfo()
          } else {
            console.error('获取用户信息失败:', res.data)
            const errorMsg = res.data?.message || '获取用户信息失败'

            // 如果是用户不存在的错误，给出特殊提示
            if (errorMsg.includes('用户不存在') || errorMsg.includes('用户ID无效')) {
              uni.showModal({
                title: '用户不存在',
                content: `当前用户ID（${this.currentUserId}）在数据库中不存在，登录信息有误，请重新登录`,
                showCancel: false,
                confirmText: '重新登录',
                success: () => {
                  // 清除登录信息并跳转登录页
                  uni.clearStorageSync()
                  uni.navigateTo({
                    url: '/pages/page3/page3?redirect=' + encodeURIComponent('/pages/mine/index')
                  })
                }
              })
            } else {
              uni.showToast({
                title: errorMsg,
                icon: 'none'
              })
              // 设置默认用户信息
              this.setDefaultUserInfo()
            }
          }
        },
        fail: (err) => {
          console.error('获取用户信息失败:', err)

          // API失败时，提示用户网络错误
          uni.showModal({
            title: '网络错误',
            content: '无法连接到服务器，请检查网络连接或稍后重试',
            showCancel: true,
            cancelText: '返回',
            confirmText: '重试',
            success: (modalRes) => {
              if (modalRes.confirm) {
                // 重试加载
                this.loadUserInfo()
              }
            }
          })

          // 设置默认用户信息以避免页面空白
          this.setDefaultUserInfo()

          uni.showToast({
            title: '网络连接失败',
            icon: 'none',
            duration: 2000
          })
        }
      })
    },

    // 设置默认用户信息（未登录或加载失败时）
    setDefaultUserInfo() {
      this.userInfo = {
        userId: null,
        nickname: '未登录用户',
        avatar: 'https://via.placeholder.com/100?text=未登录',
        phone: '',
        email: '',
        gender: null,
        genderText: '未知',
        birthDate: null,
        age: null,
        isVerified: false,
        profileProgress: 0,
        isVip: false,
        height: null,
        weight: null,
        star: null,
        animal: null,
        educationLevel: null,
        schoolName: null,
        company: null,
        jobTitle: null,
        salaryRange: null,
        maritalStatus: null,
        house: null,
        car: null,
        hobby: null,
        authenticityScore: 0
      }

      // 显示登录提示（仅在没有登录时显示）
      const token = uni.getStorageSync('token')
      if (!token) {
        setTimeout(() => {
          uni.showModal({
            title: '提示',
            content: '请先登录以查看完整功能',
            showCancel: true,
            cancelText: '稍后',
            confirmText: '去登录',
            success: (res) => {
              if (res.confirm) {
                uni.navigateTo({
                  url: '/pages/page3/page3?redirect=' + encodeURIComponent('/pages/mine/index')
                })
              }
            }
          })
        }, 1000) // 延迟1秒显示，避免页面刚加载就弹窗
      }
    },

    // 加载签到信息
    loadCheckinInfo() {
      // 确保有用户ID
      if (!this.userInfo.userId) {
        console.error('用户ID不存在，无法加载签到信息')
        return
      }

      uni.request({
        url: this.gatewayURL + '/api/checkin/info',
        method: 'GET',
        data: {
          userId: this.userInfo.userId
        },
        success: (res) => {
          console.log('签到信息:', res.data)

          if (res.data.code === 200) {
            const data = res.data.data

            // 更新签到数据
            this.checkinData = {
              continuousDays: data.continuousDays,
              totalDays: data.totalDays,
              todayChecked: data.todayChecked,
              checkedDates: data.checkedDates
            }

            // 更新奖励列表
            this.checkinRewards = data.rewards

            // 生成日历
            this.generateCalendarFromBackend(data.checkedDates)
          }
        },
        fail: (err) => {
          console.error('获取签到信息失败:', err)
          uni.showToast({
            title: '加载签到信息失败',
            icon: 'none'
          })
        }
      })
    },

    // 根据后端数据生成日历（修复版本）
    generateCalendarFromBackend(checkedDates) {
      const today = new Date()
      const year = today.getFullYear()
      const month = today.getMonth() // 0-11
      
      // 格式化当前月份显示
      this.currentMonth = `${year}年${month + 1}月`
      
      // 获取本月第一天是星期几（0=周日, 1=周一, ..., 6=周六）
      const firstDay = new Date(year, month, 1).getDay()
      
      // 获取本月总天数
      const daysInMonth = new Date(year, month + 1, 0).getDate()
      
      // 今天的日期字符串（用于比较）
      const todayStr = this.formatDate(today)
      
      const days = []
      
      // 添加空白占位（月初前的空白）
      for (let i = 0; i < firstDay; i++) {
        days.push({ date: null, checked: false, isToday: false })
      }
      
      // 添加本月的每一天
      for (let i = 1; i <= daysInMonth; i++) {
        const date = new Date(year, month, i)
        const dateStr = this.formatDate(date)
        const isToday = dateStr === todayStr
        const checked = checkedDates.includes(dateStr)
        
        days.push({
          date: i,
          checked: checked,
          isToday: isToday,
          dateStr: dateStr
        })
      }
      
      this.calendarDays = days
      
      console.log('日历生成完成:', {
        month: this.currentMonth,
        firstDay: firstDay,
        daysInMonth: daysInMonth,
        totalDays: days.length,
        todayStr: todayStr
      })
    },
    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    // 显示签到弹窗
    showCheckinPopup() {
      this.$refs.checkinPopup.open()
    },
    // 关闭签到弹窗
    closeCheckinPopup() {
      this.$refs.checkinPopup.close()
    },
    // 处理签到（通过网关）
    handleCheckin() {
      if (this.checkinData.todayChecked) {
        uni.showToast({
          title: '今日已签到',
          icon: 'none'
        })
        return
      }

      // 确保有用户ID
      if (!this.userInfo.userId) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        return
      }

      // 调用后端签到接口（通过网关）
      uni.request({
        url: this.gatewayURL + '/api/checkin/sign?userId=' + this.userInfo.userId,
        method: 'POST',
        success: (res) => {
          console.log('签到结果:', res.data)

          if (res.data.code === 200) {
            // 显示签到成功提示
            uni.showToast({
              title: res.data.message,
              icon: 'success',
              duration: 2500
            })

            const data = res.data.data

            // 更新签到数据
            this.checkinData = {
              continuousDays: data.continuousDays,
              totalDays: data.totalDays,
              todayChecked: data.todayChecked,
              checkedDates: data.checkedDates
            }

            // 更新奖励列表
            this.checkinRewards = data.rewards

            // 重新生成日历
            this.generateCalendarFromBackend(data.checkedDates)

          } else {
            // 签到失败
            uni.showToast({
              title: res.data.message,
              icon: 'none',
              duration: 2000
            })
          }
        },
        fail: (err) => {
          console.error('签到失败:', err)
          uni.showToast({
            title: '签到失败，请稍后重试',
            icon: 'none'
          })
        }
      })
    },
    goVerify() {
      uni.showToast({
        title: '前往实名认证',
        icon: 'none'
      })
    },
    goCompleteProfile() {
      this.goToPage('basicInfo')
    },
    goVip() {
      uni.navigateTo({
        url: '/pages/vip/index'
      })
    },
    goToPage(page) {
      console.log('=== goToPage 被调用 ===')
      console.log('页面参数:', page)
      console.log('当前用户ID:', this.currentUserId)

      try {
        if (page === 'basicInfo') {
          console.log('✅ 跳转到基本资料页面')
          // 跳转到基本资料页面
          uni.navigateTo({
            url: '/pages/profile/index',
            success: () => {
              console.log('✅ 基本资料页面跳转成功')
            },
            fail: (err) => {
              console.error('❌ 基本资料页面跳转失败:', err)
              uni.showToast({
                title: '页面跳转失败',
                icon: 'none'
              })
            }
          })
        } else if (page === 'verifyRealName') {
          console.log('✅ 跳转到实名认证页面')
          // 跳转到实名认证页面
          uni.navigateTo({
            url: '/pages/settings/id-verification',
            success: () => {
              console.log('✅ 实名认证页面跳转成功')
            },
            fail: (err) => {
              console.error('❌ 实名认证页面跳转失败:', err)
              uni.showToast({
                title: '页面跳转失败',
                icon: 'none'
              })
            }
          })
        } else if (page === 'verifyEducation') {
          console.log('✅ 跳转到学历认证页面')
          // 跳转到实名认证页面
          uni.navigateTo({
            url: '/pages/settings/id-verification',
            success: () => {
              console.log('✅ 学历认证页面跳转成功')
            },
            fail: (err) => {
              console.error('❌ 学历认证页面跳转失败:', err)
              uni.showToast({
                title: '页面跳转失败',
                icon: 'none'
              })
            }
          })
        } else if (page === 'partTimeMatchmaker') {
          console.log('✅ 跳转到兼职红娘页面')
          // 跳转到兼职红娘页面
          uni.navigateTo({
            url: '/pages/part-time-matchmaker/index',
            success: () => {
              console.log('✅ 兼职红娘页面跳转成功')
            },
            fail: (err) => {
              console.error('❌ 兼职红娘页面跳转失败:', err)
              uni.showToast({
                title: '页面跳转失败',
                icon: 'none'
              })
            }
          })
        } else if (page === 'blacklist') {
          console.log('✅ 跳转到黑名单页面')
          // 跳转到黑名单页面
          uni.navigateTo({
            url: '/pages/blacklist/index',
            success: () => {
              console.log('✅ 黑名单页面跳转成功')
            },
            fail: (err) => {
              console.error('❌ 黑名单页面跳转失败:', err)
              uni.showToast({
                title: '页面跳转失败',
                icon: 'none'
              })
            }
          })
        } else if (page === 'partnerRequirement') {
          console.log('✅ 跳转到对象要求页面')
          // 跳转到对象要求页面
          uni.navigateTo({
            url: '/pages/partner-requirement/index',
            success: () => {
              console.log('✅ 对象要求页面跳转成功')
            },
            fail: (err) => {
              console.error('❌ 对象要求页面跳转失败:', err)
              uni.showToast({
                title: '页面跳转失败',
                icon: 'none'
              })
            }
          })
        } else if (page === 'feedback') {
          console.log('✅ 跳转到用户反馈页面')
          // 跳转到用户反馈页面
          uni.navigateTo({
            url: '/pages/feedback/index',
            success: () => {
              console.log('✅ 用户反馈页面跳转成功')
            },
            fail: (err) => {
              console.error('❌ 用户反馈页面跳转失败:', err)
              uni.showToast({
                title: '页面跳转失败',
                icon: 'none'
              })
            }
          })
        } else if (page === 'settings') {
          console.log('✅ 跳转到设置页面')
          // 跳转到设置页面
          uni.navigateTo({
            url: '/pages/settings/index',
            success: () => {
              console.log('✅ 设置页面跳转成功')
            },
            fail: (err) => {
              console.error('❌ 设置页面跳转失败:', err)
              uni.showToast({
                title: '页面跳转失败',
                icon: 'none'
              })
            }
          })
        }
            // 	else if (page === 'customize') {
            // 		console.log('✅ 跳转到私人定制页面')
            // 		// 跳转到私人定制页面
            // 		uni.navigateTo({
            // 			url: '/pages/customize/index',
            // 			success: () => {
            // 				console.log('✅ 私人定制页面跳转成功')
            // 			},
            // 			fail: (err) => {
            // 				console.error('❌ 私人定制页面跳转失败:', err)
            // 				uni.showToast({
            // 					title: '页面跳转失败',
            // 					icon: 'none'
            // 				})
            // 			}
            // 		})
        // }
        else if (page === 'part-time-matchmaker') {
          console.log('✅ 跳转到加入红娘页面')
          // 跳转到加入红娘页面
          uni.navigateTo({
            url: '/pages/part-time-matchmaker/index',
            success: () => {
              console.log('✅ 加入红娘页面跳转成功')
            },
            fail: (err) => {
              console.error('❌ 加入红娘页面跳转失败:', err)
              uni.showToast({
                title: '页面跳转失败',
                icon: 'none'
              })
            }
          })
        } else if (page === 'myActivity') {
          console.log('✅ 跳转到我的活动页面')
          // 跳转到我的活动页面
          uni.navigateTo({
            url: '/pages/mine/my-activities',
            success: () => {
              console.log('✅ 我的活动页面跳转成功')
            },
            fail: (err) => {
              console.error('❌ 我的活动页面跳转失败:', err)
              uni.showToast({
                title: '页面跳转失败',
                icon: 'none'
              })
            }
          })
        } else if (page === 'myDynamics') {
          console.log('✅ 跳转到我的动态页面')
          // 跳转到我的动态页面
          uni.navigateTo({
            url: '/pages/mine/my-dynamics',
            success: () => {
              console.log('✅ 我的动态页面跳转成功')
            },
            fail: (err) => {
              console.error('❌ 我的动态页面跳转失败:', err)
              uni.showToast({
                title: '页面跳转失败',
                icon: 'none'
              })
            }
          })
        } else {
          console.log('⚠️ 未知页面类型:', page)
          uni.showToast({
            title: '功能开发中',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('❌ goToPage 执行出错:', error)
        uni.showToast({
          title: '页面跳转异常',
          icon: 'none'
        })
      }
    },
    switchTab(tab) {
      if (tab === 'mine') return

      const tabPages = {
        index: '/pages/index/index',
        plaza: '/pages/plaza/index',
        recommend: '/pages/recommend/index',
        message: '/pages/message/index'
      }

      if (tabPages[tab]) {
        uni.redirectTo({
          url: tabPages[tab]
        })
      }
    },

    // 处理退出登录
    handleLogout() {
      console.log('点击退出登录按钮')

      uni.showModal({
        title: '退出登录',
        content: '确定要退出登录吗？',
        showCancel: true,
        cancelText: '取消',
        confirmText: '确定',
        success: (res) => {
          if (res.confirm) {
            console.log('用户确认退出登录')
            this.executeLogout()
          } else {
            console.log('用户取消退出登录')
          }
        }
      })
    },

    // 执行退出登录（最可靠的方式）
    executeLogout() {
      console.log('=== 执行退出登录 ===')

      // 立即显示加载状态
      uni.showLoading({
        title: '退出中...',
        mask: true
      })

      // 延迟执行，确保UI更新
      setTimeout(() => {
        try {
          console.log('步骤1: 断开WebSocket连接')
          // 断开在线状态WebSocket
          try {
            const timPresenceManager = require('@/utils/tim-presence-manager.js').default;
            if (timPresenceManager) {
              timPresenceManager.disconnect();
              console.log('✅ 在线状态WebSocket已断开');
            }
          } catch (error) {
            console.error('❌ 断开在线状态WebSocket失败:', error);
          }

          // 断开TIM WebSocket
          try {
            const timManager = require('@/utils/tim-manager.js').default;
            if (timManager && timManager.isLogin) {
              timManager.logout();
              console.log('✅ TIM已登出');
            }
          } catch (error) {
            console.error('❌ TIM登出失败:', error);
          }

          console.log('步骤2: 清除登录数据')

          // 方法1: 逐个清除
          uni.removeStorageSync('token')
          uni.removeStorageSync('userInfo')
          uni.removeStorageSync('userId')
          uni.removeStorageSync('rememberedAccount')

          console.log('步骤3: 验证数据清除')
          const remainToken = uni.getStorageSync('token')
          const remainUser = uni.getStorageSync('userInfo')
          console.log('清除后检查 - token:', remainToken, 'userInfo:', remainUser)

          // 如果还有残留数据，使用强制清除
          if (remainToken || remainUser) {
            console.log('检测到残留数据，执行强制清除')
            uni.clearStorageSync()
          }

          console.log('步骤4: 重置页面状态')
          this.currentUserId = null
          this.userInfo = {
            userId: null,
            nickname: '未登录用户',
            avatar: 'https://via.placeholder.com/100?text=未登录'
          }

          // 隐藏加载，显示成功
          uni.hideLoading()
          uni.showToast({
            title: '退出成功！',
            icon: 'success',
            duration: 1500
          })

          // 延迟跳转
          setTimeout(() => {
            console.log('步骤5: 跳转到登录页面')
            uni.reLaunch({
              url: '/pages/page3/page3'
            })
          }, 1500)

        } catch (error) {
          console.error('退出过程出错:', error)
          uni.hideLoading()

          // 强制退出
          uni.clearStorageSync()
          uni.showModal({
            title: '退出完成',
            content: '已清除登录信息，请重新打开应用',
            showCancel: false,
            confirmText: '知道了'
          })
        }
      }, 300) // 300毫秒延迟确保UI响应
    },

    // 设置测试用户数据（基于数据库真实数据）
    // ⚠️ 已弃用：此方法仅供调试使用，正常流程不再调用测试数据
    setTestUserData() {
      console.log('=== 设置测试用户数据 ===')
      console.warn('⚠️ 警告：正在使用测试数据，这不应该在生产环境中发生')

      // 根据当前用户ID设置对应的数据库用户信息
      const userId = this.currentUserId || 1

      let userData = {}

      switch (userId) {
        case 1:
          userData = {
            userId: 1,
            nickname: '小明',
            avatar: 'https://example.com/avatar1.jpg',
            phone: '138****8001',
            email: 'user1@example.com',
            gender: 1,
            genderText: '男',
            birthDate: '1990-05-05',
            age: 34,
            isVerified: true,
            profileProgress: 80,
            isVip: false
          }
          break
        case 2:
          userData = {
            userId: 2,
            nickname: '小红',
            avatar: 'https://example.com/avatar2.jpg',
            phone: '138****8002',
            email: 'user2@example.com',
            gender: 2,
            genderText: '女',
            birthDate: '1992-08-22',
            age: 32,
            isVerified: true,
            profileProgress: 90,
            isVip: true
          }
          break
        case 3:
          userData = {
            userId: 3,
            nickname: '用户5718',
            avatar: 'https://via.placeholder.com/100?text=用户',
            phone: '188****5718',
            email: '',
            gender: 0,
            genderText: '未知',
            birthDate: null,
            age: null,
            isVerified: false,
            profileProgress: 30,
            isVip: false
          }
          break
        default:
          userData = {
            userId: userId,
            nickname: '测试用户',
            avatar: 'https://via.placeholder.com/100?text=测试',
            phone: '',
            email: '',
            gender: 0,
            genderText: '未知',
            birthDate: null,
            age: null,
            isVerified: false,
            profileProgress: 20,
            isVip: false
          }
      }

      // 设置用户信息
      this.userInfo = userData

      console.log('✅ 测试用户数据设置完成:', this.userInfo.nickname)

      // 设置统计数据
      this.stats = {
        myConnection: Math.floor(Math.random() * 10),
        myFavorites: Math.floor(Math.random() * 20),
        whoViewedMe: Math.floor(Math.random() * 15),
        iViewed: Math.floor(Math.random() * 25)
      }

      // 显示提示
      uni.showToast({
        title: '使用测试数据: ' + this.userInfo.nickname,
        icon: 'success',
        duration: 2000
      })
    },

    // 处理VIP购买成功事件
    handleVipPurchased() {
      console.log('=== 收到VIP购买成功通知 ===')

      // 延迟刷新，确保后端数据已更新
      setTimeout(() => {
        console.log('开始刷新用户信息...')
        this.loadUserInfo()
      }, 500)
    }
  }
}
</script>

<style lang="scss" scoped>
/* 扁平化设计风格 */
.mine-page {
  min-height: 100vh;
  background: #F5F5F5;
  padding-bottom: 120rpx;
}

/* 用户信息区域 - 扁平化 */
.user-section {
  margin: 0;
  margin-top: env(safe-area-inset-top);
  padding: 30rpx;
  background: #FFE5F1;

  .user-info {
    display: flex;
    align-items: flex-start;
    margin-bottom: 40rpx;

    .avatar {
      width: 120rpx;
      height: 120rpx;
      border-radius: 12rpx;
      margin-right: 25rpx;
      background-color: #FFFFFF;
      border: 2rpx solid #E0E0E0;
    }

    .user-details {
      flex: 1;

      .nickname-row {
        display: flex;
        align-items: center;
        margin-bottom: 16rpx;
        margin-top: 10rpx;

        .nickname {
          font-size: 38rpx;
          font-weight: bold;
          color: #333333;
          margin-right: 20rpx;
        }

        /* VIP标志样式 */
        .vip-badge {
          margin-right: 12rpx;
          display: flex;
          align-items: center;

          .vip-badge-text {
            font-size: 48rpx;
            display: inline-block;
          }
        }

        .verify-badge {
          background: #B8E986;
          padding: 8rpx 20rpx;
          border-radius: 6rpx;

          .verify-text {
            font-size: 22rpx;
            color: #FFFFFF;
            font-weight: 600;
          }
        }
      }

      /* 基本信息展示 - 扁平化 */
      .user-basic-info {
        display: flex;
        flex-wrap: wrap;
        gap: 16rpx;
        margin-bottom: 20rpx;

        .info-item {
          display: flex;
          align-items: center;
          gap: 8rpx;
          padding: 8rpx 16rpx;
          background: #FFFFFF;
          border-radius: 8rpx;
          border: 2rpx solid #E0E0E0;

          .info-icon {
            font-size: 28rpx;
          }

          .info-text {
            font-size: 24rpx;
            color: #666666;
            font-weight: 500;
          }
        }
      }

      .progress-row {
        display: flex;
        align-items: center;

        .progress-bar {
          flex: 1;
          height: 16rpx;
          background-color: #FFFFFF;
          border-radius: 8rpx;
          overflow: hidden;
          margin-right: 20rpx;
          border: 2rpx solid #E0E0E0;

          .progress-fill {
            height: 100%;
            background: #B8E986;
            border-radius: 6rpx;
            transition: width 0.3s;
          }
        }

        .progress-text {
          font-size: 24rpx;
          color: #666666;
          white-space: nowrap;
        }
      }
    }
  }
}

/* VIP会员卡片 - 扁平化 */
.vip-card {
  margin: 30rpx;
  background: #E8E5FF;
  border-radius: 12rpx;
  padding: 30rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border: 2rpx solid #D5CFFF;
  transition: all 0.2s ease;

  &:active {
    background: #D5CFFF;
  }

  .vip-content {
    display: flex;
    align-items: center;

    .vip-icon {
      font-size: 60rpx;
      margin-right: 20rpx;
    }

    .vip-info {
      display: flex;
      flex-direction: column;

      .vip-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #6B4EA3;
        margin-bottom: 8rpx;
      }

      .vip-subtitle {
        font-size: 24rpx;
        color: #8B7BAA;
      }
    }
  }

  .vip-button {
    background: #9575CD;
    color: #FFFFFF;
    padding: 16rpx 32rpx;
    border-radius: 8rpx;
    font-size: 26rpx;
    white-space: nowrap;
    font-weight: 600;
  }
}

/* 专属红娘 - 扁平化 */
.matchmaker-card {
  margin: 30rpx;
  margin-top: 20rpx;
  background: #FFF8E1;
  border-radius: 12rpx;
  padding: 25rpx;
  text-align: center;
  border: 2rpx solid #FFD54F;

  .matchmaker-text {
    font-size: 26rpx;
    color: #F57C00;
    font-weight: 500;
  }
}

/* 快捷入口 - 扁平化 */
.quick-actions {
  margin: 30rpx;
  background-color: #FFFFFF;
  border-radius: 12rpx;
  padding: 40rpx;
  display: flex;
  justify-content: space-around;
  border: 2rpx solid #E0E0E0;

  .action-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    transition: all 0.2s ease;

    &:active {
      transform: scale(0.95);
    }

    .action-icon {
      width: 100rpx;
      height: 100rpx;
      border-radius: 12rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 50rpx;
      margin-bottom: 15rpx;
      border: 2rpx solid #E0E0E0;
    }

    .calendar-icon {
      background: #FFE5E5;
    }

    .phone-icon {
      background: #FFE8F5;
    }

    .heart-icon {
      background: #FFE5E5;
    }

    .action-label {
      font-size: 26rpx;
      color: #666666;
    }
  }
}

/* 功能菜单列表 - 扁平化 */
.menu-list {
  margin: 30rpx;
  background-color: #FFFFFF;
  border-radius: 12rpx;
  overflow: hidden;
  border: 2rpx solid #E0E0E0;

  .menu-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 35rpx 30rpx;
    border-bottom: 2rpx solid #F5F5F5;
    transition: all 0.2s ease;

    &:last-child {
      border-bottom: none;
    }

    &:active {
      background: #F5F5F5;
    }

    .menu-left {
      display: flex;
      align-items: center;

      .menu-icon {
        font-size: 44rpx;
        margin-right: 20rpx;
      }

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

    .menu-arrow {
      font-size: 50rpx;
      color: #CCCCCC;
      font-weight: 300;
    }
  }

  /* 退出登录特殊样式 - 扁平化 */
  .menu-item.logout-item {
    border-top: 2rpx solid #FFE5E5;
    background: #FFF5F5;

    .menu-left .menu-icon {
      color: #E74C3C;
    }

    .menu-left .menu-text {
      color: #E74C3C;
      font-weight: 500;
    }

    .menu-arrow {
      color: #E74C3C;
    }

    &:active {
      background: #FFEBEB;
    }
  }
}

/* 签到弹窗样式 - 扁平化 */
.checkin-popup {
  width: 650rpx;
  max-height: 85vh;
  background-color: #FFFFFF;
  border-radius: 16rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  border: 2rpx solid #E0E0E0;

  .popup-header {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 30rpx 30rpx 20rpx;
    position: relative;
    background: #FFE5F1;
    flex-shrink: 0;
    border-bottom: 2rpx solid #E0E0E0;

    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #E91E63;
    }

    .close-btn {
      position: absolute;
      right: 20rpx;
      top: 25rpx;
      width: 50rpx;
      height: 50rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      .close-icon {
        font-size: 36rpx;
        color: #666666;
      }
    }
  }

  .checkin-info {
    display: flex;
    justify-content: space-around;
    padding: 20rpx 30rpx;
    background: #FFFFFF;
    flex-shrink: 0;
    border-bottom: 2rpx solid #E0E0E0;

    .info-item {
      display: flex;
      flex-direction: column;
      align-items: center;

      .info-label {
        font-size: 22rpx;
        color: #999999;
        margin-bottom: 8rpx;
      }

      .info-value {
        font-size: 36rpx;
        font-weight: bold;
        color: #E91E63;
      }
    }
  }

  .checkin-content {
    flex: 1;
    overflow-y: auto;
    max-height: 50vh;
  }

  .checkin-calendar {
    padding: 20rpx 30rpx;

    .calendar-header {
      text-align: center;
      margin-bottom: 15rpx;

      .month-text {
        font-size: 26rpx;
        font-weight: bold;
        color: #333333;
      }
    }

    .week-header {
      display: flex;
      margin-bottom: 10rpx;

      .week-day {
        flex: 1;
        text-align: center;
        font-size: 22rpx;
        color: #999999;
      }
    }

    .calendar-body {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      gap: 0;

      .calendar-day {
        height: 70rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
        margin-bottom: 8rpx;
        box-sizing: border-box;

        .day-num {
          font-size: 24rpx;
          color: #333333;
        }

        .check-mark {
          position: absolute;
          top: 3rpx;
          right: 3rpx;
          font-size: 18rpx;
          color: #FFFFFF;
          background: #E91E63;
          width: 26rpx;
          height: 26rpx;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        &.empty {
          visibility: hidden;
        }

        &.checked {
          background: #FFE5F1;
          border-radius: 8rpx;
          border: 2rpx solid #E91E63;

          .day-num {
            color: #E91E63;
            font-weight: bold;
          }
        }

        &.today {
          background: #E91E63;
          border-radius: 8rpx;

          .day-num {
            color: #FFFFFF;
            font-weight: bold;
          }
        }

        &.today.checked {
          .check-mark {
            background: #FFFFFF;
            color: #E91E63;
          }
        }
      }
    }
  }

  .checkin-rewards {
    padding: 15rpx 30rpx 20rpx;
    border-top: 1rpx solid #F5F5F5;
    flex-shrink: 0;

    .rewards-title {
      font-size: 26rpx;
      font-weight: bold;
      color: #333333;
      margin-bottom: 15rpx;
      display: block;
    }

    .rewards-list {
      display: flex;
      justify-content: space-between;
      gap: 15rpx;

      .reward-item {
        flex: 1;
        background: #F5F5F5;
        border-radius: 12rpx;
        padding: 20rpx 12rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        position: relative;
        border: 2rpx solid #E0E0E0;

        .reward-icon {
          font-size: 50rpx;
          margin-bottom: 10rpx;
        }

        .reward-day {
          font-size: 24rpx;
          color: #666666;
          margin-bottom: 8rpx;
        }

        .reward-text {
          font-size: 26rpx;
          color: #333333;
          font-weight: bold;
        }

        .received-mark {
          position: absolute;
          top: 8rpx;
          right: 8rpx;
          width: 32rpx;
          height: 32rpx;
          background: #B8E986;
          color: #FFFFFF;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 20rpx;
        }

        &.received {
          opacity: 0.6;
        }

        &.current {
          border-color: #E91E63;
          background: #FFE5F1;

          .reward-text {
            color: #E91E63;
          }
        }
      }
    }
  }

  .checkin-button-wrapper {
    padding: 0 30rpx 25rpx;
    flex-shrink: 0;

    .checkin-btn {
      width: 100%;
      background: #E91E63;
      color: #FFFFFF;
      font-size: 30rpx;
      font-weight: bold;
      border-radius: 8rpx;
      padding: 20rpx;
      border: none;
      transition: all 0.2s ease;

      &:active:not(.disabled) {
        opacity: 0.8;
      }

      &.disabled {
        background: #CCCCCC;
      }

      &::after {
        border: none;
      }
    }
  }
}

/* 底部导航栏 - 扁平化 */
.tabbar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  background-color: #FFFFFF;
  border-top: 1rpx solid #F0F0F0;
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  z-index: 999;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

  .tabbar-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 15rpx 0;
    position: relative;

    .tabbar-icon {
      font-size: 44rpx;
      margin-bottom: 5rpx;
    }

    .tabbar-text {
      font-size: 22rpx;
      color: #666666;
    }

    &.active {
      .tabbar-text {
        color: #E91E63;
        font-weight: bold;
      }
    }
  }
}


.tabbar-badge {
  position: absolute;
  top: 8rpx;
  right: 50%;
  margin-right: -40rpx;
  min-width: 32rpx;
  height: 32rpx;
  line-height: 32rpx;
  padding: 0 6rpx;
  background-color: #FA5151;
  border-radius: 16rpx;
  font-size: 20rpx;
  color: #FFFFFF;
  text-align: center;
}
</style>

