<template>
  <view class="earnings-container">
    <!-- 顶部导航栏 -->
    <view class="page-header">
      <!-- 左上角：返回主页按钮（箭头+文字 垂直排列） -->
      <view class="nav-left" @click="goBackToHome">
        <text class="nav-icon">←</text>
        <text class="nav-title">返回上一页</text>
      </view>

      <!-- 页面标题居中 -->
      <text class="page-title">收入明细</text>

      <!-- 右上角留空 -->
      <view class="nav-right"></view>
    </view>
  
    <!-- 顶部统计卡片 -->
    <view class="stats-section">
      <view class="stat-card">
        <text class="stat-value">¥{{ totalEarnings }}</text>
        <text class="stat-label">总收入</text>
      </view>
      <view class="stat-card">
        <text class="stat-value">¥{{ totalUserTips }}</text>
        <text class="stat-label">用户打赏</text>
      </view>
      <view class="stat-card">
        <text class="stat-value">¥{{ totalMerchantTips }}</text>
        <text class="stat-label">商家打赏</text>
      </view>
      <view class="stat-card">
        <text class="stat-value">{{ totalOrders }}</text>
        <text class="stat-label">总订单数</text>
      </view>
    </view>
  
    <!-- 主要内容区域 -->
    <view class="content-wrapper">
      <!-- 订单收入列表 -->
      <view v-if="orderEarningsList.length > 0" class="order-earnings-list">
        <view v-for="order in orderEarningsList" :key="order.order_no" class="order-earnings-item">
          <!-- 订单总收入 -->
          <view class="order-total">
            <text class="order-total-label">订单收入：</text>
            <text class="order-total-amount">¥{{ order.totalAmount.toFixed(2) }}</text>
          </view>
  
          <!-- 订单基础信息 -->
          <view class="order-info">
            <text class="info-item">订单号: {{ order.order_no }}</text>
            <text class="info-item">时间: {{ formatTime(order.date) }}</text>
            <text class="info-item" v-if="order.distance !== undefined">距离: {{ order.distance }}km</text>
          </view>
  
          <!-- 收入明细 -->
          <view class="earning-details">
            <view v-for="detail in order.details" :key="detail.id" class="detail-item">
              <text class="detail-type">{{ getSourceText(detail.source) }}</text>
              <text class="detail-amount">+¥{{ detail.amount.toFixed(2) }}</text>
            </view>
          </view>
        </view>
      </view>
  
      <!-- 无数据时显示 -->
      <view v-else class="no-data">
        <text class="no-data-text">暂无收入记录</text>
      </view>
  
      <!-- 加载更多按钮 -->
      <view v-if="hasMore" class="load-more">
        <button @click="loadMoreEarnings" class="load-more-btn">加载更多</button>
      </view>
    </view>
  </view>
</template>

