<template>
  <view class="page">
    <base-background />
    <!-- 使用自定义导航栏组件 -->
    <custom-navbar title="供奉记录" ref="customNavbar" />

    <view class="header">
      <!-- 状态展示 -->
      <status-display v-if="loading" type="loading" loading-text="加载中..." />

      <!-- 错误状态 -->
      <status-display v-if="error" type="error" :error-text="error" @retry="fetchData" />

      <!-- 页面内容 -->
      <view v-if="!loading && !error" class="content">
        <!-- 牌位信息卡片 -->
        <view class="memorial-card">
          <view class="memorial-info">
            <view class="info-row">
              <text class="label">{{ memorialData.name || '暂无' }}</text>
              <text class="value">{{ memorialData.code || '暂无' }}</text>
            </view>
            <view class="memorial-desc" v-if="memorialData.introduced">
              {{ memorialData.introduced }}
            </view>
          </view>
        </view>

        <!-- 供奉记录列表 -->
        <view class="records-section">
          <!-- 表头 -->
          <view class="table-header">
            <view class="header-cell">供奉人</view>
            <view class="header-cell">供奉时间</view>
            <view class="header-cell">结束时间</view>
            <view class="header-cell">供奉类型</view>
          </view>

          <!-- 记录列表 -->
          <view class="records-list">
            <view v-for="(record, index) in enshrinedList" :key="record.id" class="record-item">
              <view class="record-cell">
                <text class="worshiper-name">{{ formatWorshiperName(record.worshiperName) }}</text>
              </view>
              <view class="record-cell">
                <text class="date-text">{{ formatDate(record.startDate) }}</text>
              </view>
              <view class="record-cell">
                <text class="date-text">{{ formatDate(record.endDate) }}</text>
              </view>
              <view class="record-cell">
                <text class="offering-type">{{ record.thaliName }}</text>
              </view>
            </view>
          </view>

          <!-- 空状态 -->
          <view v-if="enshrinedList.length === 0" class="empty-state">
            <text class="empty-text">暂无供奉记录</text>
          </view>

          <!-- 加载更多提示 -->
          <view v-if="enshrinedList.length > 0 && enshrinedList.length < total" class="load-more">
            <text class="load-more-text">上拉加载更多</text>
          </view>

          <!-- 全部加载完成提示 -->
          <view
            v-if="enshrinedList.length > 0 && enshrinedList.length >= total"
            class="load-complete"
          >
            <text class="load-complete-text">已加载全部记录</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  import { getMemorialDetail, getEnshrinedList } from '@/api/memorial/memorial.js'

  export default {
    data() {
      return {
        loading: false,
        error: '',
        memorialId: '', // 牌位ID
        memorialData: {}, // 牌位详情数据
        enshrinedList: [], // 供奉记录列表
        pageNum: 1,
        pageSize: 10,
        total: 0,
      }
    },

    onLoad(options) {
      // 从路由参数获取牌位ID
      this.memorialId = options.id || '16'
      this.fetchData()
    },

    // 下拉刷新
    onPullDownRefresh() {
      this.pageNum = 1
      this.fetchData().then(() => {
        uni.stopPullDownRefresh()
      })
    },

    // 上拉加载更多
    onReachBottom() {
      if (this.enshrinedList.length < this.total) {
        this.pageNum++
        this.loadMoreData()
      }
    },

    methods: {
      // 获取所有数据
      async fetchData() {
        this.loading = true
        this.error = ''

        try {
          // 并行请求两个API
          const [memorialRes, enshrinedRes] = await Promise.all([
            this.fetchMemorialDetail(),
            this.fetchEnshrinedList(),
          ])

          // 处理牌位详情数据
          if (memorialRes.code === 200) {
            this.memorialData = memorialRes.data || {}
          }

          // 处理供奉记录数据
          if (enshrinedRes.code === 200) {
            this.enshrinedList = enshrinedRes.rows || []
            this.total = enshrinedRes.total || 0
          }
        } catch (error) {
          console.error('获取数据失败:', error)
          this.error = '网络错误，请重试'
          uni.showToast({
            title: '获取数据失败',
            icon: 'none',
          })
        } finally {
          this.loading = false
        }
      },

      // 获取牌位详情
      async fetchMemorialDetail() {
        return await getMemorialDetail(this.memorialId)
      },

      // 获取供奉记录列表
      async fetchEnshrinedList() {
        const params = {
          memorialId: this.memorialId,
          pageNum: this.pageNum,
          pageSize: this.pageSize,
        }
        return await getEnshrinedList(params)
      },

      // 加载更多数据
      async loadMoreData() {
        try {
          const res = await this.fetchEnshrinedList()
          if (res.code === 200) {
            const newRecords = res.rows || []
            this.enshrinedList = [...this.enshrinedList, ...newRecords]
            this.total = res.total || 0
          }
        } catch (error) {
          console.error('加载更多数据失败:', error)
          this.pageNum-- // 回退页码
          uni.showToast({
            title: '加载失败',
            icon: 'none',
          })
        }
      },

      // 格式化供奉人姓名（脱敏处理）
      formatWorshiperName(name) {
        if (!name) return '未知'
        if (name.length <= 2) return name
        return name.charAt(0) + '*' + name.charAt(name.length - 1)
      },

      // 格式化日期
      formatDate(dateStr) {
        if (!dateStr) return '未知'
        const date = new Date(dateStr)
        if (isNaN(date.getTime())) return '未知'

        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')

        return `${year}-${month}-${day}`
      },
    },
  }
