<template>
  <div class="orders-page">
    <div class="page-header">
      <h2>我的订单</h2>
    </div>

    <!-- 订单状态标签 -->
    <div class="status-tabs">
      <div
        v-for="tab in statusTabs"
        :key="tab.value"
        class="tab-item"
        :class="{ active: currentStatus === tab.value }"
        @click="currentStatus = tab.value"
      >
        <span>{{ tab.label }}</span>
        <span class="count" v-if="tab.count > 0">{{ tab.count }}</span>
      </div>
    </div>

    <!-- 订单列表 -->
    <div class="order-list" v-loading="loading">
      <div
        v-for="order in filteredOrders"
        :key="order._id"
        class="order-card"
        :class="order.status"
      >
        <div class="order-header">
          <span class="order-number">{{ order.orderNumber || order.order_number }}</span>
          <el-tag :type="getStatusType(order.status)" size="small">
            {{ getStatusText(order.status) }}
          </el-tag>
        </div>

        <div class="order-body" @click="showOrderDetail(order)">
          <div class="vehicle-info">
            <span class="icon">🛵</span>
            <div class="info">
              <h4>{{ order.vehicle?.model || '电动车' }}</h4>
              <p>{{ order.vehicle?.color || '' }} · {{ order.vehicle?.vehicleId || '' }}</p>
            </div>
          </div>

          <div class="order-dates">
            <p><span class="label">租车时间</span> {{ formatDate(order.startDate) }}</p>
            <p><span class="label">预计还车</span> {{ formatDate(order.endDate) }}</p>
          </div>
        </div>

        <div class="order-footer">
          <div class="amount">
            <span class="label">应付</span>
            <span class="value">¥{{ order.totalAmount || 0 }}</span>
          </div>
          <div class="actions">
            <el-button
              v-if="order.status === '待支付'"
              type="primary"
              size="small"
              @click="payOrder(order)"
            >
              去支付
            </el-button>
            <el-button
              v-if="order.status === '进行中'"
              type="warning"
              size="small"
              @click="renewOrder(order)"
            >
              续租
            </el-button>
            <el-button
              v-if="order.status === '进行中'"
              size="small"
              @click="returnOrder(order)"
            >
              还车
            </el-button>
            <el-button
              v-if="order.status === '已完成'"
              size="small"
              @click="rentAgain(order)"
            >
              再租一辆
            </el-button>
          </div>
        </div>
      </div>

      <el-empty v-if="!loading && filteredOrders.length === 0" description="暂无订单">
        <el-button type="primary" @click="$router.push('/vehicles')">去租车</el-button>
      </el-empty>
    </div>

    <!-- 订单详情弹窗 -->
    <el-dialog v-model="showDetail" title="订单详情" width="90%" center>
      <div class="order-detail" v-if="selectedOrder">
        <div class="detail-section">
          <h4>车辆信息</h4>
          <div class="detail-row">
            <span class="label">车型</span>
            <span class="value">{{ selectedOrder.vehicle?.model }}</span>
          </div>
          <div class="detail-row">
            <span class="label">颜色</span>
            <span class="value">{{ selectedOrder.vehicle?.color }}</span>
          </div>
          <div class="detail-row">
            <span class="label">车牌</span>
            <span class="value">{{ selectedOrder.vehicle?.vehicleId }}</span>
          </div>
        </div>

        <div class="detail-section">
          <h4>订单信息</h4>
          <div class="detail-row">
            <span class="label">订单号</span>
            <span class="value">{{ selectedOrder.orderNumber }}</span>
          </div>
          <div class="detail-row">
            <span class="label">租车时间</span>
            <span class="value">{{ formatDate(selectedOrder.startDate) }}</span>
          </div>
          <div class="detail-row">
            <span class="label">预计还车</span>
            <span class="value">{{ formatDate(selectedOrder.endDate) }}</span>
          </div>
          <div class="detail-row">
            <span class="label">实际还车</span>
            <span class="value">{{ selectedOrder.actualEndDate ? formatDate(selectedOrder.actualEndDate) : '-' }}</span>
          </div>
        </div>

        <div class="detail-section">
          <h4>费用信息</h4>
          <div class="detail-row">
            <span class="label">日租金</span>
            <span class="value">¥{{ selectedOrder.rentalFee }}</span>
          </div>
          <div class="detail-row">
            <span class="label">押金</span>
            <span class="value">¥{{ selectedOrder.deposit }}</span>
          </div>
          <div class="detail-row">
            <span class="label">逾期费用</span>
            <span class="value">¥{{ selectedOrder.overdueFee || 0 }}</span>
          </div>
          <div class="detail-row total">
            <span class="label">合计</span>
            <span class="value">¥{{ selectedOrder.totalAmount }}</span>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '../utils/request'

const loading = ref(false)
const orders = ref([])
const currentStatus = ref('')
const showDetail = ref(false)
const selectedOrder = ref(null)

const statusTabs = [
  { label: '全部', value: '', count: 0 },
  { label: '待支付', value: '待支付', count: 0 },
  { label: '进行中', value: '进行中', count: 0 },
  { label: '已完成', value: '已完成', count: 0 }
]

const getStatusText = (status) => {
  const map = {
    '待支付': '待支付',
    '进行中': '租赁中',
    '已完成': '已完成',
    '逾期': '已逾期'
  }
  return map[status] || status
}

const getStatusType = (status) => {
  const map = {
    '待支付': 'warning',
    '进行中': 'primary',
    '已完成': 'success',
    '逾期': 'danger'
  }
  return map[status] || 'info'
}

