<template>
  <div class="container">
    <div class="main-content">
      <!-- 导航栏 -->
      <nav class="navbar transparent">
        <div class="nav-left">
          <el-button type="text" @click="$router.back()" class="back-btn">
            <el-icon><ArrowLeft /></el-icon>
          </el-button>
        </div>
        <div class="nav-center">
          <h1 class="nav-title">积分记录</h1>
        </div>
        <div class="nav-right">
          <el-button type="text" @click="$router.push('/myshop')" class="shop-btn">
            <el-icon><ShoppingBag /></el-icon>
            商城
          </el-button>
        </div>
      </nav>

      <!-- 积分概览 -->
      <div class="points-overview">
        <div class="overview-card transparent-card">
          <div class="current-points">
            <div class="points-icon">
              <el-icon size="24"><Coin /></el-icon>
            </div>
            <div class="points-info">
              <div class="points-value">{{ userPoints }}</div>
              <!-- <div class="points-label">当前积分</div> -->
            </div>
            <img src="/imgs/point.png" alt="我的积分图标" class="balance-image">
          </div>
          <div class="points-stats">
            <div class="stat-item">
              <div class="stat-value">{{ totalEarned }}</div>
              <div class="stat-label">累计获得</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ totalSpent }}</div>
              <div class="stat-label">累计消费</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 筛选器 -->
      <div class="filter-section">
        <div class="filter-tabs">
          <div
            v-for="tab in filterTabs"
            :key="tab.value"
            :class="['tab-item', { active: selectedFilter === tab.value }]"
            @click="selectFilter(tab.value)"
          >
            {{ tab.label }}
          </div>
        </div>
      </div>

      <!-- 积分记录列表 -->
      <div class="history-content">
        <div v-loading="loading" class="history-list">
          <div v-if="filteredHistory.length === 0" class="empty-state">
            <el-icon size="60"><DocumentRemove /></el-icon>
            <p>{{ getEmptyText() }}</p>
            <el-button type="primary" @click="$router.push('/shop')">
              去赚积分
            </el-button>
          </div>

          <div v-else>
            <div v-for="record in filteredHistory" :key="record.id" class="history-item">
              <div class="item-icon">
                <el-icon :size="20" :class="getIconClass(record.type)">
                  <component :is="getIcon(record.type)" />
                </el-icon>
              </div>
              <div class="item-content">
                <div class="item-header">
                  <h4 class="item-title">{{ record.title }}</h4>
                  <div :class="['item-points', getPointsClass(record.type)]">
                    {{ getPointsText(record.type, record.points) }}
                  </div>
                </div>
                <div class="item-details">
                  <p class="item-description">{{ record.description }}</p>
                  <div class="item-meta">
                    <span class="item-date">{{ formatDateTime(record.createdAt) }}</span>
                    <span v-if="record.orderId" class="item-order">
                      订单号：{{ record.orderId }}
                    </span>
                  </div>
                </div>
              </div>
              <div class="item-action">
                <el-button
                  v-if="record.orderId"
                  type="text"
                  size="small"
                  @click="viewOrder(record.orderId)"
                >
                  查看订单
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 加载更多 -->
        <div v-if="hasMore" class="load-more">
          <el-button @click="loadMore" :loading="loadingMore">
            加载更多
          </el-button>
        </div>
      </div>

      <!-- 积分规则说明 -->
      <div class="points-rules">
        <el-collapse v-model="activeRules">
          <el-collapse-item title="积分获取规则" name="earn">
            <!-- <div class="rules-content">
              <div class="rule-item">
                <el-icon><UserFilled /></el-icon>
                <span>注册账户：+100积分</span>
              </div>
              <div class="rule-item">
                <el-icon><Calendar /></el-icon>
                <span>每日签到：+10积分</span>
              </div>
              <div class="rule-item">
                <el-icon><Share /></el-icon>
                <span>分享商品：+5积分</span>
              </div>
              <div class="rule-item">
                <el-icon><Star /></el-icon>
                <span>商品评价：+20积分</span>
              </div>
              <div class="rule-item">
                <el-icon><Trophy /></el-icon>
                <span>完成任务：+50积分</span>
              </div>
            </div> -->
          </el-collapse-item>
          <el-collapse-item title="积分使用规则" name="spend">
            <div class="rules-content">
              <div class="rule-item">
                <el-icon><ShoppingBag /></el-icon>
                <span>商品兑换：按商品标价扣除</span>
              </div>
              <div class="rule-item">
                <el-icon><Clock /></el-icon>
                <span>积分有效期：永久有效</span>
              </div>
              <div class="rule-item">
                <el-icon><Warning /></el-icon>
                <span>积分不可转让，不可提现</span>
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import {
  ArrowLeft,
  ShoppingBag,
  Coin,
  DocumentRemove,
  Plus,
  Minus,
  ShoppingCart,
  Star,
  Calendar,
  Share,
  Trophy,
  UserFilled,
  Clock,
  Warning
} from '@element-plus/icons-vue'
import api from '@/utils/api'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const loadingMore = ref(false)
const selectedFilter = ref('all')
const history = ref([])
const page = ref(1)
const hasMore = ref(true)
const userPoints = ref(0)
const totalEarned = ref(0)
const totalSpent = ref(0)
const activeRules = ref([])