</script>

<style lang="scss" scoped>
  .page {
    width: 100%;
    min-height: 100vh;
  }

  .header {
    width: 100%;
    min-height: 100vh;
    display: flex;
    align-items: flex-start;
    flex-direction: column;
    padding: 0 30rpx 40rpx 30rpx;
  }

  .content {
    width: 100%;
    padding-top: 20rpx;
  }

  // 牌位信息卡片
  .memorial-card {
    border-radius: 16rpx;
    padding: 40rpx;
    margin-bottom: 40rpx;
    width: 680rpx;
    height: 230rpx;
    background: #fffbf5;
    border: 1rpx solid #c7a26d;
  }

  .memorial-info {
    .info-row {
      display: flex;

      align-items: center;
      margin-bottom: 24rpx;

      .label {
        font-weight: 500;
        font-size: 40rpx;
        color: #522510;
        line-height: 54rpx;
        text-align: left;
        margin-right: 84rpx;
      }

      .value {
        font-weight: 500;
        font-size: 40rpx;
        color: #522510;
        line-height: 54rpx;
      }
    }

    .memorial-desc {
      border-radius: 8rpx;
      font-weight: 400;
      font-size: 32rpx;
      color: #4c382e;
      line-height: 44rpx;
      letter-spacing: 2px;
      text-align: left;
    }
  }

  // 供奉记录区域
  .records-section {
    padding: 46rpx 43rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
    background: #fffbf5;
    border-radius: 20rpx 20rpx 20rpx 20rpx;
    border: 1rpx solid #c7a26d;
    width: 680rpx;
  }

  // 表头
  .table-header {
    display: flex;
    border-radius: 8rpx;
    margin-bottom: 30rpx;
    //border:1px red solid;
    align-items: center;

    .header-cell {
      flex: 1;

      //border:1px red solid;
      font-weight: 400;
      font-size: 28rpx;
      color: #695347;
      line-height: 38rpx;
      text-align: left;
    }
  }

  // 记录列表
  .records-list {
    //border:1px red solid;
    .record-item {
      //border:1px red solid;
      display: flex;

      margin-bottom: 30rpx;

      .record-cell {
        flex: 1;
        font-weight: 400;
        font-size: 24rpx;
        color: #522510;
        line-height: 32rpx;
        text-align: left;
        //border:1px red solid;

        .worshiper-name {
          color: #522510;
          font-weight: 500;
        }

        .date-text {
          color: #666;
        }
      }
    }
  }

  // 空状态
  .empty-state {
    text-align: center;
    padding: 80rpx 0;

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

  // 加载更多提示
  .load-more {
    text-align: center;
    padding: 40rpx 0;

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

  // 加载完成提示
  .load-complete {
    text-align: center;
    padding: 40rpx 0;

    .load-complete-text {
      font-size: 26rpx;
      color: #666;
    }
  }
</style>
