<template>
  <div class="transaction-list-container transaction-list">
    <van-list
      :loading="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <van-cell-group
        v-if="transactions && transactions.length"
        inset
        style="margin-top: 10px"
      >
        <van-swipe-cell
          v-for="transaction in transactions"
          :key="transaction.id"
          class="transaction-item"
        >
          <div class="transaction-row">
            <van-checkbox
              v-if="showCheckbox"
              :model-value="isSelected(transaction.id)"
              class="checkbox-col"
              @update:model-value="toggleSelection(transaction)"
            />
            <div
              class="transaction-card"
              @click="handleClick(transaction)"
            >
              <div class="card-left">
                <div class="transaction-title">
                  <span class="reason">{{ transaction.reason || '(无摘要)' }}</span>
                </div>
                <div class="transaction-info">
                  <div>交易时间: {{ formatDate(transaction.occurredAt) }}</div>
                  <div>
                    <span v-if="transaction.classify"> 分类: {{ transaction.classify }} </span>
                    <span
                      v-if="
                        transaction.upsetedClassify &&
                          transaction.upsetedClassify !== transaction.classify
                      "
                      style="color: var(--van-warning-color)"
                    >
                      → {{ transaction.upsetedClassify }}
                    </span>
                  </div>
                  <div v-if="transaction.importFrom">
                    来源: {{ transaction.importFrom }}
                  </div>
                </div>
              </div>
              <div class="card-middle">
                <van-tag
                  :type="getTypeTagType(transaction.type)"
                  size="medium"
                >
                  {{ getTypeName(transaction.type) }}
                </van-tag>
                <template
                  v-if="
                    Number.isFinite(transaction.upsetedType) &&
                      transaction.upsetedType !== transaction.type
                  "
                >
                  →
                  <van-tag
                    :type="getTypeTagType(transaction.upsetedType)"
                    size="medium"
                  >
                    {{ getTypeName(transaction.upsetedType) }}
                  </van-tag>
                </template>
              </div>
              <div class="card-right">
                <div class="transaction-amount">
                  <div :class="['amount', getAmountClass(transaction.type)]">
                    {{ formatAmount(transaction.amount, transaction.type) }}
                  </div>
                  <div
                    v-if="transaction.balance && transaction.balance > 0"
                    class="balance"
                  >
                    余额: {{ formatMoney(transaction.balance) }}
                  </div>
                </div>
                <van-icon
                  name="arrow"
                  size="16"
                  color="var(--van-gray-5)"
                />
              </div>
            </div>
          </div>
          <template
            v-if="showDelete"
            #right
          >
            <van-button
              square
              type="danger"
              text="删除"
              class="delete-button"
              @click="handleDeleteClick(transaction)"
            />
          </template>
        </van-swipe-cell>
      </van-cell-group>

      <van-empty
        v-if="!loading && !(transactions && transactions.length)"
        description="暂无交易记录"
      />
    </van-list>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { showConfirmDialog, showToast } from 'vant'
import { deleteTransaction } from '@/api/transactionRecord'

import { defineEmits } from 'vue'

const props = defineProps({
  transactions: {
    type: Array,
    default: () => []
  },
  loading: {
    type: Boolean,
    default: false
  },
  finished: {
    type: Boolean,
    default: false
  },
  showDelete: {
    type: Boolean,
    default: true
  },
  showCheckbox: {
    type: Boolean,
    default: false
  },
  selectedIds: {
    type: Set,
    default: () => new Set()
  }
})

const emit = defineEmits(['load', 'click', 'delete', 'update:selectedIds'])

const deletingIds = ref(new Set())

const onLoad = () => {
  emit('load')
}

const handleClick = (transaction) => {
  emit('click', transaction)
}

const handleDeleteClick = async (transaction) => {
  try {
    await showConfirmDialog({
      title: '提示',
      message: '确定要删除这条交易记录吗？'
    })

    deletingIds.value.add(transaction.id)
    const response = await deleteTransaction(transaction.id)
    deletingIds.value.delete(transaction.id)

    if (response && response.success) {
      showToast('删除成功')
      emit('delete', transaction.id)
      try {
        window.dispatchEvent(new CustomEvent('transaction-deleted', { detail: transaction.id }))
      } catch (e) {
        // ignore in non-browser environment
        console.log('非浏览器环境，跳过派发 transaction-deleted 事件', e)
      }
    } else {
      showToast(response.message || '删除失败')
    }
  } catch (err) {
    // 用户取消确认会抛出 'cancel' 或类似错误
    if (err !== 'cancel') {
      console.error('删除出错:', err)
      showToast('删除失败')
    }
  }
}

const isSelected = (id) => {
  return props.selectedIds.has(id)
}

const toggleSelection = (transaction) => {
  const newSelectedIds = new Set(props.selectedIds)
  if (newSelectedIds.has(transaction.id)) {
    newSelectedIds.delete(transaction.id)
  } else {
    newSelectedIds.add(transaction.id)
  }
  emit('update:selectedIds', newSelectedIds)
}

// 获取交易类型名称
const getTypeName = (type) => {
  const typeMap = {
    0: '支出',
    1: '收入',
    2: '不计入收支'
  }
  return typeMap[type] || '未知'
}

// 获取交易类型标签类型
const getTypeTagType = (type) => {
  const typeMap = {
    0: 'danger',
    1: 'success',
    2: 'default'
  }
  return typeMap[type] || 'default'
}

// 获取金额样式类
const getAmountClass = (type) => {
  if (type === 0) {
    return 'expense'
  }
  if (type === 1) {
    return 'income'
  }
  return 'neutral'
}

// 格式化金额（带符号）
const formatAmount = (amount, type) => {
  const formatted = formatMoney(amount)
  if (type === 0) {
    return `- ${formatted}`
  }
  if (type === 1) {
    return `+ ${formatted}`
  }
  return formatted
}

// 格式化金额
const formatMoney = (amount) => {
  return `¥${Number(amount).toFixed(2)}`
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) {
    return ''
  }
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<style scoped>
.transaction-list-container {
  width: 100%;
}

.transaction-row {
  display: flex;
  align-items: center;
  width: 100%;
  overflow: hidden;
}

.checkbox-col {
  padding: 12px 8px;
  flex-shrink: 0;
}

.transaction-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  transition: background-color 0.3s;
  flex: 1;
  min-width: 0;
  overflow: hidden;
  position: relative;
}

.card-left {
  flex: 1;
  min-width: 0;
  padding-right: 12px;
  overflow: hidden;
}

.card-middle {
  position: absolute;
  top: 12px;
  right: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
  z-index: 1;
}

.card-right {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-shrink: 0;
}

.transaction-title {
  font-weight: bold;
  margin-bottom: 8px;
  overflow: hidden;
}

.reason {
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
  min-width: 0;
}

.transaction-info {
  font-size: 12px;
  color: var(--van-text-color-2);
  line-height: 1.6;
}

.original-info {
  color: var(--van-orange);
  font-style: italic;
  display: flex;
  align-items: center;
  gap: 4px;
}

.transaction-amount {
  text-align: right;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  min-width: 90px;
}

.amount {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 4px;
  white-space: nowrap;
}

.amount.expense {
  color: var(--van-danger-color);
}

.amount.income {
  color: var(--van-success-color);
}

.balance {
  font-size: 12px;
  color: var(--van-text-color-2);
  white-space: nowrap;
}

.delete-button {
  height: 100%;
}
</style>
