<script lang="ts" setup>
import { Icon } from '@iconify/vue'
import { toast } from 'vue-sonner'

import type { OrderFund } from '@/services/api/monisuo-admin.api'

import { BasicPage } from '@/components/global-layout'
import { useApproveOrderMutation, useGetAllOrdersQuery, useGetPendingOrdersQuery } from '@/services/api/monisuo-admin.api'

const pageNum = ref(1)
const pageSize = ref(10)
const activeTab = ref('pending')

// 筛选条件
const filterType = ref<number | string>('all')
const filterStatus = ref<number | string>('all')

const { data: pendingData, isLoading: pendingLoading, refetch: refetchPending } = useGetPendingOrdersQuery({
  pageNum: pageNum.value,
  pageSize: pageSize.value,
})

const { data: allData, isLoading: allLoading, refetch: refetchAll } = useGetAllOrdersQuery({
  pageNum: pageNum.value,
  pageSize: pageSize.value,
  type: filterType.value === 'all' ? undefined : filterType.value as number,
  status: filterStatus.value === 'all' ? undefined : filterStatus.value as number,
})

const approveMutation = useApproveOrderMutation()

const pendingOrders = computed(() => pendingData.value?.data?.list || [])
const pendingTotal = computed(() => pendingData.value?.data?.total || 0)
const allOrders = computed(() => allData.value?.data?.list || [])
const allTotal = computed(() => allData.value?.data?.total || 0)

const currentTotal = computed(() => activeTab.value === 'pending' ? pendingTotal.value : allTotal.value)
const totalPages = computed(() => Math.ceil(currentTotal.value / pageSize.value))

const showApproveDialog = ref(false)
const showDetailDialog = ref(false)
const currentOrder = ref<OrderFund | null>(null)
const approveStatus = ref(2)
const rejectReason = ref('')
const adminRemark = ref('')

function viewOrderDetail(order: OrderFund) {
  currentOrder.value = order
  showDetailDialog.value = true
}

function openApproveDialog(order: OrderFund, status: number) {
  currentOrder.value = order
  approveStatus.value = status
  rejectReason.value = ''
  adminRemark.value = ''
  showApproveDialog.value = true
}

async function handleApprove() {
  if (!currentOrder.value)
    return

  const action = approveStatus.value === 2 ? '通过' : '驳回'

  try {
    await approveMutation.mutateAsync({
      orderNo: currentOrder.value.orderNo,
      status: approveStatus.value,
      rejectReason: rejectReason.value || undefined,
      adminRemark: adminRemark.value || undefined,
    })

    toast.success(`订单已${action}`)
    showApproveDialog.value = false
    refetchPending()
    refetchAll()
  }
  catch (e: any) {
    toast.error(e.response?.data?.msg || `${action}失败`)
  }
}

function handlePageChange(page: number) {
  pageNum.value = page
  refetchPending()
  refetchAll()
}

function handlePageSizeChange(size: unknown) {
  if (size === null || size === undefined)
    return
  pageSize.value = Number(size)
  pageNum.value = 1
  refetchPending()
  refetchAll()
}

function resetFilters() {
  filterType.value = 'all'
  filterStatus.value = 'all'
  pageNum.value = 1
  refetchAll()
}