// 筛选标签
const filterTabs = ref([
  { label: '全部', value: 'all' },
  { label: '获得', value: 'earn' },
  { label: '消费', value: 'spend' },
  { label: '任务', value: 'task' },
  { label: '兑换', value: 'exchange' }
])

// 计算属性
const filteredHistory = computed(() => {
  let filtered = history.value || []
  if (selectedFilter.value !== 'all') {
    filtered = filtered.filter(record => record.type === selectedFilter.value)
  }
  return filtered
})

// 方法
const selectFilter = (filter) => {
  selectedFilter.value = filter
  getHistory()
}

const getEmptyText = () => {
  const textMap = {
    all: '暂无积分记录',
    earn: '暂无获得记录',
    spend: '暂无消费记录',
    task: '暂无任务记录',
    exchange: '暂无兑换记录'
  }
  return textMap[selectedFilter.value]
}

const getIcon = (type) => {
  const iconMap = {
    earn: Plus,
    spend: Minus,
    task: Trophy,
    exchange: ShoppingCart,
    review: Star,
    share: Share
  }
  return iconMap[type] || Plus
}

const getIconClass = (type) => {
  const classMap = {
    earn: 'icon-earn',
    spend: 'icon-spend',
    task: 'icon-task',
    exchange: 'icon-exchange',
    review: 'icon-review',
    share: 'icon-share'
  }
  return classMap[type] || 'icon-default'
}

const getPointsClass = (type) => {
  return type === 'spend' || type === 'exchange' ? 'points-negative' : 'points-positive'
}

const getPointsText = (type, points) => {
  const isNegative = type === 'spend' || type === 'exchange'
  return isNegative ? `-${points}` : `+${points}`
}

const getRecordTitle = (type, description) => {
  const titleMap = {
    earn: '积分获得',
    spend: '积分消费',
    task: '任务奖励',
    exchange: '商品兑换',
    review: '评价奖励',
    share: '分享奖励',
    refund: '积分退还'
  }
  
  // 如果有特定的描述，可以根据描述生成更具体的标题
  if (description.includes('订单支付')) {
    return '订单支付'
  } else if (description.includes('转账确认收款')) {
    return '转账收款奖励'
  } else if (description.includes('订单取消')) {
    return '订单取消退款'
  }
  
  return titleMap[type] || '积分变动'
}

const formatDateTime = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

const viewOrder = (orderId) => {
  router.push(`/payloading?orderId=${orderId}`)
}

const getUserPoints = async () => {
  try {
    const response = await api.get('/user/points')
    
    // 添加更灵活的数据提取方式
    userPoints.value = response.data?.currentPoints ?? response.data?.points ?? 0
    totalEarned.value = response.data?.totalEarned ?? 0
    totalSpent.value = response.data?.totalSpent ?? 0
    
  } catch (error) {
    console.error("获取积分信息失败:", error)
    ElMessage.error('获取积分信息失败')
    userPoints.value = 0
    totalEarned.value = 0
    totalSpent.value = 0
  }
}

