<template>
  <view class="records-page">
    <!-- 顶部导航 -->
    <view class="top-nav-bar">
      <view class="nav-back" @click="goBack">
        <text class="back-arrow">‹</text>
      </view>
      <view class="nav-title">
        <text class="title-text">核销记录</text>
      </view>
      <view class="nav-placeholder"></view>
    </view>

    <!-- 统计概览 -->
    <view class="stats-overview">
      <view class="stat-card">
        <text class="stat-number">{{ totalCount }}</text>
        <text class="stat-label">累计核销</text>
      </view>
      <view class="stat-divider"></view>
      <view class="stat-card">
        <text class="stat-number">{{ todayCount }}</text>
        <text class="stat-label">今日核销</text>
      </view>
    </view>

    <!-- 记录列表 -->
    <scroll-view
      class="records-scroll"
      scroll-y
      :refresher-enabled="true"
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onPullDownRefresh"
      @scrolltolower="onLoadMore"
    >
      <!-- 按日期分组的记录 -->
      <view class="records-container" v-if="groupedRecords.length > 0">
        <view
          class="date-group"
          v-for="(group, gIdx) in groupedRecords"
          :key="'date-' + gIdx"
        >
          <!-- 日期标题 -->
          <view class="date-header">
            <text class="date-label">{{ group.dateLabel }}</text>
            <text class="date-count">{{ group.list.length }} 张</text>
          </view>

          <!-- 记录卡片 -->
          <view
            class="record-card"
            v-for="(item, idx) in group.list"
            :key="'record-' + item.id"
          >
            <view class="record-time">
              <text>{{ formatTime(item.created_at) }}</text>
            </view>
            <view class="record-info">
              <text class="record-title">{{ item.goods_title }}</text>
              <text class="record-detail">
                {{ item.real_name }} · {{ formatSeatShort(item.seat_info) }}
              </text>
            </view>
            <view class="record-status">
              <text class="status-icon success">✓</text>
            </view>
          </view>
        </view>

        <!-- 加载更多 -->
        <view class="load-more" v-if="hasMore && !isLoadingMore">
          <text class="load-more-text" @click="onLoadMore">加载更多</text>
        </view>
        <view class="load-more loading" v-if="isLoadingMore">
          <view class="loading-dots">
            <view class="dot"></view>
            <view class="dot"></view>
            <view class="dot"></view>
          </view>
          <text class="load-more-text">加载中...</text>
        </view>

        <!-- 没有更多 -->
        <view class="no-more" v-if="!hasMore && groupedRecords.length > 0">
          <text>— 已加载全部 {{ totalCount }} 条记录 —</text>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-section" v-if="!isLoading && groupedRecords.length === 0">
        <iconfont name="icon-order-list" size="100rpx" color="#ccc"></iconfont>
        <text class="empty-text">暂无核销记录</text>
        <text class="empty-tip">扫码核销后将在这里显示</text>
      </view>

      <!-- 加载骨架屏 -->
      <view class="loading-section" v-if="isLoading">
        <view class="skeleton-group" v-for="i in 3" :key="i">
          <view class="skeleton-header">
            <view class="skeleton-date"></view>
          </view>
          <view class="skeleton-card" v-for="j in 2" :key="j">
            <view class="skeleton-time"></view>
            <view class="skeleton-content">
              <view class="skeleton-line"></view>
              <view class="skeleton-line short"></view>
            </view>
          </view>
        </view>
      </view>

      <!-- 底部安全区 -->
      <view class="safe-area-bottom"></view>
    </scroll-view>

    <!-- 公共组件 -->
    <component-common ref="common"></component-common>
  </view>
</template>

<script>
const app = getApp();

