<template>
  <view class="container">
    <!-- 加载中 -->
    <view v-if="loading" class="loading-wrapper">
      <text>加载中...</text>
    </view>

    <!-- 订单详情 -->
    <view v-else-if="order">
      <!-- 订单状态 -->
      <view class="card status-card">
        <view class="status-left">
          <view class="status-icon-wrapper" :class="getStatusClass(order.status)">
            <text class="status-icon">✓</text>
          </view>
          <text class="status-text">{{ order.statusText || getStatusText(order.status) }}</text>
        </view>
        <text class="invoice-status">未开票</text>
      </view>

      <!-- 订单明细 -->
      <view class="card detail-card">
        <view class="card-header">
          <text class="card-title">订单明细</text>
        </view>

        <!-- 商品列表 -->
        <view v-for="(product, index) in order.products" :key="index" class="product-item">
          <view class="product-image">
            <image v-if="product.image" :src="product.image" mode="aspectFill"></image>
            <view v-else class="image-placeholder"></view>
          </view>
          <view class="product-info">
            <text class="product-name">{{ product.name }}</text>
            <text class="product-price">销售单价 ¥{{ product.price.toFixed(2) }}</text>
          </view>
          <text class="product-quantity">x{{ product.quantity }}</text>
        </view>

        <!-- 总价 -->
        <view class="amount-row">
          <text class="amount-label">实付款</text>
          <view class="amount-value-wrapper">
            <text class="amount-prefix">合计</text>
            <text class="amount-symbol">¥</text>
            <text class="amount-integer">{{ order.totalAmount.toFixed(2) }}</text>
          </view>
        </view>

        <!-- 操作按钮 -->
        <view class="card-footer-actions">
          <button v-if="canRefund(order)" class="action-btn-outline" @click="applyRefund">申请退款</button>
          <button class="action-btn-primary" @click="printOrder">打印订单</button>
          <button class="action-btn-primary" @click="exportImage">导出图片</button>
        </view>
      </view>

      <!-- 订单信息 -->
      <view class="card info-card">
        <view class="card-header">
          <text class="card-title">订单信息</text>
        </view>
        <view class="info-list">
          <view class="info-row">
            <text class="info-label">订单编号</text>
            <view class="info-value-group">
              <text class="info-value">{{ order.orderNo }}</text>
              <view class="copy-btn" @click="copyText(order.orderNo)">
                <view class="copy-icon-box"></view>
              </view>
            </view>
          </view>
          <view class="info-row" v-if="order.hahaOrderNo">
            <text class="info-label">哈哈订单号</text>
            <view class="info-value-group">
              <text class="info-value">{{ order.hahaOrderNo }}</text>
              <view class="copy-btn" @click="copyText(order.hahaOrderNo)">
                <view class="copy-icon-box"></view>
              </view>
            </view>
          </view>
          <view class="info-row">
            <text class="info-label">下单时间</text>
            <text class="info-value">{{ formatTime(order.createTime) }}</text>
          </view>
          <view class="info-row" v-if="order.payTime">
            <text class="info-label">支付时间</text>
            <text class="info-value">{{ formatTime(order.payTime) }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">支付方式</text>
            <text class="info-value">微信</text>
          </view>
          <view class="info-row">
            <text class="info-label">设备编号</text>
            <text class="info-value">{{ order.deviceId }}</text>
          </view>
          <view class="info-row" v-if="order.confidence">
            <text class="info-label">AI识别置信度</text>
            <text class="info-value">{{ (order.confidence * 100).toFixed(1) }}%</text>
          </view>
          <view class="info-row" v-if="order.videoUrl">
            <text class="info-label">识别视频</text>
            <view class="info-link" @click="viewVideo(order.videoUrl)">
              <text class="link-text">查看视频</text>
              <text class="link-arrow">></text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部提示 -->
    <view class="footer-note">
      <text>如有疑问，请联系客服</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { getOrderDetail } from '../../api/order';
import type { OrderInfo } from '../../api/order';
import { checkAuth } from '../../utils/auth';

const order = ref<OrderInfo | null>(null);
const loading = ref(false);
const orderId = ref<number | null>(null);

/**
 * 获取订单状态文本
 */
const getStatusText = (status: number) => {
  const statusMap: any = {
    0: '待支付',
    1: '已完成',
    2: '已取消'
  };
  return statusMap[status] || '未知';
};

/**
 * 获取状态样式
 */
const getStatusClass = (status: number) => {
  if (status === 1) return 'status-success';
  if (status === 0) return 'status-pending';
  if (status === 2) return 'status-cancelled';
  return '';
};

/**
 * 判断是否可以退款
 */
const canRefund = (order: OrderInfo) => {
  return order.status === 1; // 只有已完成的订单可以退款
};

/**
 * 格式化时间
 */
const formatTime = (time: string | undefined) => {
  if (!time) return '-';
  // 如果已经是格式化的时间字符串，直接返回
  if (typeof time === 'string' && time.includes('-')) {
    return time.replace('T', ' ').substring(0, 19);
  }
  return time;
};

/**
 * 加载订单详情
 */
const loadOrderDetail = async () => {
  if (!orderId.value) {
    uni.showToast({
      title: '订单ID不存在',
      icon: 'none'
    });
    return;
  }

  loading.value = true;

  try {
    uni.showLoading({
      title: '加载中...',
      mask: true
    });

    // 调用真实接口获取订单详情
    const orderDetail = await getOrderDetail({ orderId: orderId.value });
    order.value = orderDetail;

    uni.hideLoading();
  } catch (error: any) {
    uni.hideLoading();
    console.error('加载订单详情失败:', error);
    // 错误已在request工具中显示
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  } finally {
    loading.value = false;
  }
};

/**
 * 页面加载时检查登录状态并获取订单详情
 */
onMounted(() => {
  // 检查登录状态
  if (!checkAuth()) {
    return;
  }

  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1] as any;
  const options = currentPage.options || {};

  if (options.orderId) {
    orderId.value = parseInt(options.orderId);
    loadOrderDetail();
  } else {
    uni.showToast({
      title: '订单ID不存在',
      icon: 'none'
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }
});

/**
 * 申请退款
 */
const applyRefund = () => {
  if (!order.value) return;
  uni.navigateTo({
    url: '/pages/refund/refund?orderId=' + order.value.id
  });
};

/**
 * 打印订单
 */
const printOrder = () => {
  uni.showToast({
    title: '打印订单功能开发中',
    icon: 'none'
  });
};

/**
 * 导出图片
 */
const exportImage = () => {
  uni.showToast({
    title: '导出图片功能开发中',
    icon: 'none'
  });
};

/**
 * 复制文本
 */
const copyText = (text: string) => {
  uni.setClipboardData({
    data: text,
    success: () => {
      uni.showToast({
        title: '复制成功',
        icon: 'success'
      });
    }
  });
};

/**
 * 查看视频
 */
const viewVideo = (url: string) => {
  // TODO: 实现视频播放功能
  uni.showToast({
    title: '视频播放功能开发中',
    icon: 'none'
  });
};
</script>

<style>
.container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding: 20rpx;
  box-sizing: border-box;
}

.loading-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 400rpx;
  font-size: 28rpx;
  color: #999;
}

