<template>
  <div class="seller-records gradient-background-circles">
    <MobileHeader title="Seller records" />

    <div class="content">
      <div v-if="loading" class="loading-state">
        <div class="loading-spinner"></div>
        <p>Loading records...</p>
      </div>

      <div v-else class="records-list">
        <div 
          v-for="record in records" 
          :key="record.id"
          class="record-item"
        >
          <div class="record-info">
            <div class="user-avatar">
              <span>{{ record.userName.charAt(0) }}</span>
            </div>
            <div class="record-details">
              <h4>{{ record.userName }}</h4>
              <p>ID: {{ record.userId }}</p>
              <div class="record-time">{{ record.time }}</div>
            </div>
          </div>
          <div class="record-amount">
            <span :class="['coins-amount', record.type === 0 ? 'positive' : 'negative']">{{ record.amount }} coins</span>
            <span class="transaction-type">{{ getTransactionType(record.type, record.origin) }}</span>
          </div>
        </div>
      </div>

      <div v-if="!loading && records.length === 0" class="empty-state">
        <div class="empty-icon">📋</div>
        <p>No records found</p>
        <span>No selling records yet</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import MobileHeader from '../components/MobileHeader.vue'
import { getFreightWaterFlow, getTeamEntry } from '../api/wallet.js'

const router = useRouter()
const loading = ref(false)
const records = ref([])
const currentUserId = ref(null)

// 模拟记录数据
const mockRecords = [
  {
    id: 1,
    userName: 'User1033...',
    userId: '452319866',
    amount: '-10000',
    time: '2025.08.01 10:59:59'
  },
  {
    id: 2,
    userName: 'User1033...',
    userId: '452319866', 
    amount: '-10000',
    time: '2025.08.01 10:59:59'
  },
  {
    id: 3,
    userName: 'User1033...',
    userId: '452319866',
    amount: '-10000',
    time: '2025.08.01 10:59:59'
  }
]

// 获取当前用户ID
const fetchCurrentUserId = async () => {
  try {
    const response = await getTeamEntry()
    if (response && response.status && response.body && response.body.memberProfile) {
      currentUserId.value = response.body.memberProfile.id
      return response.body.memberProfile.id
    }
  } catch (error) {
    console.error('获取用户ID失败:', error)
  }
  return null
}

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  const year = date.getFullYear()
  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')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  
  return `${year}.${month}.${day} ${hours}:${minutes}:${seconds}`
}

// 获取交易类型显示
const getTransactionType = (type, origin) => {
  if (type === 0) {
    return '进货' // 入账
  } else if (type === 1) {
    return '出货' // 出账
  }
  return origin || '未知'
}

// 获取金额显示
const getAmountDisplay = (type, quantity) => {
  const prefix = type === 0 ? '+' : '-'
  return `${prefix}${quantity}`
}

// 获取记录
const fetchRecords = async () => {
  loading.value = true
  
  try {
    // 先获取用户ID
    const userId = currentUserId.value || await fetchCurrentUserId()
    
    if (!userId) {
      console.error('无法获取用户ID')
      records.value = []
      return
    }
    
    const response = await getFreightWaterFlow(userId)
    
    if (response && response.status && response.body) {
      // 处理返回的数据
      records.value = response.body.map(item => ({
        id: item.id,
        userId: item.acceptUserId,
        userName: `User${item.acceptUserId.toString().slice(-6)}...`, // 显示最后6位
        amount: getAmountDisplay(item.type, item.quantity),
        time: formatTime(item.createTime),
        type: item.type,
        quantity: item.quantity,
        balance: item.balance,
        origin: item.origin,
        remark: item.remark,
        rechargeType: item.rechargeType
      }))
    } else {
      records.value = []
    }
  } catch (error) {
    console.error('获取记录失败:', error)
    records.value = []
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  await fetchRecords()
})
</script>

<style scoped>
.seller-records {
  font-family: -apple-system, BlinkMacSystemFont, sans-serif;
}

.content {
  padding: 16px;
  position: relative;
  z-index: 2;
}

/* 加载状态 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #666;
}

.loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #F59E0B;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-state p {
  margin: 0;
  font-size: 14px;
}

/* 记录列表 */
.records-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.record-item {
  background-color: white;
  padding: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.record-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.user-avatar {
  width: 50px;
  height: 50px;
  border-radius: 25px;
  background-color: #9CA3AF;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 18px;
  font-weight: 600;
  margin-right: 12px;
}

.record-details {
  flex: 1;
}

.record-details h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.record-details p {
  margin: 0 0 4px 0;
  font-size: 14px;
  color: #666;
}

.record-time {
  font-size: 12px;
  color: #9ca3af;
}

.record-amount {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.coins-amount {
  font-size: 14px;
  font-weight: 600;
}

.coins-amount.positive {
  color: #10B981; /* 绿色表示进货/入账 */
}

.coins-amount.negative {
  color: #EF4444; /* 红色表示出货/出账 */
}

.transaction-type {
  font-size: 12px;
  color: #9ca3af;
  margin-top: 2px;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #666;
  text-align: center;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-state p {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 500;
}

.empty-state span {
  font-size: 14px;
  color: #9ca3af;
}
</style>
