<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ArrowLeft, Van } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getOrderDetailApi,
  deliverOrderApi,
  cancelOrderApi,
  type OrderDetail
} from '@/api/order'
import { formatDate } from '@/utils/date'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const detail = ref<OrderDetail | null>(null)

async function fetchDetail() {
  const id = Number(route.params.id)
  if (!id) return
  loading.value = true
  try {
    detail.value = await getOrderDetailApi(id)
  } catch {
    /* 拦截器已提示 */
  } finally {
    loading.value = false
  }
}

function goBack() {
  router.push('/order/list')
}

function fmt(n?: number) {
  return `¥ ${n ?? 0}`
}

function fmtTime(date?: string) {
  return date ? formatDate(date) : '—'
}

async function handleDeliver() {
  if (!detail.value) return
  try {
    const { value } = await ElMessageBox.prompt(
      `请输入【${detail.value.orderNo}】的物流单号`,
      '订单发货',
      { confirmButtonText: '发货', cancelButtonText: '取消' }
    )
    await deliverOrderApi(detail.value.id, { company: '顺丰速运', trackingNo: value })
    ElMessage.success('发货成功')
    fetchDetail()
  } catch {
    /* 用户取消；失败时拦截器已提示 */
  }
}

async function handleCancel() {
  if (!detail.value) return
  try {
    await ElMessageBox.confirm(
      `确定要取消订单【${detail.value.orderNo}】吗？取消后订单关闭并释放库存。`,
      '提示',
      { type: 'warning', confirmButtonText: '确定取消', cancelButtonText: '再想想' }
    )
    await cancelOrderApi(detail.value.id)
    ElMessage.success('订单已取消')
    fetchDetail()
  } catch {
    /* 用户取消；失败时拦截器已提示 */
  }
}

/** 状态时间轴：按订单状态逐步展示节点 */
const timeline = computed(() => {
  const d = detail.value
  if (!d) return []
  const items: {
    label: string
    time?: string
    active: boolean
    type: 'primary' | 'success' | 'danger'
  }[] = [
    { label: '创建订单', time: d.createTime, active: true, type: 'primary' },
    { label: '支付成功', time: d.payTime, active: !!d.payTime, type: 'success' },
    { label: '订单发货', time: d.deliverTime, active: !!d.deliverTime, type: 'primary' },
    {
      label: '确认收货',
      time: d.receiveTime || d.finishTime,
      active: !!(d.receiveTime || d.finishTime),
      type: 'success'
    }
  ]
  if (d.status === 4) {
    items.push({ label: '订单取消', time: d.cancelTime, active: true, type: 'danger' })
  }
  if (d.status === 5) {
    items.push({ label: '订单退款', time: d.refundTime, active: true, type: 'danger' })
  }
  return items
})

onMounted(fetchDetail)
</script>