function formatAmount(amount: number): string {
  return amount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

function getStatusVariant(status: number): 'default' | 'secondary' | 'destructive' {
  if (status === 1)
    return 'secondary'
  if (status === 2)
    return 'default'
  return 'destructive'
}

function getStatusText(status: number): string {
  if (status === 1)
    return '待审批'
  if (status === 2)
    return '已通过'
  return '已驳回'
}
</script>

<template>
  <BasicPage title="订单管理" description="审批充提订单">
    <div class="space-y-4">
      <UiTabs v-model="activeTab">
        <UiTabsList>
          <UiTabsTrigger value="pending">
            待审批
            <UiBadge v-if="pendingTotal > 0" variant="destructive" class="ml-2">
              {{ pendingTotal }}
            </UiBadge>
          </UiTabsTrigger>
          <UiTabsTrigger value="all">
            全部订单
          </UiTabsTrigger>
        </UiTabsList>

        <!-- 待审批订单 -->
        <UiTabsContent value="pending" class="space-y-4">
          <!-- PC端表格 -->
          <UiCard class="hidden md:block overflow-x-auto p-4"">
            <UiTable>
              <UiTableHeader>
                <UiTableRow>
                  <UiTableHead>订单号</UiTableHead>
                  <UiTableHead>用户</UiTableHead>
                  <UiTableHead>类型</UiTableHead>
                  <UiTableHead class="text-right">
                    金额
                  </UiTableHead>
                  <UiTableHead class="hidden lg:table-cell">
                    时间
                  </UiTableHead>
                  <UiTableHead class="text-right">
                    操作
                  </UiTableHead>
                </UiTableRow>
              </UiTableHeader>
              <UiTableBody>
                <UiTableRow v-if="pendingLoading">
                  <UiTableCell :col-span="6" class="text-center py-8">
                    <UiSpinner class="mx-auto" />
                  </UiTableCell>
                </UiTableRow>
                <UiTableRow v-else-if="pendingOrders.length === 0">
                  <UiTableCell :col-span="6" class="text-center py-8 text-muted-foreground">
                    <Icon icon="lucide:inbox" class="size-8 mx-auto mb-2 opacity-50" />
                    <p>暂无待审批订单</p>
                  </UiTableCell>
                </UiTableRow>
                <UiTableRow v-for="order in pendingOrders" :key="order.id">
                  <UiTableCell class="font-mono text-xs">
                    {{ order.orderNo }}
                  </UiTableCell>
                  <UiTableCell>{{ order.username }}</UiTableCell>
                  <UiTableCell>
                    <UiBadge :variant="order.type === 1 ? 'default' : 'destructive'">
                      <Icon :icon="order.type === 1 ? 'lucide:arrow-down-left' : 'lucide:arrow-up-right'" class="size-3 mr-1" />
                      {{ order.type === 1 ? '充值' : '提现' }}
                    </UiBadge>
                  </UiTableCell>
                  <UiTableCell class="text-right font-mono font-medium">
                    ¥{{ formatAmount(order.amount) }}
                  </UiTableCell>
                  <UiTableCell class="hidden lg:table-cell text-muted-foreground text-sm">
                    {{ order.createTime }}
                  </UiTableCell>
                  <UiTableCell class="text-right">
                    <div class="flex justify-end gap-1">
                      <UiButton size="sm" variant="ghost" @click="viewOrderDetail(order)">
                        <Icon icon="lucide:eye" class="size-4" />
                      </UiButton>
                      <UiButton
                        size="sm"
                        :disabled="approveMutation.isPending.value"
                        @click="openApproveDialog(order, 2)"
                      >
                        通过
                      </UiButton>
                      <UiButton
                        size="sm"
                        variant="destructive"
                        :disabled="approveMutation.isPending.value"
                        @click="openApproveDialog(order, 3)"
                      >
                        驳回
                      </UiButton>
                    </div>
                  </UiTableCell>
                </UiTableRow>
              </UiTableBody>
            </UiTable>
          </UiCard>

          <!-- 移动端卡片列表 -->
          <div class="md:hidden space-y-3">
            <div v-if="pendingLoading" class="text-center py-8">
              <UiSpinner class="mx-auto" />
            </div>
            <template v-else-if="pendingOrders.length > 0">
              <UiCard v-for="order in pendingOrders" :key="order.id" class="p-4">
                <div class="flex items-start justify-between">
                  <div class="space-y-1">
                    <div class="font-mono text-xs text-muted-foreground">
                      {{ order.orderNo }}
                    </div>
                    <div class="font-medium">
                      {{ order.username }}
                    </div>
                  </div>
                  <UiBadge :variant="order.type === 1 ? 'default' : 'destructive'">
                    {{ order.type === 1 ? '充值' : '提现' }}
                  </UiBadge>
                </div>
                <div class="mt-3 pt-3 border-t">
                  <div class="text-xl font-mono font-bold" :class="order.type === 1 ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400'">
                    {{ order.type === 1 ? '+' : '-' }}¥{{ formatAmount(order.amount) }}
                  </div>
                  <div class="text-sm text-muted-foreground mt-1">
                    {{ order.createTime }}
                  </div>
                </div>
                <div class="mt-3 flex gap-2">
                  <UiButton size="sm" class="flex-1" @click="openApproveDialog(order, 2)">
                    通过
                  </UiButton>
                  <UiButton size="sm" variant="destructive" class="flex-1" @click="openApproveDialog(order, 3)">
                    驳回
                  </UiButton>
                </div>
              </UiCard>
            </template>
            <div v-else class="text-center py-8 text-muted-foreground">
              <Icon icon="lucide:inbox" class="size-8 mx-auto mb-2 opacity-50" />
              <p>暂无待审批订单</p>
            </div>
          </div>
        </UiTabsContent>

        <!-- 全部订单 -->
        <UiTabsContent value="all" class="space-y-4">
          <!-- 筛选条件 -->
          <UiCard class="p-4">
            <div class="flex flex-col sm:flex-row gap-4">
              <div class="w-full sm:w-[140px] grid gap-2">
                <UiLabel>类型</UiLabel>
                <UiSelect v-model="filterType">
                  <UiSelectTrigger>
                    <UiSelectValue placeholder="全部" />
                  </UiSelectTrigger>
                  <UiSelectContent>
                    <UiSelectItem value="all">
                      全部
                    </UiSelectItem>
                    <UiSelectItem :value="1">
                      充值
                    </UiSelectItem>
                    <UiSelectItem :value="2">
                      提现
                    </UiSelectItem>
                  </UiSelectContent>
                </UiSelect>
              </div>
              <div class="w-full sm:w-[140px] grid gap-2">
                <UiLabel>状态</UiLabel>
                <UiSelect v-model="filterStatus">
                  <UiSelectTrigger>
                    <UiSelectValue placeholder="全部" />
                  </UiSelectTrigger>
                  <UiSelectContent>
                    <UiSelectItem value="all">
                      全部
                    </UiSelectItem>
                    <UiSelectItem :value="1">
                      待审批
                    </UiSelectItem>
                    <UiSelectItem :value="2">
                      已通过
                    </UiSelectItem>
                    <UiSelectItem :value="3">
                      已驳回
                    </UiSelectItem>
                  </UiSelectContent>
                </UiSelect>
              </div>
              <div class="flex items-end gap-2">
                <UiButton variant="outline" @click="resetFilters">
                  重置
                </UiButton>
              </div>
            </div>
          </UiCard>

          <!-- PC端表格 -->
          <UiCard class="hidden md:block overflow-x-auto p-4"">
            <UiTable>
              <UiTableHeader>
                <UiTableRow>
                  <UiTableHead>订单号</UiTableHead>
                  <UiTableHead>用户</UiTableHead>
                  <UiTableHead>类型</UiTableHead>
                  <UiTableHead class="text-right">
                    金额
                  </UiTableHead>
                  <UiTableHead>状态</UiTableHead>
                  <UiTableHead class="hidden xl:table-cell">
                    时间
                  </UiTableHead>
                  <UiTableHead class="hidden lg:table-cell">
                    备注
                  </UiTableHead>
                  <UiTableHead class="text-right">
                    操作
                  </UiTableHead>
                </UiTableRow>
              </UiTableHeader>
              <UiTableBody>
                <UiTableRow v-if="allLoading">
                  <UiTableCell :col-span="8" class="text-center py-8">
                    <UiSpinner class="mx-auto" />
                  </UiTableCell>
                </UiTableRow>
                <UiTableRow v-else-if="allOrders.length === 0">
                  <UiTableCell :col-span="8" class="text-center py-8 text-muted-foreground">
                    暂无数据
                  </UiTableCell>
                </UiTableRow>
                <UiTableRow v-for="order in allOrders" :key="order.id">
                  <UiTableCell class="font-mono text-xs">
                    {{ order.orderNo }}
                  </UiTableCell>
                  <UiTableCell>{{ order.username }}</UiTableCell>
                  <UiTableCell>
                    <UiBadge :variant="order.type === 1 ? 'default' : 'destructive'">
                      {{ order.type === 1 ? '充值' : '提现' }}
                    </UiBadge>
                  </UiTableCell>
                  <UiTableCell class="text-right font-mono">
                    ¥{{ formatAmount(order.amount) }}
                  </UiTableCell>
                  <UiTableCell>
                    <UiBadge :variant="getStatusVariant(order.status)">
                      {{ getStatusText(order.status) }}
                    </UiBadge>
                  </UiTableCell>
                  <UiTableCell class="hidden xl:table-cell text-muted-foreground text-sm">
                    {{ order.createTime }}
                  </UiTableCell>
                  <UiTableCell class="hidden lg:table-cell text-sm text-muted-foreground max-w-[150px] truncate">
                    {{ order.rejectReason || order.adminRemark || '-' }}
                  </UiTableCell>
                  <UiTableCell class="text-right">
                    <UiButton size="sm" variant="ghost" @click="viewOrderDetail(order)">
                      <Icon icon="lucide:eye" class="size-4" />
                    </UiButton>
                  </UiTableCell>
                </UiTableRow>
              </UiTableBody>
            </UiTable>
          </UiCard>

          <!-- 移动端卡片列表 -->
          <div class="md:hidden space-y-3">
            <div v-if="allLoading" class="text-center py-8">
              <UiSpinner class="mx-auto" />
            </div>
            <template v-else-if="allOrders.length > 0">
              <UiCard v-for="order in allOrders" :key="order.id" class="p-4">
                <div class="flex items-start justify-between">
                  <div class="space-y-1">
                    <div class="font-mono text-xs text-muted-foreground">
                      {{ order.orderNo }}
                    </div>
                    <div class="font-medium">
                      {{ order.username }}
                    </div>
                  </div>
                  <div class="text-right">
                    <UiBadge :variant="order.type === 1 ? 'default' : 'destructive'" class="mb-1">
                      {{ order.type === 1 ? '充值' : '提现' }}
                    </UiBadge>
                    <UiBadge :variant="getStatusVariant(order.status)" class="block">
                      {{ getStatusText(order.status) }}
                    </UiBadge>
                  </div>
                </div>
                <div class="mt-3 pt-3 border-t">
                  <div class="text-xl font-mono font-bold">
                    ¥{{ formatAmount(order.amount) }}
                  </div>
                  <div class="text-sm text-muted-foreground mt-1">
                    {{ order.createTime }}
                  </div>
                  <div v-if="order.rejectReason || order.adminRemark" class="text-sm text-muted-foreground mt-1">
                    备注: {{ order.rejectReason || order.adminRemark }}
                  </div>
                </div>
                <div class="mt-3">
                  <UiButton size="sm" variant="outline" class="w-full" @click="viewOrderDetail(order)">
                    查看详情
                  </UiButton>
                </div>
              </UiCard>
            </template>
            <div v-else class="text-center py-8 text-muted-foreground">
              暂无数据
            </div>
          </div>
        </UiTabsContent>
      </UiTabs>

      <!-- 分页 -->
      <div v-if="currentTotal > 0" class="flex flex-col sm:flex-row items-center justify-between gap-4 px-2">
        <div class="text-sm text-muted-foreground">
          共 {{ currentTotal }} 条记录
        </div>
        <div class="flex items-center gap-4">
          <div class="flex items-center gap-2">
            <span class="text-sm">每页</span>
            <UiSelect :model-value="`${pageSize}`" @update:model-value="handlePageSizeChange">
              <UiSelectTrigger class="h-8 w-[70px]">
                <UiSelectValue />
              </UiSelectTrigger>
              <UiSelectContent>
                <UiSelectItem value="10">
                  10
                </UiSelectItem>
                <UiSelectItem value="20">
                  20
                </UiSelectItem>
                <UiSelectItem value="50">
                  50
                </UiSelectItem>
              </UiSelectContent>
            </UiSelect>
            <span class="text-sm">条</span>
          </div>
          <div class="flex items-center gap-2">
            <UiButton
              variant="outline"
              size="icon"
              class="h-8 w-8"
              :disabled="pageNum <= 1"
              @click="handlePageChange(pageNum - 1)"
            >
              <Icon icon="lucide:chevron-left" class="size-4" />
            </UiButton>
            <span class="text-sm min-w-[80px] text-center">
              {{ pageNum }} / {{ totalPages }}
            </span>
            <UiButton
              variant="outline"
              size="icon"
              class="h-8 w-8"
              :disabled="pageNum >= totalPages"
              @click="handlePageChange(pageNum + 1)"
            >
              <Icon icon="lucide:chevron-right" class="size-4" />
            </UiButton>
          </div>
        </div>
      </div>
    </div>

    <!-- 订单详情弹窗 -->
    <UiDialog v-model:open="showDetailDialog">
      <UiDialogContent class="max-w-md">
        <UiDialogHeader>
          <UiDialogTitle>订单详情</UiDialogTitle>
        </UiDialogHeader>
        <div v-if="currentOrder" class="space-y-4">
          <div class="grid grid-cols-3 gap-2 text-sm">
            <div class="text-muted-foreground">
              订单号
            </div>
            <div class="col-span-2 font-mono">
              {{ currentOrder.orderNo }}
            </div>

            <div class="text-muted-foreground">
              用户
            </div>
            <div class="col-span-2 font-medium">
              {{ currentOrder.username }}
            </div>

            <div class="text-muted-foreground">
              类型
            </div>
            <div class="col-span-2">
              <UiBadge :variant="currentOrder.type === 1 ? 'default' : 'destructive'">
                {{ currentOrder.type === 1 ? '充值' : '提现' }}
              </UiBadge>
            </div>

            <div class="text-muted-foreground">
              金额
            </div>
            <div class="col-span-2 font-mono font-bold text-lg">
              ¥{{ formatAmount(currentOrder.amount) }}
            </div>

            <div class="text-muted-foreground">
              状态
            </div>
            <div class="col-span-2">
              <UiBadge :variant="getStatusVariant(currentOrder.status)">
                {{ getStatusText(currentOrder.status) }}
              </UiBadge>
            </div>

            <div class="text-muted-foreground">
              创建时间
            </div>
            <div class="col-span-2">
              {{ currentOrder.createTime }}
            </div>

            <template v-if="currentOrder.rejectReason">
              <div class="text-muted-foreground text-red-500">
                驳回原因
              </div>
              <div class="col-span-2 text-red-500">
                {{ currentOrder.rejectReason }}
              </div>
            </template>

            <template v-if="currentOrder.adminRemark">
              <div class="text-muted-foreground">
                管理员备注
              </div>
              <div class="col-span-2">
                {{ currentOrder.adminRemark }}
              </div>
            </template>
          </div>
        </div>
        <UiDialogFooter>
          <template v-if="currentOrder?.status === 1">
            <UiButton variant="outline" @click="showDetailDialog = false">
              关闭
            </UiButton>
            <UiButton @click="openApproveDialog(currentOrder!, 2); showDetailDialog = false">
              通过
            </UiButton>
            <UiButton variant="destructive" @click="openApproveDialog(currentOrder!, 3); showDetailDialog = false">
              驳回
            </UiButton>
          </template>
          <UiButton v-else variant="outline" @click="showDetailDialog = false">
            关闭
          </UiButton>
        </UiDialogFooter>
      </UiDialogContent>
    </UiDialog>

    <!-- 审批弹窗 -->
    <UiDialog v-model:open="showApproveDialog">
      <UiDialogContent class="max-w-md">
        <UiDialogHeader>
          <UiDialogTitle>{{ approveStatus === 2 ? '通过订单' : '驳回订单' }}</UiDialogTitle>
        </UiDialogHeader>
        <div v-if="currentOrder" class="grid gap-4 py-4">
          <div class="p-3 rounded-lg bg-muted/50 text-sm">
            <div class="text-muted-foreground">
              订单号
            </div>
            <div class="font-mono">
              {{ currentOrder.orderNo }}
            </div>
            <div class="text-muted-foreground mt-2">
              金额
            </div>
            <div class="font-mono font-bold text-lg">
              ¥{{ formatAmount(currentOrder.amount) }}
            </div>
          </div>
          <div v-if="approveStatus === 3" class="grid gap-2">
            <UiLabel>驳回原因 <span class="text-red-500">*</span></UiLabel>
            <UiInput v-model="rejectReason" placeholder="请输入驳回原因" />
          </div>
          <div class="grid gap-2">
            <UiLabel>管理员备注</UiLabel>
            <UiInput v-model="adminRemark" placeholder="可选" />
          </div>
        </div>
        <UiDialogFooter>
          <UiButton variant="outline" @click="showApproveDialog = false">
            取消
          </UiButton>
          <UiButton
            :variant="approveStatus === 3 ? 'destructive' : 'default'"
            :disabled="approveMutation.isPending.value"
            @click="handleApprove"
          >
            <UiSpinner v-if="approveMutation.isPending.value" class="mr-2" />
            确认
          </UiButton>
        </UiDialogFooter>
      </UiDialogContent>
    </UiDialog>
  </BasicPage>
</template>
