<!--
  CalendarV2 专用的交易列表组件

  特殊功能：
  - 自定义 header（Items 数量、Smart 按钮）
  - 与日历视图紧密集成
  - 特定的 UI 风格和交互

  注意：此组件不是通用的 BillListComponent，专为 CalendarV2 视图设计。
  如需通用账单列表功能，请使用 @/components/Bill/BillListComponent.vue
-->
<template>
  <!-- 交易列表 -->
  <div class="transactions">
    <div class="txn-header">
      <h2 class="txn-title">
        交易记录
      </h2>
      <div class="txn-actions">
        <div class="txn-badge badge-success">
          {{ transactionCount }} Items
        </div>
        <button
          class="smart-btn"
          @click="onSmartClick"
        >
          <van-icon name="fire" />
          <span>Smart</span>
        </button>
      </div>
    </div>

    <!-- 交易卡片 -->
    <van-loading
      v-if="transactionsLoading"
      class="txn-loading"
      size="24px"
      vertical
    >
      加载中...
    </van-loading>
    <div
      v-else-if="transactions.length === 0"
      class="txn-empty"
    >
      <div class="empty-icon">
        <van-icon
          name="balance-list-o"
          size="48"
        />
      </div>
      <div class="empty-text">
        当天暂无交易记录
      </div>
      <div class="empty-hint">
        轻松享受无消费的一天 ✨
      </div>
    </div>
    <div
      v-else
      class="txn-list"
    >
      <div
        v-for="txn in transactions"
        :key="txn.id"
        class="txn-card"
        @click="onTransactionClick(txn)"
      >
        <div
          class="txn-icon"
          :style="{ backgroundColor: txn.iconBg }"
        >
          <van-icon
            :name="txn.icon"
            :color="txn.iconColor"
          />
        </div>
        <div class="txn-content">
          <div class="txn-name">
            {{ txn.name }}
          </div>
          <div class="txn-footer">
            <div class="txn-time">
              {{ txn.time }}
            </div>
            <span
              v-if="txn.classify"
              class="txn-classify-tag"
              :class="txn.type === 1 ? 'tag-income' : 'tag-expense'"
            >
              {{ txn.classify }}
            </span>
          </div>
        </div>
        <div class="txn-amount">
          {{ txn.amount }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, watch, ref } from 'vue'
import { getTransactionsByDate } from '@/api/transactionRecord'

const props = defineProps({
  selectedDate: Date
})

const emit = defineEmits(['transactionClick', 'smartClick'])

// 组件内部数据
const transactions = ref([])
const transactionsLoading = ref(false)

// 格式化日期为 key (yyyy-MM-dd)
const formatDateKey = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

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

// 格式化金额
const formatAmount = (amount, type) => {
  const sign = type === 1 ? '+' : '-' // 1=收入, 0=支出
  return `${sign}${amount.toFixed(2)}`
}

// 根据分类获取图标
const getIconByClassify = (classify) => {
  const iconMap = {
    餐饮: 'food',
    购物: 'shopping',
    交通: 'transport',
    娱乐: 'play',
    医疗: 'medical',
    工资: 'money',
    红包: 'red-packet'
  }
  return iconMap[classify] || 'star'
}

// 根据类型获取颜色
const getColorByType = (type) => {
  return type === 1 ? '#22C55E' : '#FF6B6B' // 收入绿色，支出红色
}

// 获取选中日期的交易列表
const fetchDayTransactions = async (date) => {
  try {
    transactionsLoading.value = true
    const dateKey = formatDateKey(date)
    const response = await getTransactionsByDate(dateKey)

    if (response.success && response.data) {
      // 转换为界面需要的格式
      transactions.value = response.data.map((txn) => ({
        id: txn.id,
        name: txn.reason || '未知交易',
        time: formatTime(txn.occurredAt),
        amount: formatAmount(txn.amount, txn.type),
        icon: getIconByClassify(txn.classify),
        iconColor: getColorByType(txn.type),
        iconBg: '#FFFFFF',
        classify: txn.classify,
        type: txn.type
      }))
    }
  } catch (error) {
    console.error('获取交易记录失败:', error)
  } finally {
    transactionsLoading.value = false
  }
}