const getHistory = async (isLoadMore = false) => {
  try {
    if (!isLoadMore) {
      loading.value = true
      page.value = 1
    } else {
      loadingMore.value = true
    }

    const params = {
      page: page.value,
      limit: 20,
      type: selectedFilter.value !== 'all' ? selectedFilter.value : undefined
    }

    const response = await api.get('/user/points/history', { params })
    const records = response.data.data?.records || []
    
    // 转换数据格式以匹配模板需求
    const historyData = records.map(record => ({
      id: record.id,
      type: record.type,
      points: record.amount,
      title: getRecordTitle(record.type, record.description),
      description: record.description,
      createdAt: record.created_at,
      orderId: record.order_id
    }))

    if (isLoadMore) {
      history.value.push(...historyData)
    } else {
      history.value = historyData
    }

    // 使用pagination对象判断是否还有更多数据
    const pagination = response.data.data?.pagination
    if (pagination) {
      hasMore.value = pagination.page < pagination.totalPages
      page.value = pagination.page + 1
    } else {
      hasMore.value = false
      page.value++
    }
  } catch (error) {
    console.error('获取积分记录失败:', error)
    ElMessage.error('获取积分记录失败')
    if (!isLoadMore) {
      history.value = []
    }
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

const loadMore = () => {
  getHistory(true)
}

onMounted(() => {
  getUserPoints()
  getHistory()
})
</script>

<style scoped>
/* 基础样式变量 */
/* 基础样式变量 */
:root {
  --primary-color: #4361ee;
  --secondary-color: #3f37c9;
  --accent-color: #4895ef;
  --light-color: #f8f9fa;
  --dark-color: #212529;
  --success-color: #4cc9f0;
  --warning-color: #f8961e;
  --danger-color: #f72585;
  --border-radius: 12px;
  --box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  --transition: all 0.3s ease;
}

/* 容器布局 */
.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  width: 100%;
  max-width: 100vw;
  margin: 0;
  padding: 0;
  overflow-x: hidden;
  background: linear-gradient(to bottom, #72c9ffae, #f3f3f3);
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.main-content {
  border-radius: 12px;
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 16px;
  gap: 16px;
  max-width: 375px;
  margin: 0 auto;
  width: 100%;
  box-sizing: border-box;
  overflow-x: hidden;
}

/* 导航栏样式 */
.navbar {
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 0px;
  height: 56px;
  transition: var(--transition);
  width: 100%;
}

.nav-left {
  border-radius: 12px;
  margin-right: auto;
  padding-left: 0px;
}

.nav-right {
  border-radius: 12px;
  margin-left: auto;
  padding-right: 0px;
}

.nav-center {
  border-radius: 12px;
  flex: 1;
  text-align: center;
}

.navbar.transparent {
  background: transparent;
  box-shadow: none;
}

.back-btn,
.shop-btn,
.nav-title {
  color: white;
  font-size: 14px;
}

.nav-title {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

/* 积分概览区域 */
.points-overview {
  border-radius: 12px;
  width: 100%;
}

.overview-card {
  border-radius: 12px;
  padding: 24px;
  color: white;
  width: 100%;
  overflow: hidden;
}

.transparent-card {
  background: rgba(255, 255, 255, 0.2);
  box-shadow: none;
}

.current-points {
  border-radius: 12px;
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
}

.points-icon {
  border-radius: 50%;
  width: 48px;
  height: 48px;
  background: rgba(255, 255, 255, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
}

.points-value {
  font-size: 32px;
  font-weight: 700;
  line-height: 1;
  color: #333;
}

.points-label {
  font-size: 14px;
  opacity: 0.8;
  margin-top: 4px;
  color: #666;
}

.points-stats {
  border-radius: 12px;
  display: flex;
  gap: 32px;
}

.stat-item {
  border-radius: 12px;
  text-align: center;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  line-height: 1;
  color: #333;
}

.stat-label {
  font-size: 12px;
  opacity: 0.8;
  margin-top: 4px;
  color: #666;
}

/* 筛选器区域 - 按钮均分 */
.filter-section {
  border-radius: 12px;
  background: white;
  box-shadow: var(--box-shadow);
  padding: 16px;
  width: 100%;
  overflow: hidden;
}

.filter-tabs {
  border-radius: 12px;
  display: flex;
  justify-content: space-between;
  gap: 6px;
  width: 100%;
}

.tab-item {
  border-radius: 20px;
  flex: 1;
  padding: 6px 12px;
  background: #f5f5f5;
  color: #666;
  font-size: 12px;
  cursor: pointer;
  transition: var(--transition);
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.tab-item.active {
  background: rgb(125, 216, 255);
  color: white;
}

/* 积分记录列表 */
.history-content {
  border-radius: 12px;
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.empty-state {
  border-radius: 12px;
  text-align: center;
  padding: 60px 20px;
  color: #999;
  background: white;
  box-shadow: var(--box-shadow);
  overflow: hidden;
}

.history-list {
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.history-item {
  border-radius: 12px;
  display: flex;
  align-items: flex-start;
  gap: 12px;
  background: white;
  padding: 16px;
  box-shadow: var(--box-shadow);
  transition: var(--transition);
  overflow: hidden;
  margin-bottom: 10px;
}

.history-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
}

.item-icon {
  border-radius: 50%;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.icon-earn {
  background: #e8f5e8;
  color: #52c41a;
}

.icon-spend {
  background: #fff2e8;
  color: #fa8c16;
}

.icon-task {
  background: #f6ffed;
  color: #52c41a;
}

.icon-exchange {
  background: #fff0f6;
  color: #eb2f96;
}

.icon-review {
  background: #fff7e6;
  color: #fa8c16;
}

.icon-share {
  background: #e6fffb;
  color: #13c2c2;
}

.icon-default {
  background: #f5f5f5;
  color: #999;
}

.item-content {
  border-radius: 12px;
  flex: 1;
}

.item-header {
  border-radius: 12px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.item-title {
  margin: 0;
  font-size: 16px;
  color: #333;
  font-weight: 500;
  line-height: 1.4;
  word-wrap: break-word;
  word-break: break-all;
  overflow-wrap: break-word;
}

.item-points {
  font-size: 16px;
  font-weight: 600;
  white-space: nowrap;
}

.points-positive {
  color: #52c41a;
}

.points-negative {
  color: #ff4d4f;
}

.item-details {
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.item-description {
  margin: 0;
  font-size: 14px;
  color: #666;
  line-height: 1.4;
  word-wrap: break-word;
  word-break: break-all;
  overflow-wrap: break-word;
}

.item-meta {
  border-radius: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #999;
}

.item-date {
  flex: 1;
}

.item-order {
  color: var(--primary-color);
}

.item-action {
  border-radius: 12px;
  display: flex;
  align-items: center;
}

/* 加载更多按钮 */
.load-more {
  border-radius: 12px;
  text-align: center;
  padding: 8px;
}

.load-more .el-button {
  border-radius: 12px;
  width: 128px;
  height: 44px;
  padding: 12px;
  background: linear-gradient(to right, #4facfe 0%, #00f2fe 100%);
  color: white;
  border: none;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: var(--transition);
  box-shadow: var(--box-shadow);
}

.load-more .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
  background: linear-gradient(to right, #4facfe 0%, #00f2fe 100%);
}

/* 积分规则说明 */
.points-rules {
  border-radius: 12px;
  background: white;
  box-shadow: var(--box-shadow);
  overflow: hidden;
  width: 100%;
  margin-bottom: 20px;
}

.rules-content {
  border-radius: 12px;
  padding: 16px;
}

.rule-item {
  border-radius: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 0;
  font-size: 14px;
  color: #666;
}

.rule-item .el-icon {
  color: var(--primary-color);
}

/* Element Plus 组件样式修复 */
.el-collapse {
  border-radius: 12px !important;
  border: none !important;
  overflow: hidden !important;
}

.el-collapse-item {
  border-radius: 12px !important;
  overflow: hidden !important;
}

.el-collapse-item__header {
  border-radius: 12px !important;
  padding: 16px !important;
  border-bottom: 1px solid #f0f0f0 !important;
  font-size: 16px !important;
  color: #333 !important;
}

.el-collapse-item__content {
  border-radius: 12px !important;
  padding: 0 !important;
}

.el-button {
  border-radius: 12px !important;
}

.el-button--primary {
  background: linear-gradient(to right, #4facfe 0%, #00f2fe 100%) !important;
  border: none !important;
  border-radius: 12px !important;
  transition: var(--transition) !important;
}

.el-button--primary:hover {
  transform: translateY(-2px) !important;
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15) !important;
}

.el-loading-mask {
  border-radius: 12px !important;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .main-content {
    padding: 12px;
    max-width: 100%;
    overflow-x: hidden;
  }

  .overview-card {
    padding: 16px;
  }

  .current-points {
    flex-direction: column;
    text-align: center;
    gap: 12px;
    padding-right: 0;
    align-items: center;
  }

  .balance-image {
    position: static;
    transform: none;
    height: 80px;
    max-width: 80px;
    margin-top: 8px;
  }

  .points-info {
    text-align: center;
  }

  .points-value {
    font-size: 28px;
  }

  .points-stats {
    gap: 24px;
    justify-content: center;
  }

  .stat-value {
    font-size: 18px;
  }

  .item-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .item-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .filter-tabs {
    gap: 4px;
  }

  .tab-item {
    padding: 8px 6px;
    font-size: 12px;
  }

  .history-item {
    padding: 12px;
  }

  .item-title {
    font-size: 14px;
    line-height: 1.3;
  }

  .item-description {
    font-size: 13px;
    line-height: 1.3;
  }

  .item-points {
    font-size: 14px;
  }
}

@media (max-width: 375px) {
  .main-content {
    padding: 8px;
  }

  .overview-card {
    padding: 12px;
  }

  .points-value {
    font-size: 24px;
  }

  .stat-value {
    font-size: 16px;
  }

  .tab-item {
    padding: 6px 4px;
    font-size: 11px;
  }
}

/* 图片样式 */
.balance-image {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  height: 120px;
  max-width: 100px;
  object-fit: contain;
}

/* 调整当前积分容器为相对定位 */
.current-points {
  position: relative;
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
  padding-right: 120px; /* 为图片留出更多空间 */
}

/* 调整积分概览卡片为相对定位 */
.overview-card {
  position: relative;
  border-radius: 12px;
  padding: 24px;
  color: white;
  width: 100%;
  overflow: hidden;
}
</style>