<template>
  <view class="page-settlement-detail">
    <!-- 导航栏 -->
    <view class="navbar">
      <view class="navbar-left" @tap="goBack">
        <u-icon name="arrow-left" :size="20" color="#1A1A1A" />
      </view>
      <text class="navbar-title">结算详情</text>
      <view class="navbar-right"></view>
    </view>

    <scroll-view v-if="!loading && settlement" scroll-y class="detail-content">
      <!-- 结算信息卡片 -->
      <view class="info-card">
        <view class="card-header">
          <text class="period-text">{{ formatPeriod(settlement.startDate, settlement.endDate) }}</text>
          <view :class="['status-badge', `status-${settlement.status}`]">
            <text class="status-text">{{ getStatusLabel(settlement.status) }}</text>
          </view>
        </view>

        <view class="amount-section">
          <text class="amount-label">结算金额（元）</text>
          <text class="amount-value">¥{{ formatMoney(settlement.settlementAmount) }}</text>
        </view>

        <view class="stats-grid">
          <view class="grid-item">
            <text class="grid-label">订单数</text>
            <text class="grid-value">{{ settlement.orderCount }}</text>
          </view>
          <view class="grid-item">
            <text class="grid-label">订单总额</text>
            <text class="grid-value">¥{{ formatMoney(settlement.totalAmount) }}</text>
          </view>
          <view class="grid-item">
            <text class="grid-label">服务费</text>
            <text class="grid-value fee">-¥{{ formatMoney(settlement.serviceFee) }}</text>
          </view>
          <view class="grid-item">
            <text class="grid-label">服务费率</text>
            <text class="grid-value">{{ settlement.serviceFeeRate }}%</text>
          </view>
        </view>

        <view v-if="settlement.settledAt" class="time-info">
          <text class="time-label">结算时间</text>
          <text class="time-value">{{ formatDateTime(settlement.settledAt) }}</text>
        </view>
      </view>

      <!-- 订单明细 -->
      <view class="orders-section">
        <view class="section-header">
          <text class="section-title">订单明细</text>
          <text class="section-count">共{{ items.length }}笔</text>
        </view>

        <view v-if="items.length > 0" class="orders-list">
          <view
            v-for="item in items"
            :key="item.id"
            class="order-item"
            @tap="goOrderDetail(item.orderNo)"
          >
            <view class="order-header">
              <text class="order-no">订单号: {{ item.orderNo }}</text>
              <u-icon name="arrow-right" :size="14" color="#CCCCCC" />
            </view>
            <view class="order-info">
              <text class="order-room">{{ item.roomTitle }}</text>
              <text class="order-time">{{ formatDate(item.orderCreatedAt) }}</text>
            </view>
            <view class="order-footer">
              <view class="footer-left">
                <text class="footer-label">订单金额</text>
                <text class="footer-value">¥{{ formatMoney(item.orderAmount) }}</text>
              </view>
              <view class="footer-right">
                <text class="footer-label">服务费</text>
                <text class="footer-value fee">-¥{{ formatMoney(item.serviceFee) }}</text>
              </view>
              <view class="footer-right">
                <text class="footer-label">实收</text>
                <text class="footer-value highlight">¥{{ formatMoney(item.settlementAmount) }}</text>
              </view>
            </view>
          </view>
        </view>

        <view v-else class="empty-orders">
          <text class="empty-text">暂无订单明细</text>
        </view>
      </view>

      <!-- 底部占位 -->
      <view class="bottom-placeholder"></view>
    </scroll-view>

    <!-- 加载状态 -->
    <view v-else class="loading-state">
      <view class="loading-spinner">
        <view class="spinner-dot"></view>
        <view class="spinner-dot"></view>
        <view class="spinner-dot"></view>
      </view>
      <text class="loading-text">加载中...</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { financeApi } from '@/api/seller/finance';

const loading = ref(true);
const settlement = ref<any>(null);
const items = ref<any[]>([]);
const settlementId = ref<number>(0);

onMounted(() => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1] as any;
  settlementId.value = Number(currentPage.options?.id || 0);

  if (settlementId.value) {
    fetchDetail();
  } else {
    uni.showToast({ title: '参数错误', icon: 'none' });
    setTimeout(() => uni.navigateBack(), 1500);
  }
});

async function fetchDetail() {
  loading.value = true;
  try {
    const [detailRes, itemsRes] = await Promise.all([
      financeApi.getSettlementDetail(settlementId.value),
      financeApi.getSettlementItems(settlementId.value),
    ]);
    settlement.value = detailRes.data;
    items.value = itemsRes.data.items || [];
  } catch (e: any) {
    console.error('获取结算详情失败:', e);
    uni.showToast({ title: e.message || '加载失败', icon: 'none' });
  } finally {
    loading.value = false;
  }
}

function getStatusLabel(status: string): string {
  const statusMap: Record<string, string> = {
    pending: '待结算',
    completed: '已结算',
  };
  return statusMap[status] || status;
}