<script lang="uts">
export default {
  data() {
    return {
      // 统计数据
      totalEarnings: '266.10',
      totalUserTips: '12.00',
      totalMerchantTips: '8.50',
      totalOrders: 8,

      // 按订单聚合后的收入数据
      orderEarningsList: [] as Array<OrderEarningType>,
      allOrderEarnings: [] as Array<OrderEarningType>,
      pageSize: 10,
      currentPage: 1,
    }
  },

  onLoad() {
    this.loadAllEarnings()
  },

  computed: {
    hasMore(): boolean {
      return this.allOrderEarnings.length > this.orderEarningsList.length
    }
  },

  methods: {
    // 加载所有收入明细并按订单聚合
    loadAllEarnings() {
      const rawEarnings = [
        // 配送费
        {
          id: '1',
          date: '2025-01-08T14:30:00Z',
          amount: 8.5,
          source: 'delivery_fee',
          order_no: 'D202501081234',
          distance: 12.5
        },
        {
          id: '2',
          date: '2025-01-08T15:00:00Z',
          amount: 12.0,
          source: 'delivery_fee',
          order_no: 'D202501081235',
          distance: 8.2
        },
        // 用户打赏
        {
          id: '3',
          date: '2025-01-08T15:30:00Z',
          amount: 5.0,
          source: 'user_tip',
          order_no: 'D202501081236'
        },
        {
          id: '4',
          date: '2025-01-08T16:00:00Z',
          amount: 7.0,
          source: 'user_tip',
          order_no: 'D202501081237'
        },
        // 商家打赏
        {
          id: '5',
          date: '2025-01-08T16:30:00Z',
          amount: 3.5,
          source: 'merchant_tip',
          order_no: 'D202501081238'
        },
        {
          id: '6',
          date: '2025-01-08T17:00:00Z',
          amount: 5.0,
          source: 'merchant_tip',
          order_no: 'D202501081239'
        },
        {
          id: '7',
          date: '2025-01-08T17:30:00Z',
          amount: 6.0,
          source: 'delivery_fee',
          order_no: 'D202501081240',
          distance: 3.5
        },
        {
          id: '8',
          date: '2025-01-08T18:00:00Z',
          amount: 10.0,
          source: 'user_tip',
          order_no: 'D202501081241'
        },
        {
          id: '9',
          date: '2025-01-08T18:30:00Z',
          amount: 8.5,
          source: 'merchant_tip',
          order_no: 'D202501081242'
        },
        {
          id: '10',
          date: '2025-01-08T19:00:00Z',
          amount: 12.0,
          source: 'delivery_fee',
          order_no: 'D202501081243',
          distance: 5.0
        },
        {
          id: '11',
          date: '2025-01-08T19:30:00Z',
          amount: 5.0,
          source: 'user_tip',
          order_no: 'D202501081244'
        },
        {
          id: '12',
          date: '2025-01-08T20:00:00Z',
          amount: 3.5,
          source: 'merchant_tip',
          order_no: 'D202501081245'
        }
      ]

      // 按订单号聚合数据
      const orderMap = new Map<string, OrderEarningType>()
        rawEarnings.forEach(item => {
          if (!orderMap.has(item.order_no)) {
            orderMap.set(item.order_no, {
              order_no: item.order_no,
              date: item.date,
              distance: item.distance,
              totalAmount: 0,
              details: []
            })
          }
          const order = orderMap.get(item.order_no)!
          order.totalAmount += item.amount
          order.details.push(item)
        })
      
        /* ---------- 新增：把「配送费」「商家打赏」「用户打赏」三种类型全部补齐 ---------- */
        const allTypes: Array<'delivery_fee' | 'merchant_tip' | 'user_tip'> = ['delivery_fee', 'merchant_tip', 'user_tip']
        orderMap.forEach(order => {
          // 看当前订单已存在的类型
          const existSet = new Set(order.details.map(d => d.source))
          // 缺哪种就补 0 的占位，保证顺序：配送费 / 商家打赏 / 用户打赏
          allTypes.forEach(type => {
            if (!existSet.has(type)) {
              order.details.push({
                id: `${order.order_no}_${type}`,   // 唯一 key
                date: order.date,
                amount: 0,
                source: type,
                order_no: order.order_no,
                distance: order.distance
              })
            }
          })
          // 按固定顺序排个序（可选）
          order.details.sort((a, b) =>
            allTypes.indexOf(a.source as any) - allTypes.indexOf(b.source as any)
          )
        })

      this.allOrderEarnings = Array.from(orderMap.values())
      this.calculateTotalStats()
      this.loadPage()
    },

    // 计算总统计数据
    calculateTotalStats() {
      let totalEarnings = 0
      let totalUserTips = 0
      let totalMerchantTips = 0

      this.allOrderEarnings.forEach(order => {
        order.details.forEach(detail => {
          totalEarnings += detail.amount || 0
          if (detail.source === 'user_tip') {
            totalUserTips += detail.amount || 0
          } else if (detail.source === 'merchant_tip') {
            totalMerchantTips += detail.amount || 0
          }
        })
      })

      this.totalEarnings = totalEarnings.toFixed(2)
      this.totalUserTips = totalUserTips.toFixed(2)
      this.totalMerchantTips = totalMerchantTips.toFixed(2)
      this.totalOrders = this.allOrderEarnings.length
    },

    // 加载当前页数据
    loadPage() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      const newOrders = this.allOrderEarnings.slice(start, end)
      this.orderEarningsList.push(...newOrders)
    },

    // 加载更多
    loadMoreEarnings() {
      this.currentPage++
      this.loadPage()
    },

    // 获取收入来源文本
    getSourceText(source: string): string {
      switch (source) {
        case 'delivery_fee': return '配送费'
        case 'user_tip': return '用户打赏'
        case 'merchant_tip': return '商家打赏'
        default: return '其他'
      }
    },

    // 格式化时间
    formatTime(timeStr: string): string {
      const date = new Date(timeStr)
      const now = new Date()
      const diff = now.getTime() - date.getTime()
      const minutes = Math.floor(diff / (1000 * 60))
      
      if (minutes < 60) {
        return `${minutes}分钟前`
      } else {
        return `${Math.floor(minutes / 60)}小时前`
      }
    },

    // 返回到来源页面
    goBackToHome() {
      uni.navigateBack()
    }
  }
}

