<template>
  <scroll-view class="balance-page" scroll-y>
    <view class="balance-header">
      <view class="balance-info">
        <text class="balance-label">账户余额（元）</text>
        <text class="balance-value">{{ balance }}</text>
      </view>
      <view class="balance-tips">
        <text class="tips-text">余额来源于免单奖励，请联系商家微信提现</text>
      </view>
    </view>

    <view class="stats-section">
      <view class="stat-item">
        <text class="stat-value">{{ totalEarned }}</text>
        <text class="stat-label">累计获得</text>
      </view>
      <view class="stat-divider"></view>
      <view class="stat-item">
        <text class="stat-value">{{ totalWithdrawn }}</text>
        <text class="stat-label">已提现</text>
      </view>
    </view>

    <view class="records-section">
      <view class="section-header">
        <text class="section-title">余额明细</text>
      </view>

      <view v-if="loading" class="loading-state">
        <text class="loading-text">加载中...</text>
      </view>

      <view v-else-if="records.length === 0" class="empty-state">
        <text class="empty-text">暂无余额记录</text>
      </view>

      <view v-else class="record-list">
        <view class="record-item" v-for="record in records" :key="record.id">
          <view class="record-left">
            <text class="record-type">{{ getTypeText(record.type) }}</text>
            <text class="record-time">{{ formatTime(record.created_at) }}</text>
          </view>
          <view class="record-right">
            <text class="record-amount" :class="record.amount > 0 ? 'positive' : 'negative'">
              {{ record.amount > 0 ? '+' : '' }}{{ record.amount }}
            </text>
            <text class="record-balance">余额: {{ record.balance_after }}</text>
          </view>
        </view>
      </view>
    </view>

    <view class="withdraw-section">
      <button class="withdraw-btn" @click="showWithdrawTips">
        <text class="btn-text">申请提现</text>
      </button>
      <text class="withdraw-tip">提现请联系商家微信处理</text>
    </view>
  </scroll-view>
</template>

<script setup lang="uts">
import { ref, onMounted } from 'vue'
import { supabaseService } from '@/utils/supabaseService.uts'

type BalanceRecord = {
  id: string
  type: string
  amount: number
  balance_before: number
  balance_after: number
  description: string | null
  created_at: string
}

const balance = ref<number>(0)
const totalEarned = ref<number>(0)
const totalWithdrawn = ref<number>(0)
const records = ref<BalanceRecord[]>([])
const loading = ref<boolean>(true)

const loadBalance = async (): Promise<void> => {
  try {
    const result = await supabaseService.getUserBalance()
    balance.value = result.getNumber('balance') ?? 0
    totalEarned.value = result.getNumber('total_earned') ?? 0
    totalWithdrawn.value = result.getNumber('total_withdrawn') ?? 0
  } catch (e) {
    console.error('加载余额失败:', e)
  }
}

const loadRecords = async (): Promise<void> => {
  loading.value = true
  try {
    const result = await supabaseService.getBalanceRecords(1, 50)
    const parsed: BalanceRecord[] = []
    
    for (let i = 0; i < result.length; i++) {
      const item = result[i]
      
      let id = ''
      let type = ''
      let amount = 0
      let balanceBefore = 0
      let balanceAfter = 0
      let description: string | null = null
      let createdAt = ''
      
      let itemObj: UTSJSONObject | null = null
      if (item instanceof UTSJSONObject) {
        itemObj = item
      } else {
        itemObj = JSON.parse(JSON.stringify(item)) as UTSJSONObject
      }
      
      id = itemObj.getString('id') ?? ''
      type = itemObj.getString('type') ?? ''
      amount = itemObj.getNumber('amount') ?? 0
      balanceBefore = itemObj.getNumber('balance_before') ?? 0
      balanceAfter = itemObj.getNumber('balance_after') ?? 0
      description = itemObj.getString('description')
      createdAt = itemObj.getString('created_at') ?? ''
      
      parsed.push({
        id,
        type,
        amount,
        balance_before: balanceBefore,
        balance_after: balanceAfter,
        description,
        created_at: createdAt
      })
    }
    
    records.value = parsed
  } catch (e) {
    console.error('加载余额记录失败:', e)
  } finally {
    loading.value = false
  }
}

const loadData = async (): Promise<void> => {
  await Promise.all([
    loadBalance(),
    loadRecords()
  ])
}

const getTypeText = (type: string): string => {
  if (type === 'free_order') return '免单奖励'
  if (type === 'rebate') return '返利'
  if (type === 'withdraw') return '提现'
  if (type === 'clear') return '余额清零'
  if (type === 'manual') return '手动调整'
  return '余额变动'
}

const formatTime = (timeStr: string): string => {
  if (timeStr === '') return ''
  const date = new Date(timeStr)
  const y = date.getFullYear()
  const m = (date.getMonth() + 1).toString().padStart(2, '0')
  const d = date.getDate().toString().padStart(2, '0')
  const hh = date.getHours().toString().padStart(2, '0')
  const mm = date.getMinutes().toString().padStart(2, '0')
  return `${y}-${m}-${d} ${hh}:${mm}`
}

const showWithdrawTips = (): void => {
  uni.showModal({
    title: '提现说明',
    content: '请添加商家微信进行提现处理，商家确认后将通过微信转账给您。',
    showCancel: false,
    confirmText: '我知道了'
  })
}

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

<style>
.balance-page {
  flex: 1;
  height: 100%;
  background-color: #f5f5f5;
}

.balance-header {
  background: linear-gradient(135deg, #ff6b35 0%, #ff8c42 100%);
  padding: 30px 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.balance-info {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.balance-label {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 8px;
}

.balance-value {
  font-size: 42px;
  font-weight: bold;
  color: white;
}

.balance-tips {
  margin-top: 16px;
  padding: 8px 16px;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 16px;
}

.tips-text {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.9);
}

.stats-section {
  display: flex;
  flex-direction: row;
  background-color: white;
  padding: 20px 0;
  margin-bottom: 8px;
}

.stat-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.stat-label {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.stat-divider {
  width: 1px;
  height: 40px;
  background-color: #f0f0f0;
}

.records-section {
  background-color: white;
  padding: 0 16px;
  min-height: 200px;
}

.section-header {
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.loading-state {
  padding: 40px 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-text {
  font-size: 14px;
  color: #999;
}

.empty-state {
  padding: 40px 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-text {
  font-size: 14px;
  color: #999;
}

.record-list {
  display: flex;
  flex-direction: column;
}

.record-item {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding: 16px 0;
  border-bottom: 1px solid #f9f9f9;
}

.record-left {
  display: flex;
  flex-direction: column;
}

.record-type {
  font-size: 15px;
  color: #333;
  margin-bottom: 4px;
}

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

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

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

.record-amount.positive {
  color: #ff6b35;
}

.record-amount.negative {
  color: #333;
}

.record-balance {
  font-size: 12px;
  color: #999;
}

.withdraw-section {
  padding: 20px 16px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.withdraw-btn {
  width: 100%;
  height: 44px;
  background: linear-gradient(135deg, #ff6b35 0%, #ff8c42 100%);
  border-radius: 22px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-text {
  font-size: 16px;
  font-weight: bold;
  color: white;
}

.withdraw-tip {
  font-size: 12px;
  color: #999;
  margin-top: 12px;
}
</style>
