<template>
  <view class="page-container">
    <!-- 顶部导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-back" @click="handleBack">
        <text class="back-icon">←</text>
      </view>
      <view class="navbar-title">
        <text class="title-text">积分记录</text>
      </view>
      <view class="navbar-placeholder"></view>
    </view>

    <!-- 积分记录列表 -->
    <scroll-view class="scroll-view" scroll-y>
      <view class="transaction-list">
        <!-- 按日期分组显示 -->
        <view v-for="(group, dateKey) in groupedRecords" :key="dateKey" class="date-group">
          <view class="date-header">
            <text class="date-text">{{ dateKey }}</text>
          </view>
          
          <view 
            v-for="(item, index) in group" 
            :key="index"
            class="transaction-item"
          >
            <view class="item-left">
              <view class="stock-info">
                <text class="stock-name">{{ item.title }}</text>
              </view>
              <text class="transaction-time">{{ formatTime(item.timestamp) }}</text>
            </view>
            
            <view class="item-right">
              <text :class="['amount-text', item.type === 'add' ? 'amount-sell' : 'amount-buy']">
                {{ item.type === 'add' ? '+' : '-' }}{{ item.points }}积分
              </text>
              <view :class="['status-badge', item.type === 'add' ? 'status-sell' : 'status-buy']">
                <text class="status-text">{{ item.type === 'add' ? '获得' : '消耗' }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 空状态 -->
        <view v-if="records.length === 0" class="empty-state">
          <text class="empty-icon">💰</text>
          <text class="empty-text">暂无积分记录</text>
          <text class="empty-desc">完成任务即可获得积分</text>
        </view>

        <!-- 底部安全区域 -->
        <view class="bottom-safe-area"></view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

const records = ref([])

// 返回上一页
const handleBack = () => {
  const pages = getCurrentPages()
  if (pages.length > 1) {
    // 有上一页，返回
    uni.navigateBack()
  } else {
    // 没有上一页，跳转到个人中心
    uni.switchTab({
      url: '/pages/mine/mine'
    })
  }
}

// 按日期分组的积分记录
const groupedRecords = computed(() => {
  const groups = {}
  
  records.value.forEach(item => {
    const dateKey = formatDate(item.timestamp)
    if (!groups[dateKey]) {
      groups[dateKey] = []
    }
    groups[dateKey].push(item)
  })
  
  return groups
})

// 格式化日期（用于分组）
const formatDate = (timestamp) => {
  const date = new Date(timestamp)
  const today = new Date()
  const yesterday = new Date(today)
  yesterday.setDate(yesterday.getDate() - 1)
  
  const dateStr = date.toLocaleDateString('zh-CN', { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit' 
  })
  
  const todayStr = today.toLocaleDateString('zh-CN', { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit' 
  })
  
  const yesterdayStr = yesterday.toLocaleDateString('zh-CN', { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit' 
  })
  
  if (dateStr === todayStr) {
    return '今天'
  } else if (dateStr === yesterdayStr) {
    return '昨天'
  } else {
    return dateStr
  }
}

// 格式化时间（仅显示时分）
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  
  return `${hours}:${minutes}`
}

// 加载积分记录
const loadRecords = () => {
  try {
    const storedRecords = uni.getStorageSync('points_records') || []
    // 按时间倒序排列
    records.value = storedRecords.sort((a, b) => b.timestamp - a.timestamp)
  } catch (e) {
    console.error('加载积分记录失败:', e)
    records.value = []
  }
}

// 初始化模拟数据（仅用于演示）
const initMockData = () => {
  const mockRecords = [
    {
      title: '每日签到',
      points: 10,
      type: 'add',
      timestamp: Date.now() - 1000 * 60 * 30
    },
    {
      title: '完成交易',
      points: 5,
      type: 'add',
      timestamp: Date.now() - 1000 * 60 * 60 * 2
    },
    {
      title: '查询股票',
      points: 2,
      type: 'use',
      timestamp: Date.now() - 1000 * 60 * 60 * 5
    },
    {
      title: '邀请好友',
      points: 20,
      type: 'add',
      timestamp: Date.now() - 1000 * 60 * 60 * 24
    },
    {
      title: '解锁超短池',
      points: 18,
      type: 'use',
      timestamp: Date.now() - 1000 * 60 * 60 * 24 * 2
    }
  ]
  
  // 如果没有记录，使用模拟数据
  if (records.value.length === 0) {
    records.value = mockRecords
    uni.setStorageSync('points_records', mockRecords)
  }
}

onMounted(() => {
  loadRecords()
  initMockData()
})
</script>

<style scoped>
.page-container {
  min-height: 100vh;
  background: #f5f6fb;
  display: flex;
  flex-direction: column;
}

/* 自定义导航栏 */
.custom-navbar {
  background: #ffffff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 80rpx 32rpx 30rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
  position: relative;
}

.navbar-back {
  width: 80rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.back-icon {
  font-size: 40rpx;
  color: #222222;
  font-weight: bold;
}

.navbar-title {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.title-text {
  font-size: 36rpx;
  font-weight: 800;
  color: #3F51F7;
  letter-spacing: 2rpx;
}

.navbar-placeholder {
  width: 80rpx;
}

/* 交易记录列表 */
.scroll-view {
  flex: 1;
  height: 0;
}

.transaction-list {
  padding: 0 0 32rpx;
}

/* 日期分组 */
.date-group {
  margin-bottom: 32rpx;
}

.date-header {
  padding: 24rpx 32rpx 16rpx;
}

.date-text {
  font-size: 26rpx;
  color: #9ca2b5;
  font-weight: 500;
}

/* 交易项 */
.transaction-item {
  background: #ffffff;
  padding: 32rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1rpx solid #f5f6fb;
}

.transaction-item:first-child {
  border-top-left-radius: 0;
  border-top-right-radius: 0;
}

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

.item-left {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.stock-info {
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;
}

.stock-name {
  font-size: 30rpx;
  font-weight: 600;
  color: #222222;
  margin-right: 12rpx;
}

.transaction-time {
  font-size: 24rpx;
  color: #9ca2b5;
}

.item-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.amount-text {
  font-size: 32rpx;
  font-weight: 700;
  margin-bottom: 8rpx;
}

.amount-buy {
  color: #3abf81;
}

.amount-sell {
  color: #f16565;
}

.status-badge {
  padding: 4rpx 16rpx;
  border-radius: 12rpx;
}

.status-buy {
  background: #e7f7ef;
}

.status-sell {
  background: #ffe7ee;
}

.status-text {
  font-size: 22rpx;
  font-weight: 500;
}

.status-buy .status-text {
  color: #3abf81;
}

.status-sell .status-text {
  color: #f16565;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 120rpx 0;
  background: #ffffff;
  margin: 0 32rpx;
  border-radius: 24rpx;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 32rpx;
  opacity: 0.5;
}

.empty-text {
  font-size: 32rpx;
  color: #666666;
  margin-bottom: 16rpx;
  font-weight: 500;
}

.empty-desc {
  font-size: 26rpx;
  color: #9ca2b5;
}

.bottom-safe-area {
  height: 40rpx;
}
</style>
