<template>
  <view class="like-page">
    <!-- 数据加载状态 -->
    <view class="loading-container" v-if="loading">
      <uni-loading type="circle" color="#E91E63"></uni-loading>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 空数据状态 -->
    <view class="empty-container" v-else-if="users.length === 0">
      <text class="empty-icon">💔</text>
      <text class="empty-text">暂无喜欢的用户</text>
      <view class="empty-action">
        <button class="action-btn" @click="goRecommend">去推荐看看</button>
      </view>
    </view>

    <!-- 用户列表 -->
    <scroll-view class="user-list" scroll-y="true" @refresherrefresh="onRefresh" @scrolltolower="onLoadMore" refresher-enabled="true" refresher-triggered="refreshing">
      <view class="user-item" v-for="user in users" :key="user.userId" @click="goUserDetail(user.userId)">
        <image class="user-avatar" :src="user.avatar" mode="aspectFill"></image>
        <view class="user-info">
          <view class="user-basic">
            <text class="user-nickname">{{ user.nickname }}</text>
            <text class="user-age">{{ user.age }}岁</text>
          </view>
          <view class="user-details">
            <text class="detail-item" v-if="user.height">{{ user.height }}cm</text>
            <text class="detail-item" v-if="user.weight">{{ user.weight }}kg</text>
            <text class="detail-item" v-if="user.educationText">{{ user.educationText }}</text>
            <text class="detail-item" v-if="user.salaryText">{{ user.salaryText }}</text>
          </view>
          <view class="user-location" v-if="user.location">
            <text class="location-text">{{ user.location }}</text>
          </view>
        </view>
        <view class="like-status" @click.stop="cancelLike(user.userId)">
          <text class="like-icon">❤️</text>
        </view>
      </view>

      <!-- 加载更多提示 -->
      <view class="load-more" v-if="users.length > 0">
        <text v-if="hasMore">加载中...</text>
        <text v-else>没有更多数据了</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import api from '@/utils/api.js'

