<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" lazy-load></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 v-if="order.discountAmount && order.discountAmount > 0" class="amount-row discount-row">
          <text class="amount-label">优惠金额</text>
          <view class="amount-value-wrapper">
            <text class="amount-prefix">-¥</text>
            <text class="amount-discount">{{ order.discountAmount.toFixed(2) }}</text>
          </view>
        </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.paidAmount || order.totalAmount || 0).toFixed(2) }}</text>
          </view>
        </view>

        <!-- 退款历史记录 -->
        <view v-if="order.refunds && order.refunds.length > 0" class="refund-history">
          <view class="history-title">退款记录</view>
          <view v-for="(record, index) in order.refunds" :key="index" class="history-item">
            <view class="history-timeline">
              <view :class="['timeline-dot', record.status === 'REFUNDED' ? 'success' : record.status === 'REJECTED' ? 'rejected' : 'pending']"></view>
              <view v-if="index < order.refunds.length - 1" class="timeline-line"></view>
            </view>
            <view class="history-content">
              <view class="history-header">
                <text :class="['history-status', record.status === 'REFUNDED' ? 'success' : record.status === 'REJECTED' ? 'rejected' : 'pending']">
                  {{ record.status === 'REFUNDED' ? '已退款' : record.status === 'REJECTED' ? '已拒绝' : '审核中' }}
                </text>
                <text class="history-amount">¥{{ (record.refundAmount || 0).toFixed(2) }}</text>
              </view>
              <view class="history-meta">
                <text class="history-time">{{ record.createTime }}</text>
              </view>
              <text v-if="record.reason" class="history-reason">原因：{{ record.reason }}</text>
              <text v-if="record.remark && record.status === 'REJECTED'" class="history-reject-reason">拒绝原因：{{ record.remark }}</text>
              <!-- 退款商品 -->
              <view v-if="record.items && record.items.length > 0" class="history-items">
                <view v-for="(item, i) in record.items" :key="i" class="history-item-row">
                  <text class="item-name">{{ item.productName }}</text>
                  <text class="item-meta">×{{ item.quantity }} ¥{{ (item.refundAmount || 0).toFixed(2) }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>

        <view class="card-footer-actions">
          <button v-if="canRefund(order) && order.refundStatus !== 'PENDING'" class="action-btn-outline" @click="applyRefund">申请退款</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" v-if="order.orderName">
            <text class="info-label">订单名称</text>
            <text class="info-value">{{ order.orderName }}</text>
          </view>
          <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 v-if="order.payScoreOrderId" class="info-row">
            <text class="info-label">支付详情</text>
            <view class="info-link" @click="viewPayDetail">
              <text class="link-text">查看详情</text>
              <text class="link-arrow" />
            </view>
          </view>
          <view class="info-row" v-if="order.storeName">
            <text class="info-label">门店</text>
            <text class="info-value">{{ order.storeName }}</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">
      <CustomerServiceButton
        mode="link"
        :title="'订单 ' + (order?.orderNo || '')"
        :path="'/pages/orderDetail/orderDetail?orderId=' + String(order?.id || '')"
      >
        <text>如有疑问，请联系客服</text>
      </CustomerServiceButton>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { getOrderDetail } from '../../api/order';
import type { OrderInfo } from '../../api/order';
import { getPayscoreDetailSign } from '../../api/payscore';
import { checkAuth } from '../../utils/auth';
import { getStatusText, canRefund } from '../../utils/order';
import { logger } from '../../utils/logger';

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

const getStatusClass = (status: number) => {
  if (status === 1) return 'status-success';
  if (status === 0) return 'status-pending';
  if (status === 2) return 'status-cancelled';
  return '';
};

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: '加载中...' });
    const orderDetail = await getOrderDetail({ orderId: orderId.value });
    order.value = orderDetail;
    uni.hideLoading();
  } catch (error: any) {
    uni.hideLoading();
    logger.error('加载订单详情失败:', error);
    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 = String(options.orderId);
    loadOrderDetail();
  } else {
    uni.showToast({ title: '订单ID不存在', icon: 'none' });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }
});

// 从退款页返回时刷新退款状态
onShow(() => {
  if (orderId.value) {
    loadOrderDetail();
  }
});

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

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

const viewVideo = (url: string) => {
  uni.showToast({ title: '视频播放功能开发中', icon: 'none' });
};

