<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '消费记录',
  },
}
</route>

<template>
  <view class="min-h-screen bg-gray-50 pb-20">
    <!-- 消费统计 -->
    <view class="mx-4 mt-4">
      <view class="bg-white rounded-2xl shadow-sm p-6">
        <view class="text-center">
          <text class="text-lg font-bold text-gray-800 mb-2 block">消费统计</text>
          <view class="grid grid-cols-2 gap-4">
            <view class="text-center">
              <text class="text-2xl font-bold text-sky-500 block">¥{{ totalSpend }}</text>
              <text class="text-sm text-gray-500">总消费</text>
            </view>
            <view class="text-center">
              <text class="text-2xl font-bold text-indigo-500 block">{{ spendCount }}</text>
              <text class="text-sm text-gray-500">消费次数</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 消费记录列表 -->
    <view class="mx-4 mt-4">
      <view class="bg-white rounded-2xl shadow-sm overflow-hidden">
        <view class="p-4 border-b border-gray-100 flex justify-between items-center">
          <text class="text-base font-bold text-gray-800">消费明细</text>
          <text class="text-sm text-sky-500" @tap="refreshData">刷新</text>
        </view>
        <view v-if="loading" class="p-8 text-center">
          <text class="text-gray-500">加载中...</text>
        </view>
        <view v-else-if="error" class="p-8 text-center">
          <text class="text-red-500">{{ error }}</text>
        </view>
        <view v-else-if="spendList.length === 0" class="p-8 text-center">
          <text class="text-gray-500">暂无消费记录</text>
        </view>
        <view v-else class="divide-y divide-gray-100">
          <view
            v-for="(item, index) in spendList"
            :key="index"
            class="p-4 flex items-center justify-between"
          >
            <view>
              <text
                :class="[
                  'block text-sm',
                  item.spendType === '1'
                    ? 'text-yellow-300 font-semibold border-l-2 border-purple-500 pl-2'
                    : item.spendType === '2'
                      ? 'text-emerald-300 font-semibold border-l-2 border-emerald-500 pl-2'
                      : 'text-gray-600 border-l-2 border-gray-300 pl-2',
                ]"
              >
                {{ getSpendTypeText(item.spendType) }}
              </text>
              <text class="text-sm text-gray-500">{{ formatDate(item.createTime) }}</text>
            </view>
            <text class="text-lg font-bold text-red-500">-¥{{ formatPrice(item.spendPrice) }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { getUserSpendHistoryAPI } from '@/service/login'
import type { SpendHistoryItem } from '@/service/login/type'

const spendList = ref<SpendHistoryItem[]>([])
const userId = ref('')
const loading = ref(false)
const error = ref('')

// 获取用户ID
const getUserInfo = () => {
  try {
    const userInfo = uni.getStorageSync('loginData')
    if (!userInfo || !userInfo.id) {
      error.value = '未获取到用户信息，请重新登录'
      return false
    }
    userId.value = userInfo.id
    return true
  } catch (e) {
    error.value = '获取用户信息失败'
    return false
  }
}

// 计算总消费
const totalSpend = computed(() => {
  return spendList.value.reduce((sum, item) => sum + Number(item.spendPrice), 0).toFixed(2)
})

// 计算消费次数
const spendCount = computed(() => spendList.value.length)

// 获取消费类型文本
const getSpendTypeText = (type: number) => {
  const typeMap: Record<number, string> = {
    1: '解锁用户',
    2: '参加活动',
    3: '其他',
  }
  return typeMap[type] || '未知类型'
}

// 格式化日期
const formatDate = (dateStr: string) => {
  try {
    const date = new Date(dateStr)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
  } catch (e) {
    return dateStr
  }
}

// 格式化价格
const formatPrice = (price: string) => {
  try {
    return Number(price).toFixed(2)
  } catch (e) {
    return '0.00'
  }
}

// 获取消费记录
const getSpendList = async () => {
  if (!getUserInfo()) {
    uni.showToast({
      title: error.value,
      icon: 'none',
      duration: 2000,
    })
    return
  }

  loading.value = true
  error.value = ''

  try {
    const res = await getUserSpendHistoryAPI(userId.value)
    if (res.code === 200) {
      spendList.value = res.data || []
    } else {
      error.value = res.message || '获取消费记录失败'
      uni.showToast({
        title: error.value,
        icon: 'none',
        duration: 2000,
      })
    }
  } catch (e) {
    error.value = '网络请求失败，请稍后重试'
    uni.showToast({
      title: error.value,
      icon: 'none',
      duration: 2000,
    })
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refreshData = () => {
  getSpendList()
}

onMounted(() => {
  getSpendList()
})
</script>