export default {
  data() {
    return {
      users: [],
      loading: true,
      refreshing: false,
      pageNum: 1,
      pageSize: 20,
      hasMore: true
    }
  },
  onLoad() {
    this.loadUsers()
  },
  methods: {
    // 加载我喜欢的用户列表
    async loadUsers() {
      try {
        // 从本地存储获取当前用户ID
        const userId = parseInt(uni.getStorageSync('userId') || 1)
        // 计算偏移量
        const offset = (this.pageNum - 1) * this.pageSize
        // 调用后端API获取我喜欢的用户列表
        const likedUsers = await api.recommend.getLikedUsers(userId, this.pageSize, offset)
        // 处理返回的数据，确保字段名匹配页面需要的格式
        const formattedUsers = likedUsers.map(user => ({
          userId: user.userId,
          nickname: user.nickname,
          avatar: user.avatarUrl || '',
          age: this.calculateAge(user.birthDate),
          height: user.height,
          weight: user.weight,
          educationText: this.formatEducation(user.educationLevel),
          salaryText: this.formatSalary(user.salaryRange),
          location: this.formatLocation(user.provinceId, user.cityId, user.areaId)
        }))

        // 根据是否是刷新操作来处理数据
        if (this.pageNum === 1) {
          // 首次加载或刷新，直接替换数据
          this.users = formattedUsers
        } else {
          // 加载更多，追加数据
          this.users = [...this.users, ...formattedUsers]
        }

        // 判断是否还有更多数据
        this.hasMore = formattedUsers.length >= this.pageSize
      } catch (error) {
        console.error('加载喜欢的用户失败:', error)
        uni.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        })
      } finally {
        this.loading = false
        this.refreshing = false
      }
    },

    // 下拉刷新
    async onRefresh() {
      this.refreshing = true
      this.pageNum = 1
      this.hasMore = true
      await this.loadUsers()
    },

    // 上拉加载更多
    async onLoadMore() {
      if (this.loading || !this.hasMore) return
      this.pageNum++
      await this.loadUsers()
    },

    // 计算年龄
    calculateAge(birthDate) {
      if (!birthDate) return ''
      const birth = new Date(birthDate)
      const now = new Date()
      let age = now.getFullYear() - birth.getFullYear()
      if (now.getMonth() < birth.getMonth() || (now.getMonth() === birth.getMonth() && now.getDate() < birth.getDate())) {
        age--
      }
      return age
    },

    // 格式化教育程度
    formatEducation(educationLevel) {
      if (!educationLevel) return ''
      const map = {1:'高中',2:'大专',3:'本科',4:'硕士',5:'博士'}
      return map[educationLevel] || ''
    },

    // 格式化薪资
    formatSalary(salaryRange) {
      if (!salaryRange) return ''
      const map = {1:'<5k',2:'5-10k',3:'10-20k',4:'20-50k',5:'50k+'}
      return map[salaryRange] || ''
    },

    // 格式化地理位置
    formatLocation(provinceId, cityId, areaId) {
      // 这里简化处理，实际可以根据ID查询名称
      // 由于没有实时获取地区名称的API，暂时返回空字符串
      return ''
    },

    // 取消喜欢
    async cancelLike(targetUserId) {
      try {
        // 从本地存储获取当前用户ID
        const userId = parseInt(uni.getStorageSync('userId') || 1)
        // 调用后端API取消喜欢
        await api.recommend.feedback({ userId, targetUserId, type: 'dislike' })
        // 刷新页面，重新加载喜欢的用户列表
        await this.onRefresh()
        // 显示操作成功提示
        uni.showToast({ title: '已取消喜欢', icon: 'success' })
      } catch (error) {
        console.error('取消喜欢失败:', error)
        uni.showToast({ title: '取消喜欢失败', icon: 'none' })
      }
    },

    // 跳转到用户详情页
    goUserDetail(userId) {
      uni.navigateTo({
        url: `/pages/recommend/user-detail?userId=${userId}`,
        fail: (err) => {
          console.error('跳转用户详情失败:', err)
          uni.showToast({
            title: '页面不存在',
            icon: 'none'
          })
        }
      })
    },

    // 跳转到推荐页面
    goRecommend() {
      uni.navigateTo({
        url: '/pages/recommend/index'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.like-page {
  min-height: 100vh;
  background-color: #F5F5F5;
  padding: 0 5rpx;
  box-sizing: border-box;
  overflow-x: hidden;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;

  .loading-text {
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #999999;
  }
}

.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 150rpx 0;

  .empty-icon {
    font-size: 120rpx;
    margin-bottom: 30rpx;
  }

  .empty-text {
    font-size: 32rpx;
    color: #999999;
    margin-bottom: 40rpx;
  }

  .action-btn {
    background: linear-gradient(135deg, #FF6B9D 0%, #E91E63 100%);
    color: #FFFFFF;
    border: none;
    padding: 18rpx 70rpx;
    border-radius: 45rpx;
    font-size: 28rpx;
    font-weight: 600;
    box-shadow: 0 6rpx 20rpx rgba(233, 30, 99, 0.3);
    transition: all 0.3s ease;
    letter-spacing: 1rpx;

    &:active {
      transform: translateY(2rpx);
      box-shadow: 0 3rpx 12rpx rgba(233, 30, 99, 0.4);
      background: linear-gradient(135deg, #E91E63 0%, #C2185B 100%);
    }
  }
}

.user-list {
  padding: 20rpx;
  height: 100vh;
  box-sizing: border-box;
  overflow-x: hidden;
}

.load-more {
  text-align: center;
  padding: 30rpx 0;
  font-size: 28rpx;
  color: #999999;
}

.user-item {
  display: flex;
  align-items: center;
  background-color: #FFFFFF;
  border-radius: 20rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;

  &:active {
    transform: translateY(2rpx);
    box-shadow: 0 1rpx 5rpx rgba(0, 0, 0, 0.05);
  }

  .user-avatar {
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
    margin-right: 20rpx;
    border: 4rpx solid #FFF9F9;
    box-shadow: 0 4rpx 15rpx rgba(233, 30, 99, 0.2);
  }

  .user-info {
    flex: 1;

    .user-basic {
      display: flex;
      align-items: center;
      margin-bottom: 10rpx;

      .user-nickname {
        font-size: 32rpx;
        font-weight: bold;
        color: #333333;
        margin-right: 15rpx;
      }

      .user-age {
        font-size: 28rpx;
        color: #666666;
      }
    }

    .user-details {
      display: flex;
      flex-wrap: wrap;
      gap: 15rpx;
      margin-bottom: 10rpx;

      .detail-item {
        font-size: 24rpx;
        color: #999999;
        background-color: #F5F5F5;
        padding: 6rpx 15rpx;
        border-radius: 15rpx;
      }
    }

    .user-location {
      .location-text {
        font-size: 24rpx;
        color: #999999;
      }
    }
  }

  .like-status {
    .like-icon {
      font-size: 40rpx;
      color: #E91E63;
    }
  }
}
</style>