<template>
  <div class="points-history-page">
    <!-- 导航栏 -->
    <nav class="navbar">
      <div class="nav-center">
        <h1 class="nav-title">积分记录</h1>
      </div>
      <div class="nav-right">
        <el-button 
          type="text" 
          @click="$router.push('/shop')"
          class="shop-btn"
        >
          <el-icon><ShoppingBag /></el-icon>
          商城
        </el-button>
      </div>
    </nav>

    <!-- 积分概览 -->
    <div class="points-overview">
      <div class="overview-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>
        </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 class="date-filter">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          size="small"
          @change="onDateChange"
        />
      </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>1</span>
            </div>
            <div class="rule-item">
              <el-icon><Calendar /></el-icon>
              <span>2</span>
            </div>
            <div class="rule-item">
              <el-icon><Share /></el-icon>
              <span>3</span>
            </div>
            <div class="rule-item">
              <el-icon><Star /></el-icon>
              <span>4</span>
            </div>
            <div class="rule-item">
              <el-icon><Trophy /></el-icon>
              <span>5</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>
</template>

<script setup>
import { ref, reactive, 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,
  Present,
  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 dateRange = ref([])
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(() => {
  // 确保history.value是数组，避免undefined错误
  let filtered = history.value || []
  
  // 按类型筛选
  if (selectedFilter.value !== 'all') {
    filtered = filtered.filter(record => record.type === selectedFilter.value)
  }
  
  // 按日期筛选
  if (dateRange.value && dateRange.value.length === 2) {
    const [startDate, endDate] = dateRange.value
    filtered = filtered.filter(record => {
      const recordDate = new Date(record.createdAt)
      return recordDate >= startDate && recordDate <= endDate
    })
  }
  
  return filtered
})

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

const onDateChange = () => {
  // 日期变化时重新加载数据
  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,
    gift: Present,
    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',
    gift: 'icon-present',
    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 formatDateTime = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

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

const getUserPoints = async () => {
  try {
    const response = await api.get('/user/points')
    userPoints.value = response.data.currentPoints
    totalEarned.value = response.data.totalEarned
    totalSpent.value = response.data.totalSpent
  } catch (error) {
    ElMessage.error('获取积分信息失败')
  }
}

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
    }
    
    // 添加日期筛选参数
    if (dateRange.value && dateRange.value.length === 2) {
      params.startDate = dateRange.value[0].toISOString()
      params.endDate = dateRange.value[1].toISOString()
    }
    
    const response = await api.get('/user/points/history', { params })
    
    // 确保响应数据是数组
    const historyData = response.data.history || []
    
    if (isLoadMore) {
      history.value.push(...historyData)
    } else {
      history.value = historyData
    }
    
    hasMore.value = response.data.hasMore || false
    page.value++
  } catch (error) {
    console.error('获取积分记录失败:', error)
    ElMessage.error('获取积分记录失败')
    // 确保在错误情况下history仍然是数组
    if (!isLoadMore) {
      history.value = []
    }
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

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

// 生命周期
onMounted(() => {
  getUserPoints()
  getHistory()
})
</script>

<style scoped>
.points-history-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  height: 56px;
  background: white;
  border-bottom: 1px solid #eee;
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-left,
.nav-right {
  flex: 1;
}

.nav-right {
  display: flex;
  justify-content: flex-end;
}

.back-btn,
.shop-btn {
  color: #409eff;
  font-size: 14px;
}

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

.points-overview {
  padding: 16px;
}

.overview-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  padding: 24px;
  color: white;
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.3);
}

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

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

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

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

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

.stat-item {
  text-align: center;
}

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

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

.filter-section {
  background: white;
  border-bottom: 1px solid #eee;
  padding: 16px;
}

.filter-tabs {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
  overflow-x: auto;
}

.tab-item {
  padding: 8px 16px;
  border-radius: 20px;
  background: #f5f5f5;
  color: #666;
  font-size: 14px;
  cursor: pointer;
  white-space: nowrap;
  transition: all 0.3s;
}

.tab-item.active {
  background: #409eff;
  color: white;
}

.date-filter {
  display: flex;
  justify-content: center;
}

.history-content {
  padding: 16px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

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

.history-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  background: white;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

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

.item-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  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-present {
  background: #f9f0ff;
  color: #722ed1;
}

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

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

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

.item-content {
  flex: 1;
}

.item-header {
  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;
}

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

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

.points-negative {
  color: #ff4d4f;
}

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

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

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

.item-date {
  flex: 1;
}

.item-order {
  color: #409eff;
}

.item-action {
  display: flex;
  align-items: center;
}

.load-more {
  text-align: center;
  padding: 20px;
}

.points-rules {
  margin: 16px;
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.rules-content {
  padding: 16px;
}

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

.rule-item .el-icon {
  color: #409eff;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .points-stats {
    gap: 16px;
  }
  
  .item-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .item-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .current-points {
    flex-direction: column;
    text-align: center;
    gap: 8px;
  }
}
</style>