<template>
  <view class="page-transactions">
    <!-- 导航栏 -->
    <view class="navbar">
      <view class="navbar-left" @tap="goBack">
        <u-icon name="arrow-left" :size="20" color="#1A1A1A" />
      </view>
      <text class="navbar-title">交易流水</text>
      <view class="navbar-right"></view>
    </view>

    <!-- 筛选栏 -->
    <view class="filter-bar">
      <scroll-view scroll-x class="filter-scroll">
        <view class="filter-items">
          <view
            v-for="type in transactionTypes"
            :key="type.value"
            :class="['filter-item', { active: filterType === type.value }]"
            @tap="filterType = type.value; fetchTransactions()"
          >
            <text class="filter-text">{{ type.label }}</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 交易列表 -->
    <scroll-view
      v-if="!loading"
      scroll-y
      class="transactions-list"
      @scrolltolower="loadMore"
    >
      <view v-if="transactions.length > 0" class="list-content">
        <view
          v-for="item in transactions"
          :key="item.id"
          class="transaction-item"
        >
          <view class="item-left">
            <view class="item-icon" :class="getDirectionClass(item.direction)">
              <u-icon :name="getDirectionIcon(item.direction)" :size="20" color="#ffffff" />
            </view>
            <view class="item-info">
              <text class="item-title">{{ item.description || getTypeLabel(item.transactionType) }}</text>
              <text class="item-time">{{ formatTime(item.createdAt) }}</text>
            </view>
          </view>
          <view class="item-right">
            <text :class="['item-amount', getAmountClass(item.direction)]">
              {{ getAmountPrefix(item.direction) }}{{ formatMoney(item.amount) }}
            </text>
            <text class="item-balance">余额: ¥{{ formatMoney(item.balanceAfter) }}</text>
          </view>
        </view>

        <!-- 加载更多 -->
        <view v-if="hasMore" class="load-more">
          <text class="load-more-text">加载更多...</text>
        </view>
        <view v-else-if="transactions.length > 0" class="no-more">
          <text class="no-more-text">没有更多了</text>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-else class="empty-state">
        <view class="empty-icon">
          <u-icon name="file-text" :size="80" color="#D8D8D8" />
        </view>
        <text class="empty-text">暂无交易记录</text>
      </view>
    </scroll-view>

    <!-- 加载状态 -->
    <view v-else class="loading-state">
      <view class="loading-spinner">
        <view class="spinner-dot"></view>
        <view class="spinner-dot"></view>
        <view class="spinner-dot"></view>
      </view>
      <text class="loading-text">加载中...</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { walletApi } from '@/api/user/wallet';

const loading = ref(true);
const transactions = ref<any[]>([]);
const filterType = ref('');
const page = ref(1);
const pageSize = 20;
const hasMore = ref(true);

const transactionTypes = [
  { label: '全部', value: '' },
  { label: '收入', value: 'in' },
  { label: '支出', value: 'out' },
];

onMounted(() => {
  fetchTransactions();
});

async function fetchTransactions(reset = true) {
  if (reset) {
    page.value = 1;
    transactions.value = [];
    hasMore.value = true;
  }

  loading.value = reset;

  try {
    const params: any = {
      page: page.value,
      pageSize,
    };
    if (filterType.value) {
      params.direction = filterType.value;
    }

    const res = await walletApi.getTransactions(params);
    const newData = res.data.items || [];

    if (reset) {
      transactions.value = newData;
    } else {
      transactions.value = [...transactions.value, ...newData];
    }

    hasMore.value = newData.length >= pageSize;
  } catch (e: any) {
    console.error('获取交易流水失败:', e);
    uni.showToast({ title: e.message || '加载失败', icon: 'none' });
  } finally {
    loading.value = false;
  }
}

function loadMore() {
  if (!hasMore.value || loading.value) return;
  page.value++;
  fetchTransactions(false);
}

function getTypeLabel(type: string): string {
  const typeMap: Record<string, string> = {
    invite_cashback: '邀请返现',
    withdrawal: '提现',
    refund: '退款',
  };
  return typeMap[type] || type;
}

function getDirectionIcon(direction: string): string {
  return direction === 'in' ? 'arrow-down-circle' : 'arrow-up-circle';
}

function getDirectionClass(direction: string): string {
  return direction === 'in' ? 'type-income' : 'type-expense';
}