function formatPeriod(startDate: string, endDate: string): string {
  if (!startDate || !endDate) return '';
  const start = new Date(startDate);
  const end = new Date(endDate);
  return `${start.getFullYear()}/${start.getMonth() + 1}/${start.getDate()} - ${end.getMonth() + 1}/${end.getDate()}`;
}

function formatDate(dateStr: string): string {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
}

function formatDateTime(dateStr: string): string {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
}

function formatMoney(value: number | string): string {
  const num = Number(value || 0);
  return num.toFixed(2);
}

function goOrderDetail(orderNo: string) {
  uni.navigateTo({ url: `/pages/order-detail/index?orderNo=${orderNo}` });
}

function goBack() {
  uni.navigateBack();
}
</script>

<style lang="scss" scoped>
.page-settlement-detail {
  min-height: 100vh;
  background: #F5F7FA;
  display: flex;
  flex-direction: column;
}

/* 导航栏 */
.navbar {
  background: #ffffff;
  padding: 0 24rpx;
  border-bottom: 1rpx solid #F0F0F0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
}

.navbar-left,
.navbar-right {
  width: 80rpx;
  display: flex;
  align-items: center;
}

.navbar-left {
  justify-content: flex-start;
  padding: 12rpx;
  margin-left: -12rpx;
  transition: opacity 0.3s ease;

  &:active {
    opacity: 0.6;
  }
}

.navbar-title {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  font-weight: 600;
  color: #1A1A1A;
}

/* 详情内容 */
.detail-content {
  flex: 1;
  overflow-y: auto;
}

/* 结算信息卡片 */
.info-card {
  margin: 24rpx 24rpx 16rpx;
  padding: 32rpx;
  background: #ffffff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
}

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

.period-text {
  font-size: 28rpx;
  font-weight: 600;
  color: #1A1A1A;
}

.status-badge {
  padding: 6rpx 16rpx;
  border-radius: 16rpx;

  &.status-pending {
    background: #FFF7E6;
  }

  &.status-completed {
    background: #F6FFED;
  }
}

.status-text {
  font-size: 24rpx;

  .status-pending & {
    color: #FAAD14;
  }

  .status-completed & {
    color: #52C41A;
  }
}

.amount-section {
  padding: 32rpx 0;
  border-top: 1rpx solid #F0F0F0;
  border-bottom: 1rpx solid #F0F0F0;
  margin-bottom: 24rpx;
  text-align: center;
}

.amount-label {
  display: block;
  font-size: 26rpx;
  color: #999;
  margin-bottom: 12rpx;
}

.amount-value {
  display: block;
  font-size: 48rpx;
  font-weight: 700;
  color: #FF6B35;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24rpx;
  margin-bottom: 24rpx;
}

.grid-item {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.grid-label {
  font-size: 24rpx;
  color: #999;
}

.grid-value {
  font-size: 28rpx;
  font-weight: 600;
  color: #1A1A1A;

  &.fee {
    color: #FF6B35;
  }
}

.time-info {
  padding-top: 24rpx;
  border-top: 1rpx solid #F0F0F0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.time-label {
  font-size: 26rpx;
  color: #666;
}

.time-value {
  font-size: 26rpx;
  color: #1A1A1A;
}

/* 订单明细 */
.orders-section {
  margin: 0 24rpx 16rpx;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 0 16rpx;
}

.section-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #1A1A1A;
}

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

.orders-list {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.order-item {
  padding: 24rpx;
  background: #ffffff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.98);
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
  }
}

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

.order-no {
  font-size: 24rpx;
  color: #999;
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
  margin-bottom: 16rpx;
}

.order-room {
  font-size: 28rpx;
  font-weight: 600;
  color: #1A1A1A;
}

.order-time {
  font-size: 24rpx;
  color: #999;
}

.order-footer {
  display: flex;
  padding-top: 16rpx;
  border-top: 1rpx solid #F0F0F0;
}

.footer-left,
.footer-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.footer-label {
  font-size: 22rpx;
  color: #999;
}

.footer-value {
  font-size: 26rpx;
  font-weight: 600;
  color: #1A1A1A;

  &.fee {
    color: #FF6B35;
  }

  &.highlight {
    color: #52C41A;
  }
}

.empty-orders {
  padding: 80rpx 0;
  text-align: center;
}

.empty-text {
  font-size: 26rpx;
  color: #999;
}

/* 底部占位 */
.bottom-placeholder {
  height: 40rpx;
}

/* 加载状态 */
.loading-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 16rpx;
  padding: 120rpx 0;
}

.loading-spinner {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.spinner-dot {
  width: 12rpx;
  height: 12rpx;
  background: #FF6B35;
  border-radius: 50%;
  animation: bounce 1.4s infinite ease-in-out both;

  &:nth-child(1) {
    animation-delay: -0.32s;
  }

  &:nth-child(2) {
    animation-delay: -0.16s;
  }
}

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

.loading-text {
  font-size: 24rpx;
  color: #999;
}
</style>
