<template>
  <view class="details-container">
    <!-- 订单状态卡片 -->
    <view class="status-card">
      <view class="status-icon" :class="orderStatusClass"></view>
      <view class="status-text">{{ orderStatusText }}</view>
      <view class="status-desc">{{ orderStatusDesc }}</view>
    </view>
    
    <!-- 订单信息卡片 -->
    <view class="info-card">
      <view class="card-title">订单信息</view>
      <view class="info-item">
        <text class="label">订单号</text>
        <text class="value">{{ orderInfo.orderNo || '-' }}</text>
      </view>
      <view class="info-item">
        <text class="label">设备号</text>
        <text class="value">{{ orderInfo.deviceNo || '-' }}</text>
      </view>
      <view class="info-item">
        <text class="label">租借方式</text>
        <view class="value payment-method">
          <!-- <text>{{ paymentMethod }}</text> -->
          
          <!-- 支付方式标识 -->
          <view class="payment-badge wx-score" v-if="orderInfo.payWay === 'wx_score_pay'">
            <image src="/static/images/wxpayflag.png" mode="aspectFit" class="badge-icon"></image>
            <view class="badge-text">
              <text>微信支付分</text>
              <text class="divider">|</text>
              <text class="highlight">免押租借</text>
            </view>
          </view>
          <!-- 押金租借标识 -->
          <view class="payment-badge deposit" v-else>
            <text class="badge-text">押金租借</text>
          </view>
        </view>
      </view>
      
      <view class="info-item">
        <text class="label">创建时间</text>
        <text class="value">{{ orderInfo.createTime || '-' }}</text>
      </view>
      <view class="info-item">
        <text class="label">开始时间</text>
        <text class="value">{{ orderInfo.startTime || '-' }}</text>
      </view>
      <view class="info-item" v-if="orderInfo.endTime">
        <text class="label">结束时间</text>
        <text class="value">{{ orderInfo.endTime }}</text>
      </view>
      <view class="info-item" v-if="orderInfo.phone">
        <text class="label">联系电话</text>
        <text class="value">{{ orderInfo.phone }}</text>
      </view>
    </view>
    
    <!-- 费用信息卡片 -->
    <view class="info-card">
      <view class="card-title">费用信息</view>
      <view class="info-item" v-if="orderInfo.depositAmount">
        <text class="label">押金</text>
        <text class="value">￥{{ orderInfo.depositAmount }}</text>
      </view>
      <view class="info-item" v-if="orderInfo.packageTime && orderInfo.packagePrice">
        <text class="label">套餐</text>
        <text class="value">￥{{ orderInfo.packagePrice }}元 / {{ formatTime(orderInfo.packageTime) }}</text>
      </view>
      <view class="info-item total">
        <text class="label">合计</text>
        <text class="value">￥{{ orderInfo.payAmount || 0 }}</text>
      </view>
    </view>
    
    <!-- 操作按钮 -->
    <view class="action-buttons" v-if="orderInfo.orderStatus === 'waiting_for_payment'">
      <view class="btn cancel" @click="handleCancelOrder">取消订单</view>
      <view class="btn primary" @click="handlePayment">立即支付</view>
    </view>
    
    <view class="action-buttons" v-else-if="orderInfo.orderStatus === 'in_used'">
      <view class="btn primary" @click="navigateToReturn">归还设备</view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { queryById, cancelOrder, confirmPaymentAndRent } from '@/config/user.js';

const orderId = ref('');
const orderInfo = ref({});

// 状态计算属性
const orderStatusText = computed(() => {
  const status = orderInfo.value.orderStatus;
  switch(status) {
    case 'waiting_for_payment': return '等待支付';
    case 'in_used': return '使用中';
    case 'used_done': return '已完成';
    case 'order_cancelled': return '已取消';
    default: return '未知状态';
  }
});

const orderStatusClass = computed(() => {
  const status = orderInfo.value.orderStatus;
  switch(status) {
    case 'waiting_for_payment': return 'status-waiting';
    case 'in_used': return 'status-using';
    case 'used_done': return 'status-finished';
    case 'order_cancelled': return 'status-cancelled';
    default: return '';
  }
});

const orderStatusDesc = computed(() => {
  const status = orderInfo.value.orderStatus;
  switch(status) {
    case 'waiting_for_payment': return '请在15分钟内完成支付';
    case 'in_used': return '设备正在使用中';
    case 'used_done': return '感谢您的使用';
    case 'order_cancelled': return '该订单已取消';
    default: return '';
  }
});

const paymentMethod = computed(() => {
  const payWay = orderInfo.value.payWay;
  if (payWay === 'wx_score_pay') {
    return '微信支付分 (免押金)';
  } else if (payWay === 'wx_pay') {
    return '微信支付';
  } else {
    return '押金支付';
  }
});

// 页面加载
onLoad(async (options) => {
  if (options && options.orderId) {
    orderId.value = options.orderId;
    await loadOrderDetails();
  } else {
    uni.showToast({
      title: '订单信息不存在',
      icon: 'none'
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }
});

// 加载订单详情
const loadOrderDetails = async () => {
  try {
    uni.showLoading({
      title: '加载中'
    });
    
    const res = await queryById(orderId.value);
    if (res.code === 200 && res.data) {
      orderInfo.value = res.data;
      
      // 格式化时间
      if (orderInfo.value.createTime) {
        orderInfo.value.createTime = formatDateTime(new Date(orderInfo.value.createTime));
      }
      if (orderInfo.value.startTime) {
        orderInfo.value.startTime = formatDateTime(new Date(orderInfo.value.startTime));
      }
      if (orderInfo.value.endTime) {
        orderInfo.value.endTime = formatDateTime(new Date(orderInfo.value.endTime));
      }
    } else {
      throw new Error('获取订单详情失败');
    }
    
    uni.hideLoading();
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: error.message || '获取订单详情失败',
      icon: 'none'
    });
  }
};

