<template>
  <view class="page">
    <!-- 黄色导航栏 -->
    <NavBar :title="navTitle" :showBack="true" />

    <!-- 加载状态 -->
    <view class="load-tip" v-if="!order">
      <view class="dot-row">
        <view class="pulse-dot"></view>
        <view class="pulse-dot"></view>
        <view class="pulse-dot"></view>
      </view>
    </view>

    <scroll-view class="detail-scroll" scroll-y v-if="order">
      <!-- 状态区域 -->
      <view class="status-section">
        <view class="status-row">
          <view class="status-tag" :class="getPayStatusClass(order.payStatus)">
            <text>{{ order.payStatusLabel || getPayStatusText(order.payStatus) }}</text>
          </view>
          <text class="order-no-text">订单{{ order.orderNo }}</text>
        </view>
        <text class="status-desc" :class="getPayStatusClass(order.payStatus)">
          {{ getStatusDesc(order.status, order.payStatus) }}
        </text>
      </view>

      <!-- 视频区域 -->
      <view class="video-section" v-if="order.videoUrl">
        <video class="order-video" :src="order.videoUrl" controls></video>
      </view>

      <!-- 订单明细 -->
      <view class="section">
        <text class="section-title">订单明细</text>
        <view class="product-list" v-if="order.products && order.products.length > 0">
          <view class="product-item" v-for="item in order.products" :key="item.productId">
            <image
              class="product-img"
              :src="item.pic || '/static/images/default-product.png'"
              mode="aspectFill"
            />
            <view class="product-main">
              <text class="product-name">{{ item.productName }}</text>
              <text class="product-meta">数量 x{{ item.productNum }}</text>
              <text class="product-meta">单价 ¥{{ formatMoney(item.price) }}</text>
            </view>
            <view class="product-right">
              <text class="deal-price">¥{{ formatMoney(item.price * item.productNum) }}</text>
            </view>
          </view>
        </view>
        <view class="product-empty" v-else>
          <text>暂无商品明细</text>
        </view>
        <view class="amount-row">
          <text class="amount-label">实付款</text>
          <text class="amount-value">¥{{ formatMoney(order.paidAmount) }}</text>
        </view>
      </view>

      <!-- 订单信息 -->
      <view class="section">
        <text class="section-title">订单信息</text>
        <view class="info-row">
          <text class="info-label">订单编号</text>
          <view class="info-value-row">
            <text class="info-value">{{ order.orderNo }}</text>
            <view class="copy-btn" @click="copyText(order.orderNo)">
              <text class="copy-btn-text">复制</text>
            </view>
          </view>
        </view>
        <view class="info-row">
          <text class="info-label">下单时间</text>
          <text class="info-value">{{ order.createTime || '-' }}</text>
        </view>
        <view class="info-row" v-if="order.payTime">
          <text class="info-label">支付时间</text>
          <text class="info-value">{{ order.payTime }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">门店名称</text>
          <text class="info-value">{{ order.shopName || '-' }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">设备名称</text>
          <text class="info-value">{{ order.deviceName || '-' }}</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.deviceAddress">
          <text class="info-label">设备地址</text>
          <text class="info-value">{{ order.deviceAddress }}</text>
        </view>
        <view class="info-row" v-if="order.phone">
          <text class="info-label">联系消费者</text>
          <view class="info-value-row">
            <text class="info-value">{{ formatPhone(order.phone) }}</text>
            <view class="action-btn call-btn" @click="callPhone(order.phone)">
              <text class="action-btn-text">呼叫</text>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部操作 -->
    <view class="bottom-bar" v-if="order && canRefund(order)">
      <view class="refund-btn" @click="handleRefund">
        <text class="refund-btn-text">退款</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import NavBar from '@/components/NavBar.vue';
import { getOrderDetail, handleRefund as refundOrder } from '@/api/order';
import { formatMoney as formatMoneyUtil, formatPhone as formatPhoneUtil, showToast, showConfirm } from '@/utils/common';

interface OrderProduct {
  productId: string;
  productName: string;
  productNum: number;
  price: number;
  pic?: string;
}

interface OrderDetail {
  id: string;
  orderNo: string;
  status: number;
  payStatus: string;
  payStatusLabel?: string;
  paidAmount: number;
  createTime: string;
  payTime?: string;
  shopName?: string;
  deviceId?: string;
  deviceName?: string;
  deviceAddress?: string;
  phone?: string;
  videoUrl?: string;
  products?: OrderProduct[];
}

const order = ref<OrderDetail | null>(null);
const formatMoney = formatMoneyUtil;
const formatPhone = formatPhoneUtil;

const navTitle = computed(() => {
  return `${order.value?.deviceId || '订单'}-订单详情`;
});

const getPayStatusText = (payStatus: string): string => {
  const map: Record<string, string> = {
    'UNPAID': '未支付',
    'PAID': '已支付',
    'REFUND': '已退款'
  };
  return map[payStatus] || '未知';
};

const getPayStatusClass = (payStatus: string): 'success' | 'danger' | 'warning' => {
  if (payStatus === 'PAID') return 'success';
  if (payStatus === 'REFUND') return 'danger';
  return 'warning';
};

const getStatusDesc = (status: number, payStatus: string): string => {
  if (payStatus === 'PAID') return '交易成功';
  if (payStatus === 'REFUND') return '已退款';
  if (status === 1) return '等待支付';
  if (status === 0) return '已取消';
  if (status === 3) return '已关闭';
  return '';
};

const canRefund = (o: OrderDetail): boolean => {
  return o.payStatus === 'PAID' && o.status === 2;
};

const copyText = (text: string) => {
  if (!text) {
    showToast('无内容可复制');
    return;
  }
  uni.setClipboardData({
    data: text,
    success: () => showToast('已复制', 'success')
  });
};

const callPhone = (phone: string) => {
  uni.makePhoneCall({ phoneNumber: phone });
};

const loadDetail = async (id?: string) => {
  if (!id) {
    showToast('订单ID不存在');
    return;
  }
  try {
    order.value = await getOrderDetail(id);
  } catch {
    showToast('加载订单详情失败');
  }
};

const handleRefund = async () => {
  if (!order.value) return;
  const confirmed = await showConfirm('确认对该订单进行退款操作？');
  if (!confirmed) return;
  try {
    await refundOrder(order.value.id, '商家申请退款');
    showToast('退款处理成功', 'success');
    setTimeout(() => {
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1] as { options?: Record<string, string> };
      loadDetail(currentPage?.options?.id);
    }, 1000);
  } catch {
    showToast('退款处理失败');
  }
};

onLoad((options?: Record<string, string>) => {
  loadDetail(options?.id);
});
</script>

<style lang="scss" scoped>
$font-stack: -apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', system-ui, sans-serif;

.page {
  height: 100vh;
  background: $bg-color-page;
  display: flex;
  flex-direction: column;
  font-family: $font-stack;
  overflow-x: hidden;
}

.detail-scroll {
  flex: 1;
  height: 0;
  padding-bottom: 140rpx;
}

// ====== Loading ======
.load-tip {
  display: flex;
  justify-content: center;
  padding: 120rpx 0;
}

.dot-row {
  display: flex;
  gap: 8rpx;
}

.pulse-dot {
  width: 9rpx; height: 9rpx;
  background: $text-color-placeholder;
  border-radius: 50%;
  animation: pulse 1.2s ease-in-out infinite;
  &:nth-child(2) { animation-delay: 0.2s; }
  &:nth-child(3) { animation-delay: 0.4s; }
}

@keyframes pulse {
  0%, 80%, 100% { transform: scale(0.5); opacity: 0.4; }
  40% { transform: scale(1); opacity: 1; }
}

// ====== Status section ======
.status-section {
  background: $bg-color-card;
  padding: $spacing-3 $spacing-4;
  margin-bottom: $spacing-2;

  .status-row {
    display: flex;
    align-items: center;
    margin-bottom: $spacing-1;

    .status-tag {
      padding: 4rpx $spacing-2;
      border-radius: $radius-sm;
      font-size: $font-size-sm;
      font-weight: 500;
      margin-right: $spacing-2;

      &.success {
        background: $success-color-bg;
        color: $success-color;
      }

      &.danger {
        background: $error-color-bg;
        color: $error-color;
      }

      &.warning {
        background: $warning-color-bg;
        color: $warning-color;
      }
    }

    .order-no-text {
      font-size: $font-size-md;
      font-weight: 600;
      color: $text-color-primary;
    }
  }

  .status-desc {
    font-size: 26rpx;

    &.success { color: $success-color; }
    &.danger { color: $error-color; }
    &.warning { color: $warning-color; }
  }
}

// ====== Video ======
.video-section {
  background: $bg-color-card;
  padding: 20rpx $spacing-4;
  margin-bottom: $spacing-2;

  .order-video {
    width: 100%;
    height: 400rpx;
    border-radius: $radius-base;
    background: $bg-color-secondary;
  }
}

// ====== Section card ======
.section {
  background: $bg-color-card;
  margin-bottom: $spacing-2;
  padding: $spacing-3 $spacing-4;

  .section-title {
    display: block;
    font-size: $font-size-md;
    font-weight: 600;
    color: $text-color-primary;
    margin-bottom: $spacing-2;
  }
}

// ====== Product list ======
.product-list {
  .product-item {
    display: flex;
    align-items: flex-start;
    padding: $spacing-2 0;
    border-bottom: 1rpx solid $border-color-light;

    &:last-child {
      border-bottom: none;
    }

    .product-img {
      width: 120rpx;
      height: 120rpx;
      border-radius: $radius-sm;
      background: $bg-color-page;
      margin-right: 20rpx;
      flex-shrink: 0;
    }

    .product-main {
      flex: 1;

      .product-name {
        display: block;
        font-size: $font-size-base;
        color: $text-color-primary;
        margin-bottom: $spacing-1;
      }

      .product-meta {
        display: block;
        font-size: $font-size-sm;
        color: $text-color-muted;
        margin-bottom: 4rpx;
      }
    }

    .product-right {
      display: flex;
      align-items: flex-end;

      .deal-price {
        font-size: $font-size-sm;
        color: $text-color-muted;
      }
    }
  }
}

.product-empty {
  padding: $spacing-5 0;
  text-align: center;
  font-size: $font-size-sm;
  color: $text-color-placeholder;
}

.amount-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: $spacing-2 0 0;
  border-top: 1rpx solid $border-color-light;
  margin-top: $spacing-2;

  .amount-label {
    font-size: $font-size-base;
    color: $text-color-secondary;
  }

  .amount-value {
    font-size: $font-size-lg;
    font-weight: 700;
    color: $text-color-primary;
  }
}

