<template>
  <view class="order-detail-container">
    <!-- 顶部紫色导航栏 -->
    <view class="header-nav" @click="goBack">
      <text class="back-icon">←</text>
      <text class="nav-title">订单详情</text>
    </view>
    
    <!-- 订单号和状态卡片 -->
    <view class="status-card">
      <view class="order-number">
        <text class="number-label">订单号</text>
        <text class="number-value">{{ orderDetail.orderId }}</text>
      </view>
      <view class="status-row">
        <text 
          class="status-tag" 
          :class="getOrderStatusClass(orderDetail.orderStatus)"
          :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>
          <text class="item-value">{{ orderDetail.mobilePhone || '匿名用户' }}</text>
        </view>
        <view class="info-item">
          <text class="item-label">设备编号</text>
          <text class="item-value">{{ orderDetail.shortId || '未知设备' }}</text>
        </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-overlay" v-if="loading">
      <text class="loading-spinner">🔄</text>
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 空状态 -->
    <view class="empty-state" v-if="!loading && !orderDetail.id">
      <text class="empty-icon">📭</text>
      <text class="empty-text">订单不存在</text>
      <button class="refresh-btn" @click="loadOrderDetail">刷新</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, storage } from '../../utils/index.js'

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

// 获取订单状态文本
const getOrderStatusText = (status) => {
  if (!status) return '未知状态'
  
  try {
    const dicts = storage.get('dicts')
    if (!dicts || !dicts['Order.status']) {
      console.warn('字典数据未加载或不存在 Order.status')
      return status
    }
    
    const orderStatusDict = dicts['Order.status']
    const dictItem = orderStatusDict.find(item => item.value == status)
    
    return dictItem ? dictItem.name : status
  } catch (error) {
    console.error('获取订单状态文本失败:', error)
    return status
  }
}

// 获取支付状态文本
const getPayStatusText = (status) => {
  if (!status) return '未知状态'
  
  try {
    const dicts = storage.get('dicts')
    if (!dicts || !dicts['Order.pay']) {
      console.warn('字典数据未加载或不存在 Order.pay')
      return status
    }
    
    const payStatusDict = dicts['Order.pay']
    const dictItem = payStatusDict.find(item => item.value == status)
    
    return dictItem ? dictItem.name : status
  } catch (error) {
    console.error('获取支付状态文本失败:', error)
    return status
  }
}

// 获取关机方式文本
const getCloseTypeText = (type) => {
  if (!type) return '未知方式'
  
  try {
    const dicts = storage.get('dicts')
    if (!dicts || !dicts['Order.closeType']) {
      console.warn('字典数据未加载或不存在 Order.closeType')
      return type
    }
    
    const closeTypeDict = dicts['Order.closeType']
    const dictItem = closeTypeDict.find(item => item.value == type)
    
    return dictItem ? dictItem.name : type
  } catch (error) {
    console.error('获取关机方式文本失败:', error)
    return type
  }
}

// 获取发票状态文本
const getInvoiceStatusText = (status) => {
  if (!status) return '未开票'
  
  try {
    const dicts = storage.get('dicts')
    if (!dicts || !dicts['Invoice.status']) {
      console.warn('字典数据未加载或不存在 Invoice.status')
      return status
    }
    
    const invoiceStatusDict = dicts['Invoice.status']
    const dictItem = invoiceStatusDict.find(item => item.value == status)
    
    return dictItem ? dictItem.name : status
  } catch (error) {
    console.error('获取发票状态文本失败:', error)
    return status
  }
}

// 获取订单状态样式类
const getOrderStatusClass = (status) => {
  if (!status) return ''
  
  const statusClassMap = {
    '0': 'status-wait',        // 待支付
    '1': 'status-processing',  // 进行中
    '2': 'status-completed',   // 已完成
    '3': 'status-refunded',    // 已退款
    '4': 'status-refunding',   // 退款中
    '5': 'status-canceled'     // 已取消
  }
  return statusClassMap[status] || ''
}

// 获取订单状态样式
const getOrderStatusStyle = (status) => {
  if (!status) return {}
  
  try {
    const dicts = storage.get('dicts')
    if (!dicts || !dicts['Order.status']) {
      return {}
    }
    
    const orderStatusDict = dicts['Order.status']
    const dictItem = orderStatusDict.find(item => item.value == status)
    
    // 如果字典项有颜色，使用字典颜色
    if (dictItem && dictItem.color) {
      return {
        color: dictItem.color,
        backgroundColor: `${dictItem.color}1A` // 添加10%透明度
      }
    }
    
    return {}
  } catch (error) {
    console.error('获取订单状态样式失败:', error)
    return {}
  }
}

// 计算是否可以处理退款
const canHandleRefund = computed(() => {
  return orderDetail.value.orderStatus === '4' && orderDetail.value.refundLogId
})