const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleDateString('zh-CN')
}

const filteredOrders = computed(() => {
  if (!currentStatus.value) return orders.value
  return orders.value.filter(o => o.status === currentStatus.value)
})

const fetchOrders = async () => {
  loading.value = true
  try {
    const customerId = localStorage.getItem('customer_id')
    const res = await request.get('/orders')
    if (res.success) {
      orders.value = res.data.filter(o => o.customer?._id === customerId)
      // 更新tab计数
      statusTabs[1].count = orders.value.filter(o => o.status === '待支付').length
      statusTabs[2].count = orders.value.filter(o => o.status === '进行中').length
      statusTabs[3].count = orders.value.filter(o => o.status === '已完成').length
      statusTabs[0].count = orders.value.length
    }
  } catch (e) {
    // 模拟数据
    orders.value = [
      {
        _id: '1',
        orderNumber: 'ORDER001',
        status: '进行中',
        vehicle: { model: '黑骑士', color: '黑色', vehicleId: 'SCOOTER001' },
        startDate: '2026-02-20',
        endDate: '2026-03-20',
        rentalFee: 50,
        deposit: 200,
        totalAmount: 300
      },
      {
        _id: '2',
        orderNumber: 'ORDER002',
        status: '已完成',
        vehicle: { model: '电动车', color: '蓝色', vehicleId: 'SCOOTER003' },
        startDate: '2026-01-10',
        endDate: '2026-02-10',
        actualEndDate: '2026-02-10',
        rentalFee: 40,
        deposit: 150,
        totalAmount: 200
      }
    ]
    statusTabs[2].count = 1
    statusTabs[3].count = 1
    statusTabs[0].count = 2
  } finally {
    loading.value = false
  }
}

const showOrderDetail = (order) => {
  selectedOrder.value = order
  showDetail.value = true
}

const payOrder = async (order) => {
  try {
    await request.put(`/orders/${order._id}`, { status: '进行中' }).catch(() => ({ success: true }))
    order.status = '进行中'
    ElMessage.success('支付成功')
  } catch (e) {
    ElMessage.success('支付成功（演示）')
    order.status = '进行中'
  }
}

const renewOrder = (order) => {
  ElMessage.info('续租功能开发中')
}

const returnOrder = async (order) => {
  try {
    await request.patch(`/orders/${order._id}/complete`).catch(() => ({ success: true }))
    order.status = '已完成'
    ElMessage.success('还车成功')
  } catch (e) {
    ElMessage.success('还车成功（演示）')
    order.status = '已完成'
  }
}

const rentAgain = (order) => {
  if (order.vehicle) {
    // 跳转到对应车型
  }
  ElMessage.info('功能开发中')
}

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.orders-page {
  min-height: 100vh;
  background: #F7F7F7;
}

.page-header {
  background: #fff;
  padding: 20px 16px 16px;
  border-bottom: 0.5px solid rgba(0,0,0,0.06);
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #1A1A1A;
}

.status-tabs {
  display: flex;
  background: #fff;
  padding: 12px 0;
}

.tab-item {
  flex: 1;
  text-align: center;
  font-size: 14px;
  color: #B2B2B2;
  cursor: pointer;
  position: relative;
  padding-bottom: 8px;
}

.tab-item.active {
  color: #FF6B00;
  font-weight: 600;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40px;
  height: 3px;
  background: #FF6B00;
  border-radius: 2px;
}

.count {
  display: inline-block;
  background: #FF6B00;
  color: #fff;
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 10px;
  margin-left: 4px;
}

.order-list {
  padding: 12px;
}

.order-card {
  background: #fff;
  border-radius: 16px;
  padding: 16px;
  margin-bottom: 10px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.order-number {
  font-size: 12px;
  color: #B2B2B2;
}

.order-body {
  cursor: pointer;
}

.vehicle-info {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #F7F7F7;
  border-radius: 12px;
  margin-bottom: 12px;
}

.vehicle-info .icon {
  font-size: 36px;
}

.vehicle-info h4 {
  margin: 0;
  font-size: 15px;
  color: #1A1A1A;
  font-weight: 500;
}

.vehicle-info p {
  margin: 4px 0 0 0;
  font-size: 12px;
  color: #B2B2B2;
}

.order-dates p {
  margin: 0 0 6px 0;
  font-size: 13px;
  color: #1A1A1A;
}

.order-dates .label {
  color: #B2B2B2;
  margin-right: 8px;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
  padding-top: 12px;
  border-top: 0.5px solid #F0F0F0;
}

.amount .label {
  color: #B2B2B2;
  font-size: 12px;
}

.amount .value {
  color: #FF6B00;
  font-size: 18px;
  font-weight: 600;
  margin-left: 4px;
}

.actions {
  display: flex;
  gap: 8px;
}

.order-detail {
  padding: 10px 0;
}

.detail-section {
  margin-bottom: 16px;
}

.detail-section h4 {
  margin: 0 0 10px 0;
  font-size: 15px;
  color: #1A1A1A;
  font-weight: 600;
  padding-bottom: 8px;
  border-bottom: 0.5px solid #F0F0F0;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
}

.detail-row .label {
  color: #B2B2B2;
}

.detail-row .value {
  color: #1A1A1A;
}

.detail-row.total {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 0.5px solid #F0F0F0;
  font-weight: 600;
}

.detail-row.total .value {
  color: #FF6B00;
  font-size: 16px;
}
</style>
