<template>
  <div
    class="lucid-glass-bar flex h-full w-full flex-col rounded-4xl! border-1 border-white px-6 py-7"
  >
    <div class="mb-[10px] flex justify-between border-b-1 border-dashed pb-4">
      <div>
        <div class="mb-1 text-base font-bold text-white">本月销售数据</div>
        <div class="text-sm text-white/40">本月已成交{{ salesPage.total }}单</div>
      </div>
      <Button
        variant="link"
        class="h-auto p-0 text-sm font-medium text-white/60 underline hover:text-white"
        @click="$emit('show-history')"
      >
        历史数据
      </Button>
    </div>

    <div class="flex-1 overflow-y-auto pr-1">
      <div v-if="loading" class="flex h-[100px] items-center justify-center">
        <div
          class="h-6 w-6 animate-spin rounded-full border-2 border-[#ADFF5B] border-t-transparent"
        ></div>
      </div>
      <div v-else class="">
        <div
          v-for="(item, index) in salesPage.list"
          :key="index"
          class="mb-3 flex items-center justify-between last:mb-0"
        >
          <div class="flex flex-col">
            <span class="text-sm font-semibold text-white">{{ item.user_hash }}</span>
            <span class="text-[10px] text-white/40">{{ formatTime(item.updated_at) }}</span>
          </div>
          <div class="text-lg font-bold text-white tabular-nums">$ {{ item.amount }}</div>
        </div>
        <div v-if="!salesPage.list.length">暂无数据</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Button } from '@/components/ui/button'
import request from '@/utils/request'

defineEmits(['show-history'])

const salesPage = ref({
  total: 0,
  list: [] as any[],
})

const loading = ref(false)

async function fetchSales() {
  loading.value = true
  try {
    const now = new Date()
    // 2. 获取当月 1 号 0 点 0 分 0 秒
    const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1, 0, 0, 0)
    const start_time = Math.floor(startOfMonth.getTime() / 1000)

    // 3. 获取下个月的第 0 天（即本月的最后一天）的 23:59:59
    const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59)
    const end_time = Math.floor(endOfMonth.getTime() / 1000)
    const res: any = await request.get('/api/v1/public/user/invite/sales', {
      page: 1,
      size: 3,
      start_time,
      end_time,
    })
    salesPage.value = res
  } catch (error) {
    console.error('Fetch sales error:', error)
  } finally {
    loading.value = false
  }
}

function formatTime(timestamp: number) {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: 'numeric',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
    hour12: false,
  }).format(date)
}

onMounted(() => {
  fetchSales()
})
</script>