// 定义聚合后的订单收入类型
type OrderEarningType = {
  order_no: string
  date: string
  distance?: number
  totalAmount: number
  details: Array<EarningType>
}

type EarningType = {
  id: string
  date: string
  amount?: number
  source: 'delivery_fee' | 'user_tip' | 'merchant_tip' | string
  order_no?: string
  distance?: number
}
</script>

<style scoped>
/* 全局样式 */
.earnings-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 20rpx 30rpx;
}

.page-header {
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #e9ecef;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  position: relative;
  min-height: 80rpx; /* 确保有足够空间放垂直排列的按钮和标题 */
}

.nav-left {
  position: absolute;
  top: 20rpx;
  left: 30rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
}

.nav-icon {
  font-size: 36rpx;
  margin-right: 10rpx;
  color: #333;
}

.nav-title {
  font-size: 28rpx;
  color: #000000; /* 红色 */
  font-weight: 500;
}

.page-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333; /* 黑色 */
  text-align: center;
  margin-top: 20rpx; /* 与 nav-left 保持一定距离 */
}

.nav-right {
  /* 为了保持左右对齐，右侧需要一个占位元素 */
  width: 1rpx;
  height: 1rpx;
}

.stats-section {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
  margin: 20rpx;
  padding: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.stat-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 12rpx;
}

.stat-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #4CAF50;
  margin-bottom: 10rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #666;
  text-align: center;
}

.content-wrapper {
  margin-top: 20rpx;
}

.order-earnings-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.order-earnings-item {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  border-left: 6rpx solid #4CAF50;
}

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

.order-total-label {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
}

.order-total-amount {
  font-size: 32rpx;
  font-weight: bold;
  color: #4CAF50;
}

.order-info {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 10rpx;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 15rpx;
  padding-bottom: 10rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.info-item {
  flex: 1 1 45%;
  min-width: 120rpx;
  word-break: break-all;
}

.earning-details {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8rpx 12rpx;
  border-radius: 8rpx;
  background-color: #f8f9fa;
}

.detail-type {
  font-size: 24rpx;
  color: #555;
}

.detail-amount {
  font-size: 24rpx;
  color: #4CAF50;
  font-weight: 500;
}

.load-more {
  text-align: center;
  margin-top: 20rpx;
}

.load-more-btn {
  background-color: #4CAF50;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  padding: 20rpx 40rpx;
  font-size: 28rpx;
  font-weight: bold;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.load-more-btn:hover {
  background-color: #45a049; /* 按钮悬停效果 */
}

.load-more-btn:active {
  background-color: #3d8b40; /* 按钮点击效果 */
}

.no-data {
  text-align: center;
  padding: 80rpx 30rpx;
  border-radius: 16rpx;
  background-color: #fff;
}

.no-data-text {
  font-size: 32rpx;
  color: #999;
  margin-bottom: 15rpx;
}
</style>