<template>
  <van-popup
    v-model:show="visible"
    position="bottom"
    :style="{ height: '80%' }"
    round
    closeable
  >
    <div class="popup-wrapper">
      <!-- 头部 -->
      <div class="popup-header">
        <h2 class="popup-title">
          {{ title }}
        </h2>
        <div
          v-if="total > 0"
          class="popup-subtitle"
        >
          共 {{ total }} 笔交易
        </div>
      </div>

      <!-- 交易列表 -->
      <div class="transactions">
        <!-- 加载状态 -->
        <van-loading
          v-if="loading && transactions.length === 0"
          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>

        <!-- 交易列表 -->
        <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.reason }}
              </div>
              <div class="txn-footer">
                <div class="txn-time">
                  {{ formatDateTime(txn.occurredAt) }}
                </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">
              {{ formatAmount(txn.amount, txn.type) }}
            </div>
          </div>

          <!-- 加载更多 -->
          <div
            v-if="!finished"
            class="load-more"
          >
            <van-loading
              v-if="loading"
              size="20px"
            >
              加载中...
            </van-loading>
            <van-button
              v-else
              type="primary"
              size="small"
              @click="loadMore"
            >
              加载更多
            </van-button>
          </div>

          <!-- 已加载全部 -->
          <div
            v-else
            class="finished-text"
          >
            已加载全部
          </div>
        </div>
      </div>
    </div>
  </van-popup>

  <!-- 交易详情弹窗 -->
  <TransactionDetailSheet
    v-model:show="showDetail"
    :transaction="currentTransaction"
    @save="handleSave"
    @delete="handleDelete"
  />
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { showToast } from 'vant'
import TransactionDetailSheet from '@/components/Transaction/TransactionDetailSheet.vue'
import { getTransactionList } from '@/api/transactionRecord'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  classify: {
    type: String,
    default: ''
  },
  type: {
    type: Number,
    default: 0
  },
  year: {
    type: Number,
    required: true
  },
  month: {
    type: Number,
    required: true
  }
})

const emit = defineEmits(['update:modelValue', 'refresh'])

// 双向绑定
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 标题
const title = computed(() => {
  const classifyText = props.classify || '未分类'
  const typeText = props.type === 0 ? '支出' : props.type === 1 ? '收入' : '不计收支'
  return `${classifyText} - ${typeText}`
})

// 数据状态
const transactions = ref([])
const loading = ref(false)
const finished = ref(false)
const pageIndex = ref(1)
const pageSize = 20
const total = ref(0)

// 详情弹窗
const showDetail = ref(false)
const currentTransaction = ref(null)

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  const date = new Date(dateTimeStr)
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${month}-${day} ${hours}:${minutes}`
}

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

// 根据分类获取图标
const getIconByClassify = (classify) => {
  const iconMap = {
    '餐饮': 'food',
    '购物': 'shopping',
    '交通': 'logistics',
    '娱乐': 'play-circle',
    '医疗': 'medic',
    '工资': 'gold-coin',
    '红包': 'gift'
  }
  return iconMap[classify] || 'bill'
}

// 根据类型获取颜色
const getColorByType = (type) => {
  return type === 1 ? '#22C55E' : '#FF6B6B'
}

// 加载数据
const loadData = async (isRefresh = false) => {
  if (loading.value || finished.value) {
    return
  }

  if (isRefresh) {
    pageIndex.value = 1
    transactions.value = []
    finished.value = false
  }

  loading.value = true
  try {
    const params = {
      pageIndex: pageIndex.value,
      pageSize: pageSize,
      type: props.type,
      year: props.year,
      month: props.month || 0,
      sortByAmount: true
    }

    if (props.classify) {
      params.classify = props.classify
    }

    const response = await getTransactionList(params)

    if (response.success) {
      const newList = response.data || []

      // 转换数据格式，添加显示所需的字段
      const formattedList = newList.map(txn => ({
        ...txn,
        icon: getIconByClassify(txn.classify),
        iconColor: getColorByType(txn.type),
        iconBg: '#FFFFFF'
      }))

      transactions.value = [...transactions.value, ...formattedList]
      total.value = response.total

      if (newList.length === 0 || newList.length < pageSize) {
        finished.value = true
      } else {
        pageIndex.value++
      }
    } else {
      showToast(response.message || '加载账单失败')
      finished.value = true
    }
  } catch (error) {
    console.error('加载分类账单失败:', error)
    showToast('加载账单失败')
    finished.value = true
  } finally {
    loading.value = false
  }
}

// 加载更多
const loadMore = () => {
  loadData(false)
}

// 点击交易
const onTransactionClick = (txn) => {
  currentTransaction.value = txn
  showDetail.value = true
}

// 保存交易
const handleSave = () => {
  showDetail.value = false
  // 重新加载数据
  loadData(true)
  // 通知父组件刷新
  emit('refresh')
}

// 删除交易
const handleDelete = (id) => {
  showDetail.value = false
  // 从列表中移除
  transactions.value = transactions.value.filter(t => t.id !== id)
  total.value--
  // 通知父组件刷新
  emit('refresh')
}

// 监听弹窗打开
watch(visible, (newValue) => {
  if (newValue) {
    loadData(true)
  } else {
    // 关闭时重置状态
    transactions.value = []
    pageIndex.value = 1
    finished.value = false
    total.value = 0
  }
})
</script>

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

.popup-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: var(--bg-primary);
}

.popup-header {
  flex-shrink: 0;
  padding: var(--spacing-2xl);
  padding-bottom: var(--spacing-lg);
  border-bottom: 1px solid var(--border-color);
  background: var(--bg-secondary);
}

.popup-title {
  font-family: var(--font-display);
  font-size: var(--font-xl);
  font-weight: var(--font-bold);
  color: var(--text-primary);
  margin: 0;
  text-align: center;
  letter-spacing: -0.02em;
}

.popup-subtitle {
  margin-top: var(--spacing-sm);
  font-size: var(--font-md);
  font-weight: var(--font-medium);
  color: var(--text-secondary);
  text-align: center;
}

.transactions {
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  padding: var(--spacing-lg);
}

.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;
  padding: var(--spacing-xl);
  background-color: var(--bg-secondary);
  border-radius: var(--radius-md);
  cursor: pointer;
  transition: opacity 0.2s;
  margin-top: 10px;
}

.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);
}

.load-more {
  display: flex;
  justify-content: center;
  padding: var(--spacing-xl) 0;
}

.finished-text {
  text-align: center;
  padding: var(--spacing-xl) 0;
  font-size: var(--font-md);
  color: var(--text-tertiary);
}

/* 空状态 */
.txn-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 300px;
  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);
}
</style>
