<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMyOrdersApi, payOrderApi, cancelOrderApi, receiveOrderApi, refundOrderApi } from '@/api/order'
import type { OrderDetail } from '@/types'
import { Document, Wallet, Box, Van, CircleCheck } from '@element-plus/icons-vue'

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

const orders = ref<OrderDetail[]>([])
const loading = ref(false)
const activeTab = ref<string>('all')

const tabs = [
  { label: '全部订单', value: 'all', icon: Document },
  { label: '待付款', value: '0', icon: Wallet },
  { label: '待发货', value: '1', icon: Box },
  { label: '待收货', value: '2', icon: Van },
  { label: '已完成', value: '3', icon: CircleCheck }
]

const statusType: Record<number, string> = {
  0: 'warning',
  1: 'primary',
  2: 'success',
  3: 'info',
  4: 'info'
}

const statusColorMap: Record<number, string> = {
  0: '#F59E0B',
  1: '#3B82F6',
  2: '#06D6A0',
  3: '#9CA3AF',
  4: '#9CA3AF'
}

async function load(status?: number) {
  loading.value = true
  try {
    const page = await getMyOrdersApi({
      current: 1,
      size: 50,
      status
    })
    orders.value = page.records || []
  } finally {
    loading.value = false
  }
}

function loadByTab() {
  load(activeTab.value === 'all' ? undefined : Number(activeTab.value))
}

watch(activeTab, loadByTab)

onMounted(() => {
  const qs = route.query.status
  if (qs !== undefined) {
    const s = String(qs)
    if (tabs.some(t => t.value === s)) activeTab.value = s
  }
  loadByTab()
})

async function onPay(order: OrderDetail) {
  await ElMessageBox.confirm(`确认支付订单 ${order.orderNo} 吗？`, '支付', { type: 'warning' })
  await payOrderApi(order.id)
  ElMessage.success('支付成功')
  loadByTab()
}

async function onCancel(order: OrderDetail) {
  await ElMessageBox.confirm('确认取消该订单？', '提示', { type: 'warning' })
  await cancelOrderApi(order.id)
  ElMessage.success('已取消')
  loadByTab()
}

async function onReceive(order: OrderDetail) {
  await ElMessageBox.confirm('确认已收到货？', '提示', { type: 'warning' })
  await receiveOrderApi(order.id)
  ElMessage.success('已确认收货')
  loadByTab()
}

async function onRefund(order: OrderDetail) {
  const { value: reason } = await ElMessageBox.prompt('请输入退款原因', '申请退款', {
    confirmButtonText: '提交',
    cancelButtonText: '取消',
    inputPlaceholder: '例如：商品质量问题'
  }).catch(() => ({ value: undefined }))
  if (!reason) return
  await refundOrderApi(order.id, reason)
  ElMessage.success('退款申请已提交')
  loadByTab()
}
</script>

<template>
  <div class="order-page container">
    <div class="page-header">
      <h2 class="page-title">我的订单</h2>
      <p class="page-subtitle">查看和管理您的所有订单</p>
    </div>

    <div class="order-content">
      <!-- Custom Tabs -->
      <div class="tab-bar">
        <div
          v-for="tab in tabs"
          :key="tab.value"
          class="tab-item"
          :class="{ active: activeTab === tab.value }"
          @click="activeTab = tab.value"
        >
          <el-icon :size="16"><component :is="tab.icon" /></el-icon>
          <span>{{ tab.label }}</span>
        </div>
      </div>

      <!-- Order List -->
      <div v-loading="loading" class="order-list">
        <div v-for="order in orders" :key="order.id" class="order-card">
          <div class="order-header" :style="{ borderLeftColor: statusColorMap[order.status] }">
            <div class="header-left">
              <span class="order-no">{{ order.orderNo }}</span>
              <span class="order-time">{{ order.createTime }}</span>
            </div>
            <el-tag
              :type="(statusType[order.status] as any) || 'info'"
              size="small"
              effect="dark"
              class="status-tag"
            >
              {{ order.statusText }}
            </el-tag>
          </div>
          <div class="order-items">
            <div v-for="item in order.items" :key="item.id" class="order-item">
              <div class="item-thumb">
                <img :src="item.productImage || 'https://placehold.co/100x100?text=ITEM'" />
              </div>
              <div class="item-info">
                <p class="name">{{ item.productName }}</p>
                <p class="sku">{{ item.skuName }}</p>
              </div>
              <div class="item-price">
                <span class="price">¥{{ item.price }}</span>
                <span class="qty">x{{ item.quantity }}</span>
              </div>
            </div>
          </div>
          <div class="order-footer">
            <div class="order-summary">
              共 <b>{{ order.totalQuantity }}</b> 件商品，实付
              <span class="price-lg">¥{{ Number(order.payAmount).toFixed(2) }}</span>
            </div>
            <div class="order-actions">
              <el-button v-if="order.status === 0" type="primary" size="small" round @click="onPay(order)">立即付款</el-button>
              <el-button v-if="order.status === 0" size="small" round @click="onCancel(order)">取消</el-button>
              <el-button v-if="order.status === 2" type="success" size="small" round @click="onReceive(order)">确认收货</el-button>
              <el-button v-if="[1,2,3].includes(order.status)" size="small" round type="warning" @click="onRefund(order)">申请退款</el-button>
              <el-button size="small" round>查看详情</el-button>
            </div>
          </div>
        </div>
      </div>

      <el-empty v-if="!loading && orders.length === 0" description="暂无订单">
        <el-button type="primary" @click="router.push('/')">去购物</el-button>
      </el-empty>
    </div>
  </div>
