<template>
  <view class="order-detail-container">
    <NavBar title="订单详情" @back="goBack" />
    
    <!-- 订单号和状态卡片 -->
    <view class="status-card">
      <view class="order-number">
        <text class="number-label">订单号</text>
        <view class="number-value-row">
          <text class="number-value">{{ orderDetail.orderId }}</text>
          <AppIcon name="copy" :size="28" color="#C6171E" class="copy-icon" @click.stop="copyText(orderDetail.orderId)" />
        </view>
      </view>
      <view class="status-row">
        <text
          class="status-tag"
          :style="getOrderStatusStyle(orderDetail.orderStatus)"
        >
          {{ getOrderStatusText(orderDetail.orderStatus) }}
        </text>
        <text class="create-time">{{ formatTime(orderDetail.createTime) }}</text>
      </view>
    </view>
    
    <!-- 订单信息卡片 -->
    <view class="info-card">
      <view class="card-title">订单信息</view>
      <view class="info-list">
        <view class="info-item">
          <text class="item-label">支付状态</text>
          <text class="item-value">{{ getPayStatusText(orderDetail.payStatus) }}</text>
        </view>
        <view class="info-item">
          <text class="item-label">用户手机号</text>
          <view class="item-value-row">
            <text class="item-value">{{ orderDetail.mobilePhone || '匿名用户' }}</text>
            <AppIcon v-if="orderDetail.mobilePhone" name="copy" :size="28" color="#C6171E" class="copy-icon" @click.stop="copyText(orderDetail.mobilePhone)" />
          </view>
        </view>
        <view class="info-item">
          <text class="item-label">设备编号</text>
          <view class="item-value-row">
            <text class="item-value">{{ orderDetail.shortId || '未知设备' }}</text>
            <AppIcon v-if="orderDetail.shortId" name="copy" :size="28" color="#C6171E" class="copy-icon" @click.stop="copyText(orderDetail.shortId)" />
          </view>
        </view>
        <view class="info-item">
          <text class="item-label">消费站点</text>
          <text class="item-value">{{ orderDetail.stationName || '未知站点' }}</text>
        </view>
        <view class="info-item">
          <text class="item-label">归属站点</text>
          <text class="item-value">{{ orderDetail.userStationName || '未知站点' }}</text>
        </view>
        <view class="info-item">
          <text class="item-label">关机方式</text>
          <text class="item-value">{{ getCloseTypeText(orderDetail.closeType) }}</text>
        </view>
        <view class="info-item">
          <text class="item-label">发票状态</text>
          <text class="item-value">{{ getInvoiceStatusText(orderDetail.invoiceStatus) }}</text>
        </view>
      </view>
    </view>
    
    <!-- 金额明细卡片 -->
    <view class="amount-card">
      <view class="card-title">金额明细</view>
      <view class="amount-list">
        <view class="amount-item">
          <text class="amount-label">消费总额</text>
          <text class="amount-value">¥{{ formatAmount(orderDetail.amount) }}</text>
        </view>
        <view class="amount-item">
          <text class="amount-label">应收金额</text>
          <text class="amount-value">¥{{ formatAmount(orderDetail.amountReceivable) }}</text>
        </view>
        <view class="amount-item">
          <text class="amount-label">实收金额</text>
          <text class="amount-value primary">¥{{ formatAmount(orderDetail.amountReceived) }}</text>
        </view>
        <view class="amount-item" v-if="orderDetail.discountAmount !== undefined && orderDetail.discountAmount > 0">
          <text class="amount-label">优惠金额</text>
          <text class="amount-value success">-¥{{ formatAmount(orderDetail.discountAmount) }}</text>
        </view>
        <view class="amount-item" v-if="orderDetail.prepayMoney !== undefined && orderDetail.prepayMoney > 0">
          <text class="amount-label">预付金额</text>
          <text class="amount-value">¥{{ formatAmount(orderDetail.prepayMoney) }}</text>
        </view>
      </view>
    </view>
    
    <!-- 服务明细 -->
    <view class="service-card" v-if="orderDetail.detail && orderDetail.detail.length > 0">
      <view class="card-title">服务明细</view>
      <view class="service-table">
        <view class="table-header">
          <text class="col col-name">服务项目</text>
          <text class="col col-time">时长</text>
          <text class="col col-price">单价</text>
          <text class="col col-amount">金额</text>
        </view>
        <view 
          v-for="(service, index) in orderDetail.detail" 
          :key="index" 
          class="table-row"
        >
          <text class="col col-name">{{ service.name }}</text>
          <text class="col col-time">{{ service.seconds }}</text>
          <text class="col col-price">¥{{ service.price }}</text>
          <text class="col col-amount">¥{{ service.amount }}</text>
        </view>
      </view>
    </view>
    
    <!-- 操作按钮 -->
    <view class="action-section" v-if="canHandleRefund">
      <button class="refund-btn" @click="handleRefund">
        处理退款
      </button>
    </view>
    
    <!-- 加载状态 -->
    <view class="loading-state" v-if="loading">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-if="!loading && !orderDetail.orderId">
      <view class="empty-icon-wrapper">
        <AppIcon name="inbox" size="48" color="#B0B0B0" />
      </view>
      <text class="empty-text">未找到该订单</text>
      <text class="empty-hint">请检查订单号是否正确，或返回列表重新选择</text>
      <button class="empty-back-btn" @click="goBack">返回订单列表</button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { getOrderDetail, handleRefund as refundApi } from '../../api/order.js'