const viewPayDetail = async () => {
  if (!order.value?.payScoreOrderId) return;

  try {
    uni.showLoading({ title: '加载中...' });
    const signData = await getPayscoreDetailSign({ outOrderNo: order.value.payScoreOrderId });
    uni.hideLoading();

    wx.openBusinessView({
      businessType: 'wxpayScoreDetail',
      extraData: {
        mch_id: signData.mchId,
        service_id: signData.serviceId,
        out_order_no: signData.outOrderNo,
        timestamp: signData.timestamp,
        nonce_str: signData.nonceStr,
        sign_type: signData.signType,
        sign: signData.sign,
      },
      success: () => {
        logger.log('[订单详情] 支付分订单详情页返回');
      },
      fail: (err: any) => {
        logger.error('[订单详情] openBusinessView fail:', err);
        const errMsg = err?.errMsg || '';
        if (!errMsg.includes('cancel')) {
          uni.showToast({ title: '打开支付详情失败', icon: 'none' });
        }
      },
    });
  } catch (error: any) {
    uni.hideLoading();
    logger.error('[订单详情] 获取支付分签名失败:', error);
    uni.showToast({ title: error?.message || '获取支付详情失败', icon: 'none' });
  }
};
</script>

<style scoped lang="scss">
.container {
  min-height: 100vh;
  background: linear-gradient(180deg, $color-primary-bg 0%, $color-bg-secondary 30%);
  padding: 24rpx;
  box-sizing: border-box;
}

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

/* 通用卡片样式 */
.card {
  background-color: $color-bg-primary;
  border-radius: $radius-lg;
  padding: 32rpx;
  margin-bottom: 24rpx;
  box-shadow: $shadow-md;
}

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

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

.status-icon-wrapper {
  width: 56rpx;
  height: 56rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;

  &.status-success {
    background: linear-gradient(135deg, $color-success, #43A047);
    box-shadow: 0 4rpx 12rpx rgba(76, 175, 80, 0.3);
  }

  &.status-pending {
    background: linear-gradient(135deg, $color-warning, #F57C00);
    box-shadow: 0 4rpx 12rpx rgba(255, 152, 0, 0.3);
  }

  &.status-cancelled {
    background: linear-gradient(135deg, $color-text-secondary, #9E9E9E);
    box-shadow: 0 4rpx 12rpx rgba(140, 140, 140, 0.3);
  }
}

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

.status-text {
  font-size: 34rpx;
  color: $color-text-primary;
  font-weight: 700;
}

.invoice-status {
  font-size: 24rpx;
  color: $color-error;
  padding: 6rpx 16rpx;
  background: rgba(244, 67, 54, 0.06);
  border-radius: 12rpx;
}

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

.card-header {
  padding: 32rpx;
  border-bottom: 1rpx solid $color-bg-secondary;
}

.card-title {
  font-size: 32rpx;
  font-weight: 700;
  color: $color-text-primary;
}

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

  &:active {
    background: $color-bg-secondary;
  }
}

.product-image {
  width: 140rpx;
  height: 140rpx;
  background: $color-bg-tertiary;
  border-radius: $radius-md;
  margin-right: 24rpx;
  overflow: hidden;

  image {
    width: 100%;
    height: 100%;
    border-radius: $radius-md;
  }
}

.image-placeholder {
  width: 100%;
  height: 100%;
  background: $color-bg-tertiary;
  border-radius: $radius-md;
  display: flex;
  align-items: center;
  justify-content: center;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 30rpx;
  color: $color-text-primary;
  font-weight: 600;
  margin-bottom: 16rpx;
  display: block;
  line-height: 1.5;
}

.product-price {
  font-size: 26rpx;
  color: $color-text-secondary;
}

.product-quantity {
  font-size: 26rpx;
  color: $color-text-tertiary;
  margin-top: 60rpx;
  font-weight: 500;
}

.amount-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx;
  border-top: 1rpx solid $color-bg-secondary;
  background: $color-bg-primary;
}

.discount-row {
  background: rgba(76, 175, 80, 0.04);
  border-top: none;
  padding: 24rpx 32rpx;
}

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

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

.amount-prefix {
  font-size: 26rpx;
  color: $color-text-secondary;
  margin-right: 10rpx;
}

.amount-symbol {
  font-size: 28rpx;
  color: $color-warning;
  font-weight: 700;
}

.amount-integer {
  font-size: 40rpx;
  color: $color-warning;
  font-weight: 800;
}

.amount-discount {
  font-size: 32rpx;
  color: $color-success;
  font-weight: 700;
}

.refund-notice {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin: 0 $spacing-lg $spacing-xs;
  padding: 20rpx $spacing-md;
  border-radius: $radius-md;
  font-size: 26rpx;
  line-height: 1.5;

  .notice-dot {
    width: 14rpx;
    height: 14rpx;
    border-radius: 50%;
    flex-shrink: 0;
  }

  .notice-amount {
    font-weight: 700;
  }

  &.pending {
    background-color: $color-primary-bg;
    color: $color-primary-dark;

    .notice-dot {
      background-color: $color-warning;
      animation: notice-dot-pulse 1.5s ease-in-out infinite;
    }
  }

  &.partial {
    background-color: #E3F2FD;
    color: #1565C0;

    .notice-dot {
      background-color: $color-info;
    }
  }

  &.full {
    background-color: #E8F5E9;
    color: #2E7D32;

    .notice-dot {
      background-color: $color-success;
    }
  }
}

@keyframes notice-dot-pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.4; }
}