// 监听 selectedDate 变化，重新加载数据
watch(
  () => props.selectedDate,
  async (newDate) => {
    if (newDate) {
      await fetchDayTransactions(newDate)
    }
  },
  { immediate: true }
)

// 交易数量
const transactionCount = computed(() => transactions.value.length)

// 点击交易卡片
const onTransactionClick = (txn) => {
  emit('transactionClick', txn)
}

// 点击 Smart 按钮
const onSmartClick = () => {
  emit('smartClick')
}
</script>

<style scoped>
@import '@/assets/theme.css';

/* ========== 交易列表 ========== */
.transactions {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-lg);
  padding: var(--spacing-3xl);
  padding-top: 0;
}

.txn-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.txn-title {
  font-family: var(--font-display);
  font-size: var(--font-xl);
  font-weight: var(--font-bold);
  color: var(--text-primary);
  margin: 0;
}

.txn-actions {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

.txn-badge {
  padding: 6px 12px;
  font-size: var(--font-base);
  font-weight: var(--font-semibold);
  border-radius: var(--radius-sm);
}

.badge-success {
  background-color: var(--accent-success-bg);
  color: var(--accent-success);
}

.smart-btn {
  display: flex;
  align-items: center;
  margin-left: 6px;
  gap: 6px;
  padding: 6px 12px;
  background-color: var(--accent-info-bg);
  color: var(--accent-info);
  border: none;
  border-radius: var(--radius-sm);
  font-size: var(--font-base);
  font-weight: var(--font-semibold);
  cursor: pointer;
  transition: opacity 0.2s;
}

.smart-btn:active {
  opacity: 0.7;
}

.txn-loading {
  padding: var(--spacing-3xl);
  text-align: center;
}

.txn-list {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-lg);
}

.txn-card {
  display: flex;
  align-items: center;
  gap: 14px;
  margin-top: 10px;
  padding: var(--spacing-xl);
  background-color: var(--bg-secondary);
  border-radius: var(--radius-md);
  cursor: pointer;
  transition: opacity 0.2s;
}

.txn-card:active {
  opacity: 0.7;
}

.txn-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 44px;
  height: 44px;
  border-radius: var(--radius-full);
  flex-shrink: 0;
}

.txn-content {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
  flex: 1;
  min-width: 0;
}

.txn-name {
  font-size: var(--font-lg);
  font-weight: var(--font-semibold);
  color: var(--text-primary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.txn-footer {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

.txn-time {
  font-size: var(--font-md);
  font-weight: var(--font-medium);
  color: var(--text-tertiary);
}

.txn-classify-tag {
  padding: 2px 8px;
  font-size: var(--font-xs);
  font-weight: var(--font-medium);
  border-radius: var(--radius-full);
  flex-shrink: 0;
}

.txn-classify-tag.tag-income {
  background-color: rgba(34, 197, 94, 0.15);
  color: var(--accent-success);
}

.txn-classify-tag.tag-expense {
  background-color: rgba(59, 130, 246, 0.15);
  color: #3b82f6;
}

.txn-amount {
  font-size: var(--font-lg);
  font-weight: var(--font-bold);
  color: var(--text-primary);
  flex-shrink: 0;
  margin-left: var(--spacing-md);
}

/* ========== 空状态 ========== */
.txn-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 200px;
  padding: var(--spacing-4xl) var(--spacing-2xl);
  gap: var(--spacing-md);
}

.empty-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 80px;
  border-radius: var(--radius-full);
  background: linear-gradient(135deg, var(--bg-tertiary) 0%, var(--bg-secondary) 100%);
  color: var(--text-tertiary);
  margin-bottom: var(--spacing-sm);
}

.empty-text {
  font-size: var(--font-lg);
  font-weight: var(--font-semibold);
  color: var(--text-secondary);
}

.empty-hint {
  font-size: var(--font-md);
  font-weight: var(--font-medium);
  color: var(--text-tertiary);
  opacity: 0.8;
}
</style>