// ====== Info rows ======
.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: $spacing-3 0;
  border-bottom: 1rpx solid $border-color-light;

  &:last-child {
    border-bottom: none;
  }

  .info-label {
    font-size: $font-size-base;
    color: $text-color-muted;
    flex-shrink: 0;
  }

  .info-value {
    font-size: $font-size-base;
    color: $text-color-primary;
    text-align: right;
  }

  .info-value-row {
    display: flex;
    align-items: center;
    gap: $spacing-2;
  }
}

// ====== Action buttons ======
.copy-btn, .action-btn {
  padding: 8rpx $spacing-3;
  border-radius: $radius-sm;
  flex-shrink: 0;

  &:active { opacity: 0.7; }
}

.copy-btn {
  background: $bg-color-page;

  .copy-btn-text {
    font-size: $font-size-xs;
    color: $text-color-secondary;
  }
}

.action-btn {
  .action-btn-text {
    font-size: $font-size-xs;
    font-weight: 500;
  }
}

.call-btn {
  background: $primary-color-bg;

  .action-btn-text {
    color: $primary-color-dark;
  }
}

// ====== Bottom bar ======
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: $bg-color-card;
  padding: $spacing-3 $spacing-4;
  padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
  border-top: 1rpx solid $border-color-light;
  flex-shrink: 0;

  .refund-btn {
    width: 100%;
    background: $primary-color;
    border-radius: $radius-xl;
    padding: 28rpx 0;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: opacity 0.15s ease;

    &:active { opacity: 0.8; }

    .refund-btn-text {
      font-size: $font-size-lg;
      font-weight: 600;
      color: $text-color-primary;
    }
  }
}
</style>