<template>
  <div class="page-container">
    <div class="page-header">
      <div class="header-left">
        <el-button text :icon="ArrowLeft" @click="goBack">返回列表</el-button>
        <div>
          <h2>订单详情</h2>
          <p v-if="detail" class="page-desc">订单号：{{ detail.orderNo }}</p>
        </div>
      </div>
      <div v-if="detail" class="header-actions">
        <el-tag :type="(detail.statusTagType as any)" size="large">
          {{ detail.statusText }}
        </el-tag>
        <el-button v-if="detail.status === 1" type="success" :icon="Van" @click="handleDeliver">
          发货
        </el-button>
        <el-button v-if="detail.status === 0" type="danger" @click="handleCancel">
          取消订单
        </el-button>
      </div>
    </div>

    <div v-loading="loading" class="detail-body">
      <template v-if="detail">
        <el-row :gutter="16">
          <!-- 基本信息 -->
          <el-col :xs="24" :lg="14">
            <el-card shadow="never" class="section-card">
              <template #header>
                <span class="card-title">基本信息</span>
              </template>
              <el-descriptions :column="2" border>
                <el-descriptions-item label="订单号">{{ detail.orderNo }}</el-descriptions-item>
                <el-descriptions-item label="下单时间">{{ fmtTime(detail.createTime) }}</el-descriptions-item>
                <el-descriptions-item label="支付渠道">{{ detail.payChannelText || '—' }}</el-descriptions-item>
                <el-descriptions-item label="支付时间">{{ fmtTime(detail.payTime) }}</el-descriptions-item>
                <el-descriptions-item label="支付交易号" :span="2">{{ detail.payTradeNo || '—' }}</el-descriptions-item>
                <el-descriptions-item label="订单备注" :span="2">
                  {{ detail.remark || '—' }}
                </el-descriptions-item>
              </el-descriptions>
            </el-card>
          </el-col>

          <!-- 买家信息 -->
          <el-col :xs="24" :lg="10">
            <el-card shadow="never" class="section-card">
              <template #header>
                <span class="card-title">买家信息</span>
              </template>
              <el-descriptions :column="2" border>
                <el-descriptions-item label="用户 ID">{{ detail.userId }}</el-descriptions-item>
                <el-descriptions-item label="用户名">{{ detail.username || '—' }}</el-descriptions-item>
                <el-descriptions-item label="收件人">{{ detail.receiverName || '—' }}</el-descriptions-item>
                <el-descriptions-item label="联系电话">{{ detail.receiverPhone || '—' }}</el-descriptions-item>
                <el-descriptions-item label="收货地址" :span="2">
                  {{ detail.receiverAddress || '—' }}
                </el-descriptions-item>
              </el-descriptions>
            </el-card>
          </el-col>
        </el-row>

        <!-- 商品明细 -->
        <el-card shadow="never" class="section-card">
          <template #header>
            <span class="card-title">商品明细</span>
            <span class="card-extra">共 {{ detail.totalQuantity }} 件</span>
          </template>
          <el-table :data="detail.items" stripe border>
            <el-table-column label="商品" min-width="260">
              <template #default="{ row }">
                <div class="product-cell">
                  <el-image
                    v-if="row.productImage"
                    :src="row.productImage"
                    :preview-src-list="[row.productImage]"
                    fit="cover"
                    class="product-img"
                  />
                  <div v-else class="product-img product-img-placeholder">无图</div>
                  <span class="product-name">{{ row.productName }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="skuName" label="规格" width="140" />
            <el-table-column label="单价" width="120" align="right">
              <template #default="{ row }">{{ fmt(row.price) }}</template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="90" align="center" />
            <el-table-column label="小计" width="130" align="right">
              <template #default="{ row }">
                <span class="amount">{{ fmt(row.totalAmount) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <el-row :gutter="16">
          <!-- 金额明细 -->
          <el-col :xs="24" :lg="12">
            <el-card shadow="never" class="section-card">
              <template #header>
                <span class="card-title">金额明细</span>
              </template>
              <div class="amount-list">
                <div class="amount-row">
                  <span>商品总额</span>
                  <span>{{ fmt(detail.totalAmount) }}</span>
                </div>
                <div class="amount-row">
                  <span>运费</span>
                  <span>{{ fmt(detail.freightAmount) }}</span>
                </div>
                <div class="amount-row">
                  <span>优惠金额（满减/折扣）</span>
                  <span class="discount">-{{ fmt(detail.discountAmount) }}</span>
                </div>
                <div class="amount-row">
                  <span>优惠券抵扣</span>
                  <span class="discount">-{{ fmt(detail.couponAmount) }}</span>
                </div>
                <div class="amount-row amount-row-total">
                  <span>实付金额</span>
                  <span class="amount">{{ fmt(detail.payAmount) }}</span>
                </div>
              </div>
            </el-card>
          </el-col>

          <!-- 物流信息 -->
          <el-col :xs="24" :lg="12">
            <el-card shadow="never" class="section-card">
              <template #header>
                <span class="card-title">物流信息</span>
              </template>
              <el-descriptions :column="2" border>
                <el-descriptions-item label="物流公司">
                  {{ detail.trackingCompany || (detail.status >= 2 ? '—' : '待发货') }}
                </el-descriptions-item>
                <el-descriptions-item label="物流单号">
                  {{ detail.trackingNo || '—' }}
                </el-descriptions-item>
                <el-descriptions-item label="发货时间" :span="2">
                  {{ fmtTime(detail.deliverTime) }}
                </el-descriptions-item>
                <el-descriptions-item label="退款交易号" :span="2">
                  {{ detail.refundTradeNo || '—' }}
                </el-descriptions-item>
                <el-descriptions-item label="退款时间" :span="2">
                  {{ fmtTime(detail.refundTime) }}
                </el-descriptions-item>
              </el-descriptions>
            </el-card>
          </el-col>
        </el-row>

        <!-- 状态时间轴 -->
        <el-card shadow="never" class="section-card">
          <template #header>
            <span class="card-title">订单状态时间轴</span>
          </template>
          <el-timeline class="order-timeline">
            <el-timeline-item
              v-for="(item, idx) in timeline"
              :key="idx"
              :type="item.type"
              :hollow="!item.active"
              :timestamp="fmtTime(item.time)"
            >
              {{ item.label }}
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </template>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}
.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}
.detail-body {
  min-height: 200px;
}
.section-card {
  margin-bottom: 16px;
  border-radius: $radius-md;
  box-shadow: $shadow-sm;
}
.card-title {
  font-weight: 600;
  color: $color-text-primary;
}
.card-extra {
  float: right;
  font-size: 12px;
  color: $color-text-secondary;
}
.product-cell {
  display: flex;
  align-items: center;
  gap: 10px;
}
.product-img {
  width: 48px;
  height: 48px;
  border-radius: $radius-sm;
  flex-shrink: 0;
}
.product-img-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: $color-text-secondary;
  background: $bg-hover;
}
.product-name {
  color: $color-text-primary;
}
.amount-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.amount-row {
  display: flex;
  justify-content: space-between;
  color: $color-text-regular;
  font-size: 13px;
}
.amount-row-total {
  padding-top: 10px;
  border-top: 1px dashed $color-border;
  font-size: 15px;
  font-weight: 600;
}
.amount {
  color: $color-danger;
  font-weight: 600;
}
.discount {
  color: $color-success;
}
.order-timeline {
  padding: 4px 8px;
}
</style>
