<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'

import { fetchOrders, payOrder, type Order } from '@/api/orders'
import { useSessionStore } from '@/stores/session'
import { orderStatusLabel } from '@/utils/statusLabels'

const loading = ref(false)
const orders = ref<Order[]>([])
const payingOrderId = ref<number | null>(null)
const session = useSessionStore()

onMounted(loadOrders)

async function loadOrders() {
  loading.value = true
  try {
    orders.value = await fetchOrders()
  } finally {
    loading.value = false
  }
}

async function handlePay(order: Order) {
  payingOrderId.value = order.id
  try {
    await payOrder(order.id)
    ElMessage.success('支付成功，等待号主交接')
    await loadOrders()
  } catch (error) {
    ElMessage.error(readError(error, '支付失败'))
  } finally {
    payingOrderId.value = null
  }
}

function readError(error: unknown, fallback: string) {
  if (typeof error === 'object' && error && 'response' in error) {
    const response = (error as { response?: { data?: { message?: string } } }).response
    return response?.data?.message || fallback
  }
  return fallback
}

function orderRole(order: Order) {
  if (order.renter_id === session.userId) return '买家'
  if (order.owner_id === session.userId) return '号主'
  return '-'
}

function money(value: unknown) {
  return Math.round(Number(value || 0))
}
</script>

<template>
  <section class="page">
    <div class="page-header">
      <p class="eyebrow">Orders</p>
      <h1>我的订单</h1>
      <p>跟踪待支付、待交接、使用中、待归还、申诉中和已完成订单。</p>
    </div>

    <el-table v-loading="loading" class="table-panel" :data="orders">
      <el-table-column prop="order_no" label="订单号" min-width="210" />
      <el-table-column prop="title" label="账号" min-width="180" />
      <el-table-column label="我的金额" width="100">
        <template #default="{ row }">¥{{ money(row.display_amount) }}</template>
      </el-table-column>
      <el-table-column label="押金" width="100">
        <template #default="{ row }">¥{{ money(row.deposit_amount) }}</template>
      </el-table-column>
      <el-table-column label="身份" width="80">
        <template #default="{ row }">{{ orderRole(row) }}</template>
      </el-table-column>
      <el-table-column label="状态" width="140">
        <template #default="{ row }">{{ orderStatusLabel(row.status) }}</template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template #default="{ row }">
          <el-button
            v-if="row.status === 'pending_payment'"
            size="small"
            type="primary"
            :disabled="row.renter_id !== session.userId"
            :loading="payingOrderId === row.id"
            @click="handlePay(row)"
          >
            支付
          </el-button>
          <RouterLink :to="`/orders/${row.id}`">
            <el-button size="small">详情</el-button>
          </RouterLink>
        </template>
      </el-table-column>
    </el-table>
  </section>
</template>