import { formatTime, showToast, formatAmount, fmtDictName, getDictColor, copyText } from '../../utils/index.js'
import dictUtil, { loadDicts } from '../../utils/dict.js'

const orderId = ref('')
const orderDetail = ref({})
const loading = ref(true)

// 从字典获取订单状态文本
const getOrderStatusText = (status) => {
  return fmtDictName('Order.status', status)
}

// 从字典获取支付状态文本
const getPayStatusText = (status) => {
  return fmtDictName('Order.pay', status)
}

// 从字典获取关机方式文本
const getCloseTypeText = (type) => {
  return fmtDictName('Order.closeType', type)
}

// 从字典获取发票状态文本
const getInvoiceStatusText = (status) => {
  return fmtDictName('Invoice.status', status)
}

// 从字典获取订单状态内联样式
const getOrderStatusStyle = (status) => {
  const color = getDictColor('Order.status', status)
  if (color) {
    return {
      color: color,
      backgroundColor: `${color}1A`
    }
  }
  return {}
}

// 计算是否可以处理退款
const canHandleRefund = computed(() => {
  const refundValue = dictUtil.getDictValue('Order.status', '退款中')
  return orderDetail.value.orderStatus === refundValue && orderDetail.value.refundLogId
})

// 加载订单详情
const loadOrderDetail = async () => {
  if (!orderId.value) {
    showToast('订单ID不存在')
    loading.value = false
    return
  }
  
  loading.value = true
  try {
    const res = await getOrderDetail(orderId.value)
    if (res && res.code === 200) {
      let data = res.data
      
      // 处理服务明细
      if (data.detail) {
        // 适配不同的数据结构
        if (typeof data.detail === 'string') {
          try {
            data.detail = JSON.parse(data.detail)
          } catch (e) {
            console.error('解析服务明细失败:', e)
            data.detail = []
          }
        }
        
        // 格式化服务明细
        data.detail = data.detail
          .filter(item => item.amount > 0 || item.seconds > 0)
          .map(item => {
            const serviceName = dictUtil.getDictLabel('Order.feeType', item.name)
            return {
              name: serviceName,
              seconds: formatDuration(item.seconds),
              price: formatAmount(item.price),
              amount: formatAmount(item.amount)
            }
          })
      } else {
        data.detail = []
      }
      
      orderDetail.value = data
    } else {
      showToast(res.msg || '获取订单详情失败')
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    showToast('获取订单详情失败')
  } finally {
    loading.value = false
  }
}

// 格式化时长
const formatDuration = (seconds) => {
  if (!seconds || isNaN(seconds)) return '0秒'
  
  const totalSeconds = parseInt(seconds)
  const minutes = Math.floor(totalSeconds / 60)
  const remainingSeconds = totalSeconds % 60
  
  if (minutes > 0) {
    return `${minutes}分${remainingSeconds}秒`
  } else {
    return `${remainingSeconds}秒`
  }
}

// 处理退款
const handleRefund = async () => {
  if (!orderDetail.value.refundLogId) {
    showToast('没有退款记录ID')
    return
  }
  
  try {
    await refundApi(orderDetail.value.refundLogId)
    showToast('退款处理成功', 'success')
    // 刷新订单详情
    loadOrderDetail()
  } catch (error) {
    console.error('处理退款失败:', error)
    showToast('处理退款失败')
  }
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 页面加载时获取订单ID并加载详情
onMounted(async () => {
  await loadDicts()

  // 获取页面参数
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const receivedOrderId = currentPage.options.orderId || ''

  if (!receivedOrderId) {
    showToast('订单ID不存在，无法加载详情')
    loading.value = false
    return
  }

  orderId.value = receivedOrderId
  loadOrderDetail()
})
</script>

<style scoped>
/* 容器 */
.order-detail-container {
  min-height: 100vh;
  background-color: #F5F7FA;
  padding-bottom: 120rpx;
}

/* 订单号和状态卡片 */
.status-card {
  margin: 20rpx 30rpx;
  padding: 24rpx 30rpx;
  background: #FFFFFF;
  border-radius: 48rpx;
}

.order-number {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #F0F0F0;
}

.number-label {
  font-size: 24rpx;
  color: #999999;
}

.number-value {
  font-size: 24rpx;
  color: #1A1A1A;
  font-weight: 600;
  flex: 1;
  text-align: right;
}

.status-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.status-tag {
  font-size: 24rpx;
  font-weight: 500;
  padding: 6rpx 24rpx;
  border-radius: 200rpx;
}

.create-time {
  font-size: 24rpx;
  color: #999999;
}

/* 信息卡片 */
.info-card,
.amount-card,
.service-card {
  margin: 20rpx 30rpx;
  background: #FFFFFF;
  border-radius: 48rpx;
  overflow: hidden;
}

.card-title {
  padding: 24rpx 30rpx 20rpx;
  font-size: 32rpx;
  font-weight: 600;
  color: #1A1A1A;
  border-bottom: 1rpx solid #F0F0F0;
}

/* 信息列表 */
.info-list {
  padding: 20rpx 30rpx 24rpx;
}

.info-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #F5F7FA;
}

.info-item:last-child {
  border-bottom: none;
}

.item-label {
  font-size: 28rpx;
  color: #666666;
}

.item-value {
  font-size: 28rpx;
  color: #1A1A1A;
  font-weight: 500;
  text-align: right;
}

.item-value-row {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.number-value-row {
  display: flex;
  align-items: center;
  gap: 8rpx;
  flex: 1;
  justify-content: flex-end;
}

.copy-icon {
  flex-shrink: 0;
}

/* 金额列表 */
.amount-list {
  padding: 20rpx 30rpx 24rpx;
}

.amount-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #F5F7FA;
}

.amount-item:last-child {
  border-bottom: none;
}

.amount-label {
  font-size: 28rpx;
  color: #666666;
}

.amount-value {
  font-size: 28rpx;
  color: #1A1A1A;
  font-weight: 600;
}

.amount-value.primary {
  font-size: 32rpx;
  color: #C6171E;
  font-weight: 700;
}

.amount-value.success {
  color: #52C41A;
}

/* 服务明细表格 */
.service-table {
  padding: 0 30rpx 24rpx;
}

.table-header,
.table-row {
  display: flex;
  align-items: center;
  padding: 16rpx 0;
}

.table-header {
  border-bottom: 1rpx solid #F0F0F0;
}

.table-header .col {
  font-size: 24rpx;
  color: #999999;
  font-weight: 500;
}

.table-row {
  border-bottom: 1rpx solid #F5F7FA;
}

.table-row:last-child {
  border-bottom: none;
}

.table-row .col {
  font-size: 28rpx;
  color: #1A1A1A;
}

.col-name,
.col-time,
.col-price,
.col-amount {
  flex: 1;
  text-align: center;
  min-width: 0;
  word-break: break-all;
}

.col-amount {
  font-weight: 600;
  color: #52C41A;
}

/* 操作按钮 */
.action-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 24rpx 30rpx;
  background: #FFFFFF;
  border-top: 1rpx solid #F0F0F0;
  box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.06);
  z-index: 100;
}

