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

    <!-- 订单完成内容 -->
    <view v-else-if="order" class="content">
      <!-- 绿色弧顶 -->
      <view class="arc-header">
        <view class="arc-bg" />
        <view class="arc-nav" />
      </view>

      <!-- 弧线下内容 -->
      <view class="body-content">
        <!-- 成功状态居中区 -->
        <view class="success-status">
          <!-- 成功图标 -->
          <view class="success-icon-wrapper">
            <view class="success-icon">
              <view class="check-stem" />
            </view>
          </view>
          <text class="success-title">已完成</text>
        </view>
        <!-- <text class="success-subtitle">计入按时支付记录</text> -->
        <!-- 商户信息 -->
        <view class="card merchant-card">
          <!-- <view class="merchant-header">
            <view class="merchant-icon-wrapper">
              <view class="merchant-icon">
                <text class="merchant-icon-text">柜</text>
              </view>
            </view>
            <text class="merchant-name">AI零售柜</text>
          </view> -->
          <view class="merchant-info-row">
            <text class="info-label">先享服务</text>
            <text class="info-value">自助先购后付</text>
          </view>
          <view class="merchant-info-row">
            <text class="info-label">服务信息</text>
            <text class="info-value">智慧零售</text>
          </view>
        </view>

        <!-- 商品清单 -->
        <view class="card products-card">
          <view class="card-header">
            <text class="card-title">商品信息</text>
          </view>
          <view class="product-list">
            <view v-for="(product, index) in order.products" :key="index" class="product-item">
              <text class="product-name">{{ product.name }}</text>
              <view class="product-right">
                <text class="product-qty">X{{ product.quantity }}</text>
                <text class="product-subtotal">¥{{ (product.price * product.quantity).toFixed(2) }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 总计支付 -->
        <view class="card total-card">
          <text class="total-label">总计支付</text>
          <view class="total-amount-wrapper">
            <text class="total-symbol">¥</text>
            <text class="total-amount">{{ (order.paidAmount || order.totalAmount || 0).toFixed(2) }}</text>
          </view>
        </view>

        <!-- 订单详情 -->
        <view class="card detail-card">
          <view class="detail-item">
            <text class="detail-label">付款方式</text>
            <text class="detail-value">{{ payMethodText }}</text>
          </view>
          <view class="detail-item" v-if="order.storeName">
            <text class="detail-label">服务地点</text>
            <text class="detail-value">{{ order.storeName }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">开始时间</text>
            <text class="detail-value">{{ formatTime(order.createTime) }}</text>
          </view>
          <view class="detail-item" v-if="order.payTime">
            <text class="detail-label">结束时间</text>
            <text class="detail-value">{{ formatTime(order.payTime) }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">服务单号</text>
            <text class="detail-value detail-code">{{ order.outTradeNo || order.orderNo }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">商户单号</text>
            <text class="detail-value detail-code">{{ order.orderNo }}</text>
          </view>
          <view class="detail-item detail-link-item" @click="goToOrderDetail">
            <text class="detail-label">交易账单</text>
            <view class="detail-link">
              <text class="link-text">详情</text>
              <text class="link-arrow">›</text>
            </view>
          </view>
        </view>

        <!-- 按时支付记录 -->
        <view class="card payment-record-card" @click="goToOrderDetail">
          <text class="payment-record-text">按时支付记录</text>
          <text class="payment-record-arrow">›</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { getOrderDetail } from '../../api/order';
import type { OrderInfo } from '../../api/order';
import { logger } from '../../utils/logger';

const order = ref<OrderInfo | null>(null);
const loading = ref(true);

const payMethodText = computed(() => {
  if (!order.value) return '自动扣费';
  const ch = order.value.payChannel;
  if (ch === 'wechat_payscore') return '微信支付分 · 服务结束后自动扣费';
  if (ch === 'wechat') return '微信支付';
  if (ch === 'alipay') return '支付宝';
  if (ch === 'balance') return '余额支付';
  return '自动扣费';
});

const formatTime = (time: string | undefined) => {
  if (!time) return '-';
  try {
    const d = new Date(time);
    if (isNaN(d.getTime())) {
      if (time.includes('-')) return time.replace('T', ' ').substring(0, 19);
      return time;
    }
    const pad = (n: number) => String(n).padStart(2, '0');
    return `${d.getFullYear()}/${pad(d.getMonth() + 1)}/${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
  } catch {
    return time;
  }
};

const loadOrderDetail = async (orderId: string) => {
  loading.value = true;
  try {
    uni.showLoading({ title: '加载中...', mask: true });
    const orderDetail = await getOrderDetail({ orderId });
    order.value = orderDetail;
    uni.hideLoading();
  } catch (error: any) {
    uni.hideLoading();
    logger.error('加载订单完成页失败:', error);
    order.value = {
      id: '0',
      orderNo: orderId,
      outTradeNo: 'TEST_OUT_TRADE_NO_123456',
      hahaOrderNo: '',
      deviceId: 'TEST_DEVICE_001',
      totalAmount: 18.50,
      paidAmount: 18.50,
      discountAmount: 0,
      payStatus: 'PAID',
      payChannel: 'wechat_payscore',
      status: 3,
      products: [
        { name: '芝士牛肉卷', quantity: 1, price: 12.50 },
        { name: '可乐330ml', quantity: 1, price: 6.00 }
      ],
      storeName: '人民广场旗舰店',
      createTime: new Date().toISOString(),
      payTime: new Date().toISOString()
    } as OrderInfo;
  } finally {
    loading.value = false;
  }
};

const goToOrderDetail = () => {
  if (!order.value) return;
  uni.navigateTo({
    url: '/pages/orderDetail/orderDetail?orderId=' + String(order.value.id)
  });
};

onLoad((options: any) => {
  const orderId = options?.orderNo || options?.orderId;
  if (orderId) {
    loadOrderDetail(orderId);
  } else {
    uni.showToast({ title: '订单信息不存在', icon: 'none' });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }
});
</script>

<style lang="scss">
$wechat-green: #07C160;

.container {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: env(safe-area-inset-bottom);
}

/* ========== 加载中 ========== */
.loading-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 600rpx;
  gap: 24rpx;
}

.loading-spinner {
  width: 48rpx;
  height: 48rpx;
  border: 4rpx solid #e0e0e0;
  border-top-color: $wechat-green;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

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

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

/* ========== 绿色弧顶 ========== */
.arc-header {
  position: relative;
  height: 180rpx;
  overflow: hidden;
  background: $wechat-green;
}

.arc-bg {
  position: absolute;
  bottom: -100rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 160%;
  height: 200rpx;
  border-radius: 50%;
  background: #f5f5f5;
}

.arc-nav {
  position: relative;
  z-index: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 88rpx;
  padding-top: env(safe-area-inset-top);
}

.arc-title {
  font-size: 34rpx;
  font-weight: 600;
  color: #fff;
}

/* ========== 弧线下内容 ========== */
.body-content {
  position: relative;
  z-index: 1;
  padding: 0 24rpx;
}

/* 成功状态 - 垂直居中 */
.success-status {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 160rpx;
  margin-top: -60rpx;
  padding: 0;
}

.success-icon-wrapper {
  display: flex;
  justify-content: center;
  margin-bottom: 16rpx;
  animation: successPop 0.5s cubic-bezier(0.34, 1.56, 0.64, 1);
}

.success-icon {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background: $wechat-green;
  display: flex;
  align-items: center;
  justify-content: center;
}

.check-stem {
  width: 24rpx;
  height: 48rpx;
  border-right: 6rpx solid #fff;
  border-bottom: 6rpx solid #fff;
  transform: rotate(45deg);
  margin-top: -6rpx;
}

@keyframes successPop {
  0% { transform: scale(0); opacity: 0; }
  60% { transform: scale(1.15); }
  100% { transform: scale(1); opacity: 1; }
}

.success-title {
  display: block;
  width: 100%;
  font-size: 40rpx;
  font-weight: 700;
  color: #1a1a1a;
  text-align: center;
  margin-bottom: 36rpx;
  letter-spacing: 2rpx;
}

.success-subtitle {
  font-size: 24rpx;
  color: #aaa;
  text-align: center;
  margin-bottom: 36rpx;
  letter-spacing: 1rpx;
}

/* ========== 通用卡片 ========== */
.card {
  background: #fff;
  border-radius: 16rpx;
  padding: 28rpx;
  margin-bottom: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
}

/* ========== 商户卡片 ========== */
.merchant-header {
  display: flex;
  align-items: center;
  gap: 16rpx;
  margin-bottom: 20rpx;
}

.merchant-icon-wrapper {
  margin-right: 16rpx;
}

.merchant-icon {
  width: 48rpx;
  height: 48rpx;
  border-radius: 50%;
  background: #FF9800;
  display: flex;
  align-items: center;
  justify-content: center;
}

.merchant-icon-text {
  font-size: 24rpx;
  color: #fff;
  font-weight: 600;
}

.merchant-name {
  font-size: 32rpx;
  font-weight: 700;
  color: #1a1a1a;
}

.merchant-info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12rpx 0;
}

.info-label {
  font-size: 26rpx;
  color: #999;
}

.info-value {
  font-size: 26rpx;
  color: #333;
}

/* ========== 商品卡片 ========== */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.card-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #1a1a1a;
}

.card-count {
  font-size: 24rpx;
  color: #999;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 12rpx 0;
}

.product-name {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 16rpx;
}

.product-right {
  display: flex;
  align-items: center;
  flex-shrink: 0;
}

.product-qty {
  font-size: 26rpx;
  color: #999;
  margin-right: 24rpx;
}

.product-subtotal {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  min-width: 120rpx;
  text-align: right;
}

/* ========== 总计支付卡片 ========== */
.total-card {
  display: flex;
  justify-content: space-between;
  align-items: baseline;
}

.total-label {
  font-size: 30rpx;
  color: #666;
}

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

.total-symbol {
  font-size: 32rpx;
  color: #1a1a1a;
  font-weight: 700;
  margin-right: 4rpx;
}

.total-amount {
  font-size: 56rpx;
  color: #1a1a1a;
  font-weight: 800;
}

/* ========== 详情卡片 ========== */
.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18rpx 0;

  &:not(:last-child) {
    border-bottom: 1rpx solid #f8f8f8;
  }
}

.detail-label {
  font-size: 26rpx;
  color: #999;
  flex-shrink: 0;
  margin-right: 24rpx;
}

.detail-value {
  font-size: 26rpx;
  color: #333;
  text-align: right;
  word-break: break-all;
}

.detail-code {
  font-size: 22rpx;
  color: #666;
  max-width: 380rpx;
  font-family: monospace;
}

.detail-link-item {
  &:active {
    opacity: 0.6;
  }
}

.detail-link {
  display: flex;
  align-items: center;
  gap: 4rpx;
}

.link-text {
  font-size: 26rpx;
  color: $wechat-green;
}

.link-arrow {
  font-size: 32rpx;
  color: $wechat-green;
  font-weight: 300;
}

/* ========== 按时支付记录卡片 ========== */
.payment-record-card {
  display: flex;
  justify-content: space-between;
  align-items: center;

  &:active {
    opacity: 0.7;
  }
}

.payment-record-text {
  font-size: 28rpx;
  color: #333;
}

.payment-record-arrow {
  font-size: 32rpx;
  color: #ccc;
  font-weight: 300;
}
</style>