/* 通用卡片样式 */
.card {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

/* 订单状态卡片 */
.status-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-left {
  display: flex;
  align-items: center;
}

.status-icon-wrapper {
  width: 44rpx;
  height: 44rpx;
  background-color: #7ED321;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16rpx;
}

.status-icon-wrapper.status-success {
  background-color: #7ED321;
}

.status-icon-wrapper.status-pending {
  background-color: #FF9100;
}

.status-icon-wrapper.status-cancelled {
  background-color: #999999;
}

.status-icon {
  color: #ffffff;
  font-size: 28rpx;
  font-weight: bold;
}

.status-text {
  font-size: 32rpx;
  color: #333333;
  font-weight: 500;
}

.invoice-status {
  font-size: 28rpx;
  color: #FF6B6B;
}

/* 订单明细卡片 */
.detail-card {
  padding: 0;
  overflow: hidden;
}

.card-header {
  padding: 30rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.product-item {
  display: flex;
  padding: 30rpx;
  align-items: flex-start;
}

.product-image {
  width: 140rpx;
  height: 140rpx;
  background-color: #f9f9f9;
  border-radius: 8rpx;
  margin-right: 20rpx;
  border: 1rpx solid #eeeeee;
}

.product-image image {
  width: 100%;
  height: 100%;
  border-radius: 8rpx;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 30rpx;
  color: #333333;
  margin-bottom: 16rpx;
  display: block;
}

.product-price {
  font-size: 26rpx;
  color: #999999;
}

.product-quantity {
  font-size: 26rpx;
  color: #999999;
  margin-top: 60rpx;
}

.amount-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-top: 1rpx solid #f5f5f5;
}

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

.amount-value-wrapper {
  display: flex;
  align-items: baseline;
}

.amount-prefix {
  font-size: 26rpx;
  color: #333333;
  margin-right: 10rpx;
}

.amount-symbol {
  font-size: 26rpx;
  color: #333333;
  font-weight: bold;
}

.amount-integer {
  font-size: 36rpx;
  color: #333333;
  font-weight: bold;
}

.card-footer-actions {
  display: flex;
  justify-content: flex-end;
  padding: 20rpx 30rpx 30rpx;
}

.action-btn-outline {
  background-color: #f8f8f8;
  border: 1rpx solid #e0e0e0;
  border-radius: 12rpx;
  font-size: 26rpx;
  color: #666666;
  margin: 0 0 0 20rpx;
  padding: 10rpx 24rpx;
  line-height: 1.5;
}

.action-btn-outline::after {
  border: none;
}

.action-btn-primary {
  background-color: #FFD200;
  border-radius: 12rpx;
  font-size: 26rpx;
  color: #333333;
  margin: 0 0 0 20rpx;
  padding: 10rpx 24rpx;
  line-height: 1.5;
  font-weight: 500;
}

.action-btn-primary::after {
  border: none;
}

/* 订单信息卡片 */
.info-card {
  padding: 0;
}

.info-list {
  padding: 10rpx 30rpx 30rpx;
}

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

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

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

.info-value-group {
  display: flex;
  align-items: center;
}

.info-value {
  font-size: 28rpx;
  color: #333333;
}

.copy-btn {
  margin-left: 10rpx;
  padding: 4rpx;
}

.copy-icon-box {
  width: 28rpx;
  height: 32rpx;
  border: 3rpx solid #999999;
  position: relative;
  border-radius: 4rpx;
}

.copy-icon-box::after {
  content: '';
  position: absolute;
  width: 20rpx;
  height: 24rpx;
  border: 3rpx solid #999999;
  background-color: #ffffff;
  top: -8rpx;
  right: -8rpx;
  border-radius: 4rpx;
}

.info-link {
  display: flex;
  align-items: center;
}

.link-text {
  font-size: 28rpx;
  color: #999999;
  margin-right: 6rpx;
}

.link-arrow {
  font-size: 28rpx;
  color: #cccccc;
}

/* 底部提示 */
.footer-note {
  text-align: center;
  padding: 40rpx 0;
}

.footer-note text {
  font-size: 26rpx;
  color: #cccccc;
}
</style>
