<template>
  <div class="order-detail-page">
    <BackNav />
    <div v-if="order" class="detail-card">
      
      <div class="status-section">
        <el-tag :type="statusType(order.status)" size="large">{{ statusText(order.status) }}</el-tag>
        <span v-if="order.payment_method" class="payment-method">支付方式: {{ paymentMethodText(order.payment_method) }}</span>
        <el-button v-if="order.status === 'pending_payment'" type="primary" @click="goPay">去支付</el-button>
      </div>
      
      <div class="section-title">订单信息</div>
      <el-descriptions :column="2" border class="order-desc">
        <el-descriptions-item label="商品小计">¥{{ order.subtotal || order.total_amount }}</el-descriptions-item>
        <el-descriptions-item label="运费">¥{{ order.shipping_fee || 0 }}</el-descriptions-item>
        <el-descriptions-item label="服务费">¥{{ order.service_fee || 0 }}</el-descriptions-item>
        <el-descriptions-item label="税费">¥{{ order.tax || 0 }}</el-descriptions-item>
        <el-descriptions-item label="订单总额">
          <span class="total-amount">¥{{ order.total_amount }}</span>
        </el-descriptions-item>
        <el-descriptions-item :label="$t('order.createTime')">{{ formatDate(order.created_at) }}</el-descriptions-item>
        <el-descriptions-item :label="$t('order.trackingNumber')" v-if="order.tracking_number">{{ order.tracking_number }}</el-descriptions-item>
      </el-descriptions>
      
      <div class="section-title" v-if="order.shipping_address">收货地址</div>
      <div class="address-info" v-if="order.shipping_address">
        <p><strong>{{ order.shipping_address.name }}</strong> {{ order.shipping_address.phone }}</p>
        <p>{{ order.shipping_address.province }}{{ order.shipping_address.city }}{{ order.shipping_address.district }}{{ order.shipping_address.address }}</p>
      </div>
      
      <div class="section-title">商品明细</div>
      <el-table :data="order.order_items" size="small">
        <el-table-column prop="product.name" label="商品" />
        <el-table-column prop="quantity" label="数量" width="80" />
        <el-table-column prop="price" label="单价" width="100"><template #default="{ row }">¥{{ row.price }}</template></el-table-column>
        <el-table-column label="小计" width="100"><template #default="{ row }">¥{{ (row.price * row.quantity).toFixed(2) }}</template></el-table-column>
      </el-table>
      
      <div class="refund-section" v-if="canRefund">
        <el-button type="danger" @click="showRefund = true">{{ $t('order.applyRefund') }}</el-button>
      </div>
      
      <div class="refund-info" v-if="order.refund_status">
        <el-tag type="warning">退款状态: {{ refundStatusText(order.refund_status) }}</el-tag>
        <p v-if="order.refund_reason">退款原因: {{ order.refund_reason }}</p>
        <p v-if="order.refund_amount">退款金额: ¥{{ order.refund_amount }}</p>
      </div>
    </div>
    <el-dialog v-model="showRefund" :title="$t('order.applyRefund')" width="400px">
      <el-input v-model="refundReason" type="textarea" :placeholder="$t('order.refundReason')" />
      <template #footer>
        <el-button @click="showRefund = false">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="applyRefund">{{ $t('common.submit') }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { orderApi } from '../../api'
import BackNav from '../../components/BackNav.vue'

const route = useRoute()
const router = useRouter()
const order = ref<any>(null)
const showRefund = ref(false)
const refundReason = ref('')

const statusMap: Record<string, string> = {
  pending_payment: '待支付', pending_confirm: '待确认', pending_ship: '待发货',
  shipped: '已发货', completed: '已完成', refunding: '退款中', refunded: '已退款', cancelled: '已取消',
}
const statusTypeMap: Record<string, string> = {
  pending_payment: 'warning', pending_confirm: 'info', pending_ship: 'info',
  shipped: 'primary', completed: 'success', refunding: 'danger', refunded: 'danger', cancelled: 'info',
}
const refundStatusMap: Record<string, string> = {
  pending: '待处理', approved: '已批准', rejected: '已拒绝', completed: '已完成',
}
const paymentMethodMap: Record<string, string> = {
  balance: '余额支付', alipay: '支付宝', wechat: '微信支付',
}

function statusText(s: string) { return statusMap[s] || s }
function statusType(s: string) { return statusTypeMap[s] || 'info' }
function refundStatusText(s: string) { return refundStatusMap[s] || s }
function paymentMethodText(s: string) { return paymentMethodMap[s] || s }

function formatDate(date: string) {
  if (!date) return '-'
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

const canRefund = computed(() => {
  if (!order.value) return false
  return !['shipped', 'completed', 'refunded', 'refunding'].includes(order.value.status)
})

onMounted(async () => {
  const res: any = await orderApi.getById(Number(route.params.id))
  order.value = res.data
})

function goPay() {
  router.push(`/checkout/${order.value.id}`)
}

async function applyRefund() {
  if (!refundReason.value.trim()) {
    ElMessage.warning('请填写退款原因')
    return
  }
  await orderApi.refund(order.value.id, { reason: refundReason.value })
  ElMessage.success('退款申请已提交')
  showRefund.value = false
  const res: any = await orderApi.getById(order.value.id)
  order.value = res.data
}
</script>

<style scoped lang="scss">
.order-detail-page { padding: 0; }
.detail-card { background: #2d2d44; border: 1px solid rgba(255, 255, 255, 0.06); border-radius: 12px; padding: 24px; }

.status-section {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
}

.payment-method {
  color: rgba(255, 255, 255, 0.5);
  font-size: 14px;
}

.section-title {
  color: #fff;
  font-size: 16px;
  font-weight: 600;
  margin: 24px 0 12px;
  padding-left: 12px;
  border-left: 3px solid #4e6ef2;
}

.order-desc { margin-bottom: 0; }

.total-amount {
  font-size: 18px;
  font-weight: 700;
  color: #4e6ef2;
}

.address-info {
  background: rgba(255, 255, 255, 0.04);
  border-radius: 8px;
  padding: 16px;
  
  p {
    color: rgba(255, 255, 255, 0.8);
    margin: 4px 0;
    
    strong {
      color: #fff;
      margin-right: 12px;
    }
  }
}

.refund-section { margin-top: 24px; }

.refund-info {
  margin-top: 24px;
  padding: 16px;
  background: rgba(245, 158, 11, 0.1);
  border-radius: 8px;

  p {
    color: rgba(255, 255, 255, 0.7);
    margin: 8px 0 0;
  }
}

@media (max-width: 768px) {
  .detail-card {
    padding: 16px;
  }

  .status-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .section-title {
    font-size: 15px;
  }

  :deep(.el-descriptions) {
    .el-descriptions__label {
      width: 80px !important;
    }
  }

  :deep(.el-table) {
    font-size: 13px;

    .el-table__cell {
      padding: 8px 4px;
    }
  }
}
</style>
