<script setup>
definePage({
  layout: 'PageLayout',
  style: {
    navigationBarTitleText: '提现记录',
    navigationStyle: 'default',
  },
})

import { ref, onMounted } from 'vue'
import { storeToRefs } from 'pinia'
import { useAgentStore } from '@/stores/agentStore'
import { getWithdrawalList } from '@/api/agent'

const agentStore = useAgentStore()
const { isAgent } = storeToRefs(agentStore)

// 状态映射：1=待审核，2=审核通过，3=审核拒绝，4=提现中，5=提现成功，6=提现失败
const statusConfig = {
  1: { chinese: '待审核', color: { bg: 'bg-yellow-100', text: 'text-yellow-800', dot: 'bg-yellow-500', amount: 'text-yellow-500' } },
  2: { chinese: '审核通过', color: { bg: 'bg-blue-100', text: 'text-blue-800', dot: 'bg-blue-500', amount: 'text-blue-500' } },
  3: { chinese: '审核拒绝', color: { bg: 'bg-red-100', text: 'text-red-800', dot: 'bg-red-500', amount: 'text-red-500' } },
  4: { chinese: '提现中', color: { bg: 'bg-purple-100', text: 'text-purple-800', dot: 'bg-purple-500', amount: 'text-purple-500' } },
  5: { chinese: '提现成功', color: { bg: 'bg-green-100', text: 'text-green-800', dot: 'bg-green-500', amount: 'text-green-500' } },
  6: { chinese: '提现失败', color: { bg: 'bg-red-100', text: 'text-red-800', dot: 'bg-red-500', amount: 'text-red-500' } },
}

const list = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const hasMore = ref(true)

function maskName(name) {
  if (!name || typeof name !== 'string') return ''
  if (name.length <= 7) return name
  return name.substring(0, 3) + '****' + name.substring(7)
}

function statusToChinese(status) {
  return statusConfig[status]?.chinese || '未知状态'
}

function getStatusStyle(status) {
  const config = statusConfig[status] || {}
  return `${config.color?.bg || 'bg-gray-100'} ${config.color?.text || 'text-gray-800'}`
}

function getDotColor(status) {
  return statusConfig[status]?.color?.dot || 'bg-gray-500'
}

function getAmountColor(status) {
  return statusConfig[status]?.color?.amount || 'text-gray-500'
}

async function loadList(isRefresh = false) {
  if (!isAgent.value) return
  if (loading.value) return
  const nextPage = isRefresh ? 1 : page.value
  if (!isRefresh && !hasMore.value) return
  loading.value = true
  try {
    const { data, error } = await getWithdrawalList({ page: nextPage, page_size: pageSize.value })
    if (data.value?.code === 200 && !error.value) {
      const res = data.value.data
      total.value = res?.total ?? 0
      const items = res?.list || []
      if (nextPage === 1) {
        list.value = items
        page.value = 1
      } else {
        list.value = list.value.concat(items)
      }
      page.value = nextPage
      hasMore.value = list.value.length < total.value
    } else {
      hasMore.value = false
    }
  } catch (e) {
    hasMore.value = false
    console.error(e)
  } finally {
    loading.value = false
  }
}

function loadMore() {
  if (!hasMore.value || loading.value) return
  page.value += 1
  loadList(false)
}

onMounted(() => {
  if (isAgent.value) loadList(true)
})
</script>

<template>
  <view class="min-h-screen bg-gray-50 p-4">
    <view v-if="!isAgent" class="rounded-xl bg-white shadow p-6 text-center">
      <view class="text-gray-500 text-sm">请先注册成为代理</view>
    </view>
    <template v-else>
      <view v-if="loading && list.length === 0" class="rounded-xl bg-white shadow p-6">
        <wd-skeleton :row="4" />
      </view>
      <view v-else-if="list.length === 0" class="rounded-xl bg-white shadow p-8 text-center text-gray-500 text-sm">
        暂无提现记录
      </view>
      <view v-else class="space-y-3">
        <view
          v-for="(item, index) in list"
          :key="item.id || index"
          class="bg-white rounded-xl p-4 shadow-sm"
        >
          <view class="flex justify-between items-center mb-2">
            <text class="text-gray-500 text-sm">{{ item.create_time || '—' }}</text>
            <text class="font-bold" :class="getAmountColor(item.status)">{{ (item.amount || 0).toFixed(2) }}元</text>
          </view>
          <view class="flex items-center mb-2">
            <view
              class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium"
              :class="getStatusStyle(item.status)"
            >
              <view class="w-2 h-2 rounded-full mr-1" :class="getDotColor(item.status)" />
              <text>{{ statusToChinese(item.status) }}</text>
            </view>
          </view>
          <view class="text-xs text-gray-500 space-y-1">
            <view v-if="item.payee_account">收款账户：{{ maskName(item.payee_account) }}</view>
            <view v-if="item.payee_name">收款人：{{ item.payee_name }}</view>
            <view v-if="item.tax_amount > 0">税费：-¥{{ (item.tax_amount || 0).toFixed(2) }}</view>
            <view v-if="item.actual_amount > 0" class="text-green-600 font-medium">实际到账：¥{{ (item.actual_amount || 0).toFixed(2) }}</view>
            <view v-if="item.withdrawal_no">提现单号：{{ item.withdrawal_no }}</view>
            <view v-if="item.remark">备注：{{ item.remark }}</view>
          </view>
        </view>
      </view>
      <view v-if="loading && list.length > 0" class="py-4 text-center text-gray-400 text-sm">加载中…</view>
      <view v-else-if="hasMore && list.length > 0" class="py-4 text-center text-blue-500 text-sm" @click="loadMore">加载更多</view>
      <view v-else-if="list.length > 0" class="py-4 text-center text-gray-400 text-sm">没有更多了</view>
    </template>
  </view>
</template>