export default {
  data() {
    return {
      // 统计数据
      totalCount: 0,
      todayCount: 0,
      // 列表数据
      records: [],
      // 分页
      page: 1,
      pageSize: 20,
      hasMore: true,
      // 加载状态
      isLoading: true,
      isRefreshing: false,
      isLoadingMore: false,
    };
  },

  computed: {
    // 按日期分组
    groupedRecords() {
      var groups = {};
      var today = new Date();
      today.setHours(0, 0, 0, 0);
      var todayStart = today.getTime();
      
      var yesterday = new Date(today);
      yesterday.setDate(yesterday.getDate() - 1);
      var yesterdayStart = yesterday.getTime();

      this.records.forEach(item => {
        var date = new Date(item.created_at * 1000);
        date.setHours(0, 0, 0, 0);
        var dateTime = date.getTime();
        var label = '';
        
        if (dateTime === todayStart) {
          label = '今天';
        } else if (dateTime === yesterdayStart) {
          label = '昨天';
        } else {
          label = this.formatDate(item.created_at);
        }

        if (!groups[label]) {
          groups[label] = {
            dateLabel: label,
            list: []
          };
        }
        groups[label].list.push(item);
      });

      return Object.values(groups);
    }
  },

  onLoad() {
    this.init();
  },

  onShow() {
    // 刷新数据
    if (!this.isLoading) {
      this.onPullDownRefresh();
    }
  },

  methods: {
    // 返回
    goBack() {
      const pages = getCurrentPages();
      if (pages.length > 1) {
        uni.navigateBack();
      } else {
        uni.reLaunch({ url: '/pages/index/index' });
      }
    },

    // 初始化
    init() {
      var user = app.globalData.get_user_info(this, 'init');
      if (user == false) {
        this.isLoading = false;
        return;
      }
      this.loadRecords();
    },

    // 加载记录
    loadRecords() {
      var self = this;
      this.isLoading = true;
      
      uni.request({
        url: app.globalData.get_request_url('myVerifications', 'ticket', 'vr_ticket'),
        method: 'GET',
        data: {
          page: this.page,
          page_size: this.pageSize
        },
        dataType: 'json',
        success: function(res) {
          self.isLoading = false;
          self.isRefreshing = false;
          self.isLoadingMore = false;
          
          if (res.data.code == 0) {
            var data = res.data.data || {};
            
            if (self.page === 1) {
              self.records = data.list || [];
            } else {
              self.records = self.records.concat(data.list || []);
            }
            
            self.totalCount = data.total || 0;
            self.hasMore = self.page < (data.pages || 1);
            
            // 计算今日核销
            self.calculateTodayCount();
          } else {
            if (app.globalData.is_login_check(res.data, self, 'init')) {
              app.globalData.showToast(res.data.msg);
            }
          }
        },
        fail: function() {
          self.isLoading = false;
          self.isRefreshing = false;
          self.isLoadingMore = false;
          app.globalData.showToast(self.$t('common.internet_error_tips'));
        }
      });
    },

    // 计算今日核销数
    calculateTodayCount() {
      var today = new Date();
      today.setHours(0, 0, 0, 0);
      var todayStart = today.getTime() / 1000;
      
      var count = 0;
      this.records.forEach(item => {
        if (item.created_at >= todayStart) {
          count++;
        }
      });
      this.todayCount = count;
    },

    // 下拉刷新
    onPullDownRefresh() {
      this.isRefreshing = true;
      this.page = 1;
      this.hasMore = true;
      this.loadRecords();
    },

    // 加载更多
    onLoadMore() {
      if (this.isLoadingMore || !this.hasMore) return;
      
      this.isLoadingMore = true;
      this.page++;
      this.loadRecords();
    },

    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return '';
      var date = new Date(timestamp * 1000);
      var hours = date.getHours().toString().padStart(2, '0');
      var minutes = date.getMinutes().toString().padStart(2, '0');
      return hours + ':' + minutes;
    },

    // 格式化日期
    formatDate(timestamp) {
      if (!timestamp) return '';
      var date = new Date(timestamp * 1000);
      var month = (date.getMonth() + 1).toString().padStart(2, '0');
      var day = date.getDate().toString().padStart(2, '0');
      return month + '月' + day + '日';
    },

    // 格式化座位信息（简化）
    formatSeatShort(seatInfo) {
      if (!seatInfo) return '';
      var parts = seatInfo.split('|');
      if (parts.length >= 5) {
        return parts[3] + ' ' + parts[4];
      }
      return seatInfo;
    },
  },
};
</script>

<style>
@import './records.css';
</style>