.card-footer-actions {
  display: flex;
  justify-content: flex-end;
  padding: 24rpx 32rpx 32rpx;
  gap: 16rpx;
}

.action-btn-outline {
  background-color: $color-bg-primary;
  border: 2rpx solid $color-border;
  border-radius: $radius-xl;
  font-size: 26rpx;
  color: $color-text-secondary;
  margin: 0;
  padding: 16rpx 32rpx;
  line-height: 1;

  &::after {
    border: none;
  }

  &:active {
    transform: scale(0.95);
    background-color: $color-bg-secondary;
  }
}

/* 退款历史记录 */
.refund-history {
  padding: 0 $spacing-lg;
  margin-bottom: $spacing-md;
}

.history-title {
  font-size: 28rpx;
  font-weight: 600;
  color: $color-text-primary;
  margin-bottom: $spacing-md;
}

.history-item {
  display: flex;
  gap: $spacing-md;

  &:last-child .timeline-line {
    display: none;
  }
}

.history-timeline {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 40rpx;
  flex-shrink: 0;
}

.timeline-dot {
  width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
  margin-top: 6rpx;
  flex-shrink: 0;

  &.success { background-color: $color-success; }
  &.rejected { background-color: $color-error; }
  &.pending { background-color: $color-warning; }
}

.timeline-line {
  width: 2rpx;
  flex: 1;
  min-height: 30rpx;
  background-color: $color-border;
  margin: 8rpx 0;
}

.history-content {
  flex: 1;
  padding-bottom: $spacing-md;
  min-width: 0;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6rpx;
}

.history-status {
  font-size: 26rpx;
  font-weight: 500;

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

.history-amount {
  font-size: 28rpx;
  font-weight: 700;
  color: $color-text-primary;
}

.history-meta {
  margin-bottom: 4rpx;
}

.history-time {
  font-size: 22rpx;
  color: $color-text-tertiary;
}

.history-reason {
  display: block;
  font-size: 24rpx;
  color: $color-text-secondary;
  margin-top: 6rpx;
  line-height: 1.5;
}

.history-reject-reason {
  display: block;
  font-size: 24rpx;
  color: $color-error;
  margin-top: 6rpx;
  line-height: 1.5;
}

.history-items {
  margin-top: 12rpx;
  padding: 16rpx;
  background-color: $color-bg-secondary;
  border-radius: $radius-sm;
}

.history-item-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6rpx 0;

  .item-name {
    font-size: 24rpx;
    color: $color-text-primary;
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .item-meta {
    font-size: 24rpx;
    color: $color-text-secondary;
    flex-shrink: 0;
    margin-left: 16rpx;
  }
}

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

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

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 28rpx 0;
  border-bottom: 1rpx solid $color-bg-secondary;

  &:active {
    background: $color-bg-secondary;
  }

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

.info-label {
  font-size: 28rpx;
  color: $color-text-secondary;
}

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

.info-value {
  font-size: 28rpx;
  color: $color-text-primary;
  font-weight: 500;
}

.copy-btn {
  margin-left: 12rpx;
  padding: 8rpx;

  &:active {
    transform: scale(0.9);
  }
}

.copy-icon-box {
  width: 28rpx;
  height: 32rpx;
  border: 3rpx solid $color-text-secondary;
  position: relative;
  border-radius: 4rpx;

  &::after {
    content: '';
    position: absolute;
    width: 20rpx;
    height: 24rpx;
    border: 3rpx solid $color-text-secondary;
    background-color: $color-bg-primary;
    top: -8rpx;
    right: -8rpx;
    border-radius: 4rpx;
  }
}

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

  &:active {
    opacity: 0.6;
  }
}

.link-text {
  font-size: 28rpx;
  color: $color-warning;
  font-weight: 600;
  margin-right: 6rpx;
}

.link-arrow {
  font-size: 28rpx;
  color: $color-primary-dark;

  &::after {
    content: '>';
  }
}

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

  text {
    font-size: 24rpx;
    color: $color-text-tertiary;
  }
}
</style>
