<template>
  <view class="comments-page">
    <!-- 头部导航 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <uni-icons type="arrowleft" size="24" color="#333"></uni-icons>
      </view>
      <text class="title">全部评论 ({{ totalCount }})</text>
      <view class="placeholder"></view>
    </view>

    <!-- 评论列表 -->
    <scroll-view 
      class="comments-list" 
      scroll-y
      @scrolltolower="loadMore"
      :scroll-with-animation="true"
    >
      <view v-if="loading && comments.length === 0" class="loading-container">
        <uni-loading size="32" color="#007aff"></uni-loading>
        <text class="loading-text">加载中...</text>
      </view>

      <view v-else-if="comments.length === 0" class="empty-container">
        <uni-icons type="chat" size="64" color="#ccc"></uni-icons>
        <text class="empty-text">暂无评论</text>
      </view>

      <view v-else>
        <view 
          v-for="comment in comments" 
          :key="comment.id" 
          class="comment-item"
        >
          <image 
            :src="comment.user.avatar || '/static/avatar/default.png'" 
            class="comment-avatar" 
            mode="aspectFill"
          ></image>
          
          <view class="comment-content">
            <view class="comment-header">
              <text class="comment-user">{{ comment.user.nickname }}</text>
              <text class="comment-time">{{ formatTime(comment.createTime) }}</text>
            </view>
            
            <text class="comment-text">{{ comment.content }}</text>
            
            <view class="comment-actions">
              <view class="action-btn" @click="likeComment(comment)">
                <uni-icons 
                  :type="comment.isLiked ? 'heart-filled' : 'heart'" 
                  size="16" 
                  :color="comment.isLiked ? '#ff4757' : '#999'"
                ></uni-icons>
                <text class="action-count">{{ comment.likeCount || 0 }}</text>
              </view>
              
              <view class="action-btn" @click="replyComment(comment)">
                <uni-icons type="chat" size="16" color="#999"></uni-icons>
                <text class="action-count">回复</text>
              </view>
            </view>
            
            <!-- 回复列表 -->
            <view v-if="comment.replies && comment.replies.length > 0" class="replies-container">
              <view 
                v-for="reply in comment.replies" 
                :key="reply.id" 
                class="reply-item"
              >
                <text class="reply-user">{{ reply.user.nickname }}</text>
                <text class="reply-text">: {{ reply.content }}</text>
                <text class="reply-time">{{ formatTime(reply.createTime) }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 加载更多 -->
        <view v-if="hasMore" class="load-more">
          <uni-loading size="24" color="#999" v-if="loadingMore"></uni-loading>
          <text class="load-more-text" v-else>上拉加载更多</text>
        </view>
        
        <view v-else class="no-more">
          <text>没有更多评论了</text>
        </view>
      </view>
    </scroll-view>

    <!-- 底部输入框 -->
    <view class="comment-input-container">
      <input 
        v-model="newComment" 
        class="comment-input" 
        placeholder="写下你的评论..."
        :focus="isFocus"
        @focus="onInputFocus"
        @blur="onInputBlur"
        @confirm="submitComment"
      />
      <view 
        class="send-btn" 
        :class="{ active: newComment.trim() }"
        @click="submitComment"
      >
        <text>发送</text>
      </view>
    </view>

    <!-- 回复面板 -->
    <view 
      v-if="showReplyPanel" 
      class="reply-panel"
      :style="{ bottom: inputHeight + 'px' }"
    >
      <text class="reply-hint">回复 @{{ replyTarget.user.nickname }}</text>
      <view class="close-reply" @click="cancelReply">
        <uni-icons type="close" size="20" color="#999"></uni-icons>
      </view>
    </view>
  </view>
</template>

<script>
import travelService from '@/api/services'

export default {
  data() {
    return {
      travelId: null,
      comments: [],
      totalCount: 0,
      loading: false,
      loadingMore: false,
      hasMore: true,
      page: 1,
      pageSize: 10,
      
      newComment: '',
      isFocus: false,
      inputHeight: 0,
      
      showReplyPanel: false,
      replyTarget: null
    }
  },
  
  onLoad(options) {
    this.travelId = options.id
    this.loadComments()
  },
  
  onReady() {
    this.getInputHeight()
  },
  
  methods: {
    async loadComments() {
      if (this.loading) return
      
      this.loading = true
      try {
        const params = {
          page: this.page,
          pageSize: this.pageSize
        }
        
        const res = await travelService.getComments(this.travelId, params)
        const { list, total } = res.data
        
        if (this.page === 1) {
          this.comments = list
        } else {
          this.comments = [...this.comments, ...list]
        }
        
        this.totalCount = total
        this.hasMore = this.comments.length < total
        
      } catch (error) {
        uni.showToast({
          title: '加载评论失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
        this.loadingMore = false
      }
    },
    
    async loadMore() {
      if (this.loadingMore || !this.hasMore) return
      
      this.loadingMore = true
      this.page += 1
      await this.loadComments()
    },
    
    async submitComment() {
      if (!this.newComment.trim()) {
        uni.showToast({
          title: '评论内容不能为空',
          icon: 'none'
        })
        return
      }
      
      try {
        let commentData = { content: this.newComment.trim() }
        
        // 如果是回复
        if (this.showReplyPanel && this.replyTarget) {
          commentData.replyTo = this.replyTarget.id
          commentData.parentId = this.replyTarget.parentId || this.replyTarget.id
        }
        
        await travelService.addComment(this.travelId, commentData)
        
        uni.showToast({
          title: '评论成功',
          icon: 'success'
        })
        
        this.newComment = ''
        this.cancelReply()
        this.isFocus = false
        
        // 重新加载评论
        this.page = 1
        this.loadComments()
        
      } catch (error) {
        uni.showToast({
          title: error.message || '评论失败',
          icon: 'none'
        })
      }
    },
    
    async likeComment(comment) {
      try {
        // 这里需要实现点赞评论的API
        // await commentService.likeComment(comment.id)
        
        comment.isLiked = !comment.isLiked
        if (comment.isLiked) {
          comment.likeCount = (comment.likeCount || 0) + 1
        } else {
          comment.likeCount = Math.max(0, (comment.likeCount || 1) - 1)
        }
        
        this.$forceUpdate()
        
      } catch (error) {
        uni.showToast({
          title: '操作失败',
          icon: 'none'
        })
      }
    },
    
    replyComment(comment) {
      this.replyTarget = comment
      this.showReplyPanel = true
      this.isFocus = true
    },
    
    cancelReply() {
      this.replyTarget = null
      this.showReplyPanel = false
    },
    
    onInputFocus() {
      this.isFocus = true
    },
    
    onInputBlur() {
      this.isFocus = false
    },
    
    getInputHeight() {
      const query = uni.createSelectorQuery().in(this)
      query.select('.comment-input-container').boundingClientRect(data => {
        if (data) {
          this.inputHeight = data.height
        }
      }).exec()
    },
    
    formatTime(time) {
      if (!time) return ''
      
      const now = new Date()
      const commentTime = new Date(time)
      const diff = now - commentTime
      
      const minute = 60 * 1000
      const hour = 60 * minute
      const day = 24 * hour
      
      if (diff < minute) {
        return '刚刚'
      } else if (diff < hour) {
        return Math.floor(diff / minute) + '分钟前'
      } else if (diff < day) {
        return Math.floor(diff / hour) + '小时前'
      } else if (diff < 7 * day) {
        return Math.floor(diff / day) + '天前'
      } else {
        return commentTime.toLocaleDateString()
      }
    },
    
    goBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style scoped>
.comments-page {
  height: 100vh;
  background: #f8f8f8;
  display: flex;
  flex-direction: column;
}

/* 头部导航 */
.header {
  height: 88rpx;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32rpx;
  border-bottom: 1rpx solid #eee;
  position: relative;
  z-index: 10;
}

.back-btn {
  padding: 16rpx;
}

.title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
}

.placeholder {
  width: 48rpx;
  height: 48rpx;
}

/* 评论列表 */
.comments-list {
  flex: 1;
  background: #fff;
  padding: 0 32rpx;
}

.loading-container,
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.loading-text,
.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-top: 20rpx;
}

.comment-item {
  display: flex;
  padding: 32rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-avatar {
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 12rpx;
}

.comment-user {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  margin-right: 16rpx;
}

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

.comment-text {
  font-size: 28rpx;
  color: #333;
  line-height: 1.5;
  margin-bottom: 20rpx;
}

.comment-actions {
  display: flex;
  gap: 32rpx;
}

.action-btn {
  display: flex;
  align-items: center;
  padding: 8rpx 16rpx;
  border-radius: 24rpx;
  background: #f8f8f8;
}

.action-count {
  font-size: 24rpx;
  color: #666;
  margin-left: 8rpx;
}

/* 回复列表 */
.replies-container {
  margin-top: 20rpx;
  padding: 20rpx;
  background: #f8f8f8;
  border-radius: 12rpx;
}

.reply-item {
  margin-bottom: 12rpx;
}

.reply-item:last-child {
  margin-bottom: 0;
}

.reply-user {
  font-size: 26rpx;
  font-weight: 600;
  color: #007aff;
  margin-right: 8rpx;
}

.reply-text {
  font-size: 26rpx;
  color: #333;
}

.reply-time {
  font-size: 22rpx;
  color: #999;
  margin-left: 16rpx;
}

/* 加载更多 */
.load-more,
.no-more {
  text-align: center;
  padding: 32rpx 0;
  color: #999;
  font-size: 28rpx;
}

.load-more-text {
  color: #999;
}

/* 底部输入框 */
.comment-input-container {
  background: #fff;
  padding: 20rpx 32rpx;
  border-top: 1rpx solid #eee;
  display: flex;
  align-items: center;
  position: relative;
  z-index: 100;
}

.comment-input {
  flex: 1;
  height: 80rpx;
  background: #f8f8f8;
  border-radius: 40rpx;
  padding: 0 32rpx;
  font-size: 28rpx;
  margin-right: 20rpx;
}

.send-btn {
  background: #ccc;
  color: #fff;
  padding: 16rpx 32rpx;
  border-radius: 32rpx;
  font-size: 28rpx;
  font-weight: 600;
  transition: background 0.3s;
}

.send-btn.active {
  background: #007aff;
}

/* 回复面板 */
.reply-panel {
  position: fixed;
  left: 0;
  right: 0;
  background: #fff;
  padding: 16rpx 32rpx;
  border-top: 1rpx solid #eee;
  display: flex;
  align-items: center;
  justify-content: space-between;
  z-index: 90;
}

.reply-hint {
  font-size: 28rpx;
  color: #666;
}

.close-reply {
  padding: 8rpx;
}
</style>