<template>
  <view class="feedback-page">
    <scroll-view 
      class="feedback-list" 
      scroll-y 
      @scrolltolower="loadMore"
      :scroll-with-animation="true"
    >
      <view class="empty" v-if="feedbackList.length === 0">
        <uni-icons style="margin-left: 20px;" custom-prefix="iconfont" type="icon-kongshuju" size="80" color="#ccc"></uni-icons>
        <text style="margin-top: 20px;">暂无留言</text>
      </view>
      <view 
        class="feedback-item" 
        v-for="(item, index) in feedbackList" 
        :key="index"
        @click="goDetail(item)"
      >
        <view class="feedback-content">
          <text class="subject">{{ item.title }}</text>
          <text class="create-time">{{ formatTimestamp(item.suggestionTime) }}</text>
        </view>
      </view>
      <view class="loading-more" v-if="loading">
        <text>加载中...</text>
      </view>
      <view class="no-more" v-if="noMore">
        <text>没有更多留言了~</text>
      </view>
    </scroll-view>
    <view class="write-btn-box">
      <button class="write-btn" @click="goWriteComment">去留言</button>
    </view>
  </view>
</template>

<script>
import { FetchInitReaderMessage  } from '@/api/user';
import config from '@/utils/config';
import { getOpenId } from '@/utils/storage';

export default {
  data() {
    return {
      feedbackList: [],
      pageNum: 0,
      pageSize: 10,
      loading: false,
      noMore: false,
    };
  },
  onLoad() {
    this.getInitReaderMessage();
  },
  onShow() {
    // 检查是否需要刷新（从留言页面提交成功返回）
    const needRefresh = uni.getStorageSync('needRefreshFeedback');
    uni.removeStorageSync('needRefreshFeedback');
    
    if (needRefresh) {
      this.refreshList();
    }
  },
  methods: {
    async getInitReaderMessage(){
      const openId = await getOpenId();
      if (!openId) {
        uni.showToast({ title: '获取用户信息失败', icon: 'none' });
        return;
      }
      // const currentReaderCard = await getCurrentReaderCard();
      const res = await FetchInitReaderMessage({
        libcode: config.LIB_CODE,
        openId: openId,
        // readCardNo: currentReaderCard.readCardNo,
        // readName: '',
        page: this.pageNum,
        size: this.pageSize,
      });
      if (res.code === 200) {
        this.feedbackList = res.data.content || [];
      } else {
        uni.showToast({ title: res.message || '获取留言列表失败', icon: 'none' });
      }
    },
    goWriteComment() {
      uni.navigateTo({
        url: '/subpkg/pages/feedback/feedback'
      });
    },
    goDetail(item) {
      console.log(item);
      uni.navigateTo({
        url: '/subpkg/pages/feedback-detail/feedback-detail?item=' + encodeURIComponent(JSON.stringify(item))
      });
    },
    formatTimestamp(timestamp) {
      if (!timestamp || typeof timestamp !== 'number') {
        return '暂无时间';
      }
      
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    async loadMore() {
      if (this.loading || this.noMore) return;
      
      this.loading = true;
      this.pageNum++;
      
      try {
        const openId = await getOpenId();
        if (!openId) {
          uni.showToast({ title: '获取用户信息失败', icon: 'none' });
          return;
        }
        
        const res = await FetchInitReaderMessage({
          libcode: config.LIB_CODE,
          openId: openId,
          page: this.pageNum,
          size: this.pageSize,
        });
        
        if (res.code === 200) {
          const newData = res.data.content || [];
          if (newData.length > 0) {
            this.feedbackList = [...this.feedbackList, ...newData];
          } else {
            this.noMore = true;
          }
        } else {
          uni.showToast({ title: res.message || '获取留言列表失败', icon: 'none' });
          this.pageNum--;
        }
      } catch (error) {
        console.error('加载更多失败:', error);
        this.pageNum--;
        uni.showToast({ title: '加载更多失败', icon: 'none' });
      } finally {
        this.loading = false;
      }
    },
    async refreshList() {
      // 重置分页状态
      this.pageNum = 0;
      this.noMore = false;
      this.loading = false;
      
      // 重新加载第一页数据
      await this.getInitReaderMessage();
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 300
      });
      uni.stopPullDownRefresh();
    }
  }
};
</script>

<style lang="scss" scoped>
.feedback-page {
  background-color: #f7f8fa;
  min-height: 100vh;
}

.feedback-list {
  height: calc(100vh - 80px);
}

.empty {
  height: calc(100vh - 200px);
}

.feedback-item {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  margin: 0 10px 10px 10px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.06);
}

.feedback-content {
  line-height: 1.6;
}

.subject {
  font-size: 15px;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 8px;
}

.create-time {
  font-size: 12px;
  color: #999;
  display: block;
  text-align: right;
}

.write-btn-box {
  position: fixed;
  bottom: 20px;
  left: 0;
  right: 0;
  padding: 0 15px;
}

.write-btn {
  background-color: #01a4fe;
  color: #fff;
  border-radius: 25px;
  font-size: 14px;
  padding: 4px 0;
}

.loading-more,
.no-more {
  text-align: center;
  padding: 15px 0;
  font-size: 12px;
  color: #999;
}
</style>