// 格式化时间
const formatDateTime = (date) => {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hour = date.getHours().toString().padStart(2, '0');
  const minute = date.getMinutes().toString().padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}`;
};

// 格式化套餐时间
const formatTime = (minutes) => {
  if (!minutes) return '';
  
  const mins = parseInt(minutes);
  if (mins < 60) {
    return `${mins}分钟`;
  } else {
    const hours = Math.floor(mins / 60);
    const remainingMins = mins % 60;
    return remainingMins > 0 ? `${hours}小时${remainingMins}分钟` : `${hours}小时`;
  }
};

// 取消订单
const handleCancelOrder = () => {
  uni.showModal({
    title: '确认取消',
    content: '确定要取消此订单吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: '处理中' });
          
          const result = await cancelOrder({
            orderId: orderId.value
          });
          
          if (result.code === 200) {
            uni.hideLoading();
            uni.showToast({
              title: '订单已取消',
              icon: 'success'
            });
            
            // 重新加载订单详情
            await loadOrderDetails();
          } else {
            throw new Error(result.msg || '取消订单失败');
          }
        } catch (error) {
          uni.hideLoading();
          uni.showToast({
            title: error.message || '取消订单失败',
            icon: 'none'
          });
        }
      }
    }
  });
};

// 立即支付
const handlePayment = async () => {
  try {
    uni.showLoading({
      title: '处理中'
    });
    
    const res = await confirmPaymentAndRent(orderId.value);
    if (res.code === 200) {
      uni.hideLoading();
      uni.showToast({
        title: '支付成功',
        icon: 'success'
      });
      
      // 重新加载订单详情
      await loadOrderDetails();
    } else {
      throw new Error(res.msg || '支付失败');
    }
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: error.message || '支付失败',
      icon: 'none'
    });
  }
};

// 跳转到归还页面
const navigateToReturn = () => {
  uni.navigateTo({
    url: `/pages/return/index?deviceId=${orderInfo.value.deviceNo}&orderId=${orderId.value}`
  });
};
</script>

<style lang="scss" scoped>
.details-container {
  min-height: 100vh;
  background: #f7f8fa;
  padding: 30rpx;
  padding-bottom: 100rpx;
  box-sizing: border-box;
  
  // 状态卡片
  .status-card {
    background: #fff;
    border-radius: 20rpx;
    padding: 40rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 30rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
    
    .status-icon {
      width: 120rpx;
      height: 120rpx;
      border-radius: 50%;
      margin-bottom: 20rpx;
      
      &.status-waiting {
        background: #FFF9C4;
      }
      
      &.status-using {
        background: #E8F5E9;
      }
      
      &.status-finished {
        background: #E3F2FD;
      }
      
      &.status-cancelled {
        background: #FFEBEE;
      }
    }
    
    .status-text {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 10rpx;
    }
    
    .status-desc {
      font-size: 28rpx;
      color: #999;
    }
  }
  
  // 信息卡片
  .info-card {
    background: #fff;
    border-radius: 20rpx;
    padding: 30rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
    
    .card-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 20rpx;
      position: relative;
      padding-left: 20rpx;
      
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 8rpx;
        height: 32rpx;
        background: #1976D2;
        border-radius: 4rpx;
      }
    }
    
    .info-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx 0;
      border-bottom: 1px solid #f5f5f5;
      
      &:last-child {
        border-bottom: none;
      }
      
      .label {
        font-size: 28rpx;
        color: #666;
      }
      
      .value {
        font-size: 28rpx;
        color: #333;
        word-break: break-all;
        text-align: right;
        max-width: 70%;
        
        &.payment-method {
          display: flex;
          flex-direction: column;
          align-items: flex-end;
          
          .payment-badge {
            margin-top: 8rpx;
            display: flex;
            align-items: center;
            padding: 4rpx 10rpx;
            border-radius: 8rpx;
            
            &.wx-score {
              background: rgba(7, 193, 96, 0.08);
              
              .badge-icon {
                width: 32rpx;
                height: 26rpx;
                margin-right: 8rpx;
              }
              
              .badge-text {
                font-size: 22rpx;
                color: #07c160;
                display: flex;
                align-items: center;
                
                .divider {
                  margin: 0 6rpx;
                }
                
                .highlight {
                  font-weight: 500;
                }
              }
            }
            
            &.deposit {
              background: #f5f5f5;
              
              .badge-text {
                font-size: 22rpx;
                color: #666;
                font-weight: 500;
              }
            }
          }
        }
      }
      
      &.total {
        margin-top: 10rpx;
        padding-top: 30rpx;
        border-top: 1px solid #f5f5f5;
        
        .label, .value {
          font-size: 32rpx;
          font-weight: 600;
          color: #333;
        }
        
        .value {
          color: #FF5722;
        }
      }
    }
  }
  
  // 操作按钮
  .action-buttons {
    display: flex;
    justify-content: space-between;
    padding: 30rpx 0;
    
    .btn {
      flex: 1;
      height: 88rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 32rpx;
      font-weight: 500;
      border-radius: 44rpx;
      
      &.cancel {
        background: #f5f5f5;
        color: #666;
        margin-right: 20rpx;
      }
      
      &.primary {
        background: #1976D2;
        color: #fff;
      }
      
      &:active {
        opacity: 0.9;
      }
    }
  }
}
</style> 