.refund-btn {
  width: 100%;
  padding: 22rpx 0;
  background: #C6171E;
  color: #FFFFFF;
  border: none;
  border-radius: 16rpx;
  font-size: 30rpx;
  font-weight: 600;
  box-shadow: 0 4rpx 16rpx rgba(198, 23, 30, 0.25);
}

.refund-btn:active {
  background: #A81212;
  transform: scale(0.97);
}

/* 加载状态 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
  color: #999999;
}

.loading-spinner {
  font-size: 64rpx;
  animation: spin 1s linear infinite;
  margin-bottom: 32rpx;
  color: #B0B0B0;
}

.loading-text {
  font-size: 28rpx;
  color: #999999;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 160rpx 60rpx;
  color: #999999;
  text-align: center;
}

.empty-icon-wrapper {
  margin-bottom: 24rpx;
}

.empty-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #1A1A1A;
  margin-top: 24rpx;
  margin-bottom: 16rpx;
}

.empty-hint {
  font-size: 28rpx;
  color: #999999;
  margin-bottom: 40rpx;
  line-height: 1.5;
}

.empty-back-btn {
  padding: 20rpx 60rpx;
  background: #C6171E;
  color: #FFFFFF;
  border: none;
  border-radius: 32rpx;
  font-size: 28rpx;
  font-weight: 500;
}

.empty-back-btn:active {
  background: #A81212;
  transform: scale(0.97);
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

</style>