</template>

<style scoped>
.order-page {
  padding: 24px 0 60px;
}
.page-header {
  margin-bottom: 24px;
}
.page-title {
  font-size: 24px;
  font-weight: 700;
  margin-bottom: 4px;
}
.page-subtitle {
  color: var(--color-text-muted);
  font-size: 14px;
}

/* Tab Bar */
.tab-bar {
  display: flex;
  gap: 8px;
  margin-bottom: 20px;
  background: #fff;
  padding: 8px;
  border-radius: var(--radius-full);
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--color-border-light);
  overflow-x: auto;
}
.tab-item {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 10px 20px;
  border-radius: var(--radius-full);
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  color: var(--color-text-secondary);
  transition: all var(--transition-fast);
  white-space: nowrap;
  flex-shrink: 0;
}
.tab-item:hover {
  background: var(--color-primary-light);
  color: var(--color-primary);
}
.tab-item.active {
  background: var(--color-primary-gradient);
  color: #fff;
  box-shadow: var(--shadow-sm);
}

/* Order List */
.order-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.order-card {
  background: #fff;
  border-radius: var(--radius-xl);
  overflow: hidden;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--color-border-light);
  transition: box-shadow var(--transition-fast);
}
.order-card:hover {
  box-shadow: var(--shadow-md);
}
.order-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 14px 20px;
  background: var(--color-background);
  font-size: 13px;
  border-left: 4px solid transparent;
}
.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}
.order-no {
  font-weight: 700;
  color: var(--color-text);
  font-size: 14px;
}
.order-time {
  color: var(--color-text-muted);
}
.status-tag {
  font-weight: 500;
}

/* Order Items */
.order-items {
  padding: 16px 20px;
}
.order-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 10px 0;
}
.item-thumb {
  width: 72px;
  height: 72px;
  border-radius: var(--radius-md);
  overflow: hidden;
  flex-shrink: 0;
  border: 1px solid var(--color-border-light);
}
.item-thumb img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.item-info {
  flex: 1;
}
.item-info .name {
  font-weight: 600;
  font-size: 15px;
  margin-bottom: 6px;
  color: var(--color-text);
}
.item-info .sku {
  color: var(--color-text-muted);
  font-size: 13px;
}
.item-price {
  text-align: right;
  min-width: 80px;
}
.item-price .qty {
  color: var(--color-text-muted);
  font-size: 13px;
  display: block;
  margin-top: 2px;
}

/* Order Footer */
.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 14px 20px;
  background: var(--color-background);
  border-top: 1px solid var(--color-border-light);
}
.order-summary {
  font-size: 14px;
  color: var(--color-text-secondary);
}
.order-summary b {
  color: var(--color-text);
}
.order-summary .price-lg {
  color: var(--color-primary);
  font-weight: 700;
  margin-left: 4px;
  font-size: 18px;
}
.order-actions {
  display: flex;
  gap: 8px;
}

/* Responsive */
@media (max-width: 768px) {
  .tab-bar {
    border-radius: var(--radius-lg);
  }
  .tab-item {
    padding: 8px 14px;
    font-size: 13px;
  }
  .order-footer {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  .order-actions {
    justify-content: flex-end;
    flex-wrap: wrap;
  }
  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  .status-tag {
    align-self: flex-start;
  }
}
</style>