function getAmountClass(direction: string): string {
  return direction === 'in' ? 'amount-income' : 'amount-expense';
}

function getAmountPrefix(direction: string): string {
  return direction === 'in' ? '+' : '-';
}

function formatMoney(value: number | string): string {
  const num = Number(value || 0);
  return num.toFixed(2);
}

function formatTime(time: string): string {
  if (!time) return '';
  const date = new Date(time);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const day = 24 * 60 * 60 * 1000;

  if (diff < day && date.getDate() === now.getDate()) {
    return `今天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  } else if (diff < 2 * day && date.getDate() === now.getDate() - 1) {
    return `昨天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  } else {
    return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  }
}

function goBack() {
  uni.navigateBack();
}
</script>

<style lang="scss" scoped>
.page-transactions {
  min-height: 100vh;
  background: #F5F7FA;
  display: flex;
  flex-direction: column;
}

/* 导航栏 */
.navbar {
  background: #ffffff;
  padding: 0 24rpx;
  border-bottom: 1rpx solid #F0F0F0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
}

.navbar-left,
.navbar-right {
  width: 80rpx;
  display: flex;
  align-items: center;
  padding: 12rpx;
  margin: -12rpx;
  transition: opacity 0.3s ease;

  &:active {
    opacity: 0.6;
  }
}

.navbar-left {
  justify-content: flex-start;
}

.navbar-right {
  justify-content: flex-end;
}

.navbar-title {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  font-weight: 600;
  color: #1A1A1A;
}

/* 筛选栏 */
.filter-bar {
  background: #ffffff;
  border-bottom: 1rpx solid #F0F0F0;
}

.filter-scroll {
  white-space: nowrap;
}

.filter-items {
  display: inline-flex;
  padding: 16rpx 24rpx;
  gap: 16rpx;
}

.filter-item {
  display: inline-block;
  padding: 12rpx 24rpx;
  background: #F5F7FA;
  border-radius: 32rpx;
  transition: all 0.3s ease;

  &.active {
    background: linear-gradient(135deg, #FF8C5A 0%, #FF6B35 100%);
  }

  &:active {
    opacity: 0.7;
  }
}

.filter-text {
  font-size: 26rpx;
  color: #666;
  white-space: nowrap;

  .active & {
    color: #ffffff;
    font-weight: 600;
  }
}

/* 交易列表 */
.transactions-list {
  flex: 1;
  overflow-y: auto;
}

.list-content {
  padding: 16rpx 0;
}

.transaction-item {
  margin: 0 24rpx 16rpx;
  padding: 24rpx;
  background: #ffffff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
  display: flex;
  align-items: center;
  justify-content: space-between;
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.98);
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
  }
}

.item-left {
  display: flex;
  align-items: center;
  gap: 16rpx;
  flex: 1;
}

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

  &.type-income {
    background: linear-gradient(135deg, #52C41A 0%, #389E0D 100%);
  }

  &.type-expense {
    background: linear-gradient(135deg, #FF6B35 0%, #FF4D4F 100%);
  }
}

.item-info {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
  flex: 1;
}

.item-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #1A1A1A;
}

.item-time {
  font-size: 24rpx;
  color: #999;
}

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

.item-amount {
  font-size: 32rpx;
  font-weight: 700;

  &.amount-income {
    color: #52C41A;
  }

  &.amount-expense {
    color: #FF4D4F;
  }
}

.item-balance {
  font-size: 24rpx;
  color: #999;
}

/* 加载更多 */
.load-more,
.no-more {
  padding: 32rpx;
  text-align: center;
}

.load-more-text,
.no-more-text {
  font-size: 24rpx;
  color: #999;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
  gap: 24rpx;
}

.empty-icon {
  opacity: 0.3;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

/* 加载状态 */
.loading-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 16rpx;
  padding: 120rpx 0;
}

.loading-spinner {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.spinner-dot {
  width: 12rpx;
  height: 12rpx;
  background: #FF6B35;
  border-radius: 50%;
  animation: bounce 1.4s infinite ease-in-out both;

  &:nth-child(1) {
    animation-delay: -0.32s;
  }

  &:nth-child(2) {
    animation-delay: -0.16s;
  }
}

@keyframes bounce {
  0%, 80%, 100% {
    transform: scale(0.6);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.loading-text {
  font-size: 24rpx;
  color: #999;
}
</style>