// 加载订单详情
const loadOrderDetail = async () => {
  if (!orderId.value) {
    console.error('订单ID为空')
    showToast('订单ID不存在')
    loading.value = false
    return
  }
  
  console.log('正在加载订单详情，订单ID:', orderId.value)
  loading.value = true
  try {
    const res = await getOrderDetail(orderId.value)
    console.log('订单详情响应:', res)
    
    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 => {
            // 从字典中获取服务项目名称
            let serviceName = item.name
            try {
              const dicts = storage.get('dicts')
              if (dicts && dicts['Order.feeType']) {
                const feeTypeDict = dicts['Order.feeType']
                const dictItem = feeTypeDict.find(d => d.value == item.name)
                if (dictItem) {
                  serviceName = dictItem.name
                }
              }
            } catch (e) {
              console.error('解析服务项目字典失败:', e)
            }
            
            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(() => {
  // 获取页面参数
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const receivedOrderId = currentPage.options.orderId || ''
  
  console.log('订单详情页接收到的参数:', currentPage.options)
  console.log('订单ID:', receivedOrderId)
  
  if (!receivedOrderId) {
    console.error('未接收到订单ID')
    showToast('订单ID不存在，无法加载详情')
    loading.value = false
    return
  }
  
  orderId.value = receivedOrderId
  loadOrderDetail()
})
</script>

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

/* 顶部紫色导航栏 */
.header-nav {
  display: flex;
  align-items: center;
  padding-top: calc(24rpx + var(--status-bar-height));
  padding-right: 30rpx;
  padding-bottom: 24rpx;
  padding-left: 30rpx;
  background: linear-gradient(135deg, #667EEA 0%, #764BA2 100%);
  box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.2);
  position: relative;
  z-index: 10;
}

/* 确保内容不被导航栏遮挡 */
.status-card {
  margin-top: 40rpx;
}

.back-icon {
  font-size: 40rpx;
  color: #FFFFFF;
  font-weight: 600;
  margin-right: 16rpx;
}

.nav-title {
  font-size: 34rpx;
  color: #FFFFFF;
  font-weight: 600;
}

/* 订单号和状态卡片 */
.status-card {
  margin: 20rpx 30rpx;
  padding: 24rpx 30rpx;
  background: #FFFFFF;
  border-radius: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
}

.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: 22rpx;
  font-weight: 600;
  padding: 6rpx 20rpx;
  border-radius: 30rpx;
}

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

/* 信息卡片 */
.info-card,
.amount-card,
.service-card {
  margin: 20rpx 30rpx;
  background: #FFFFFF;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
}

.card-title {
  padding: 24rpx 30rpx 20rpx;
  font-size: 28rpx;
  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 #F8F9FA;
}

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

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

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

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

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

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

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

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

.amount-value.primary {
  font-size: 32rpx;
  color: #667EEA;
  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: 22rpx;
  color: #999999;
  font-weight: 600;
}

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

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

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

.col-name {
  flex: 1;
}

.col-time {
  width: 120rpx;
  text-align: center;
}

.col-price {
  width: 100rpx;
  text-align: center;
}

.col-amount {
  width: 100rpx;
  text-align: right;
  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: linear-gradient(90deg, #F5222D 0%, #FF4D4F 100%);
  color: #FFFFFF;
  border: none;
  border-radius: 16rpx;
  font-size: 30rpx;
  font-weight: 600;
  box-shadow: 0 6rpx 20rpx rgba(245, 34, 45, 0.35);
}

.refund-btn:active {
  transform: translateY(2rpx);
  opacity: 0.9;
}

/* 加载状态 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.4);
  backdrop-filter: blur(2px);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

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

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

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

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

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 32rpx;
  opacity: 0.5;
}

.empty-text {
  font-size: 28rpx;
  margin-bottom: 40rpx;
}

.refresh-btn {
  padding: 20rpx 60rpx;
  background: linear-gradient(90deg, #667EEA 0%, #764BA2 100%);
  color: #FFFFFF;
  border: none;
  border-radius: 16rpx;
  font-size: 28rpx;
  font-weight: 500;
}

.refresh-btn:active {
  transform: scale(0.95);
  opacity: 0.9;
}

/* 状态颜色 */
.status-wait {
  color: #FAAD14;
  background: linear-gradient(135deg, #FFF7E6 0%, #FFE7BA 100%);
}

.status-processing {
  color: #1890FF;
  background: linear-gradient(135deg, #E6F7FF 0%, #BAE7FF 100%);
}

.status-completed {
  color: #52C41A;
  background: linear-gradient(135deg, #F6FFED 0%, #D9F7BE 100%);
}

.status-refunded,
.status-canceled {
  color: #999999;
  background: linear-gradient(135deg, #F5F5F5 0%, #E0E0E0 100%);
}

.status-refunding {
  color: #F5222D;
  background: linear-gradient(135deg, #FFF1F0 0%, #FFCCC7 100%);
}
</style>
