<template>
  <view class="note-detail-container">
    <!-- 笔记内容区域 -->
    <view class="content-scroll">
      <!-- 轮播图区域 -->
      <view class="banner-content">
        <swiper
          class="top-banner"
          :circular="true"
          :interval="6000"
          :duration="800"
          :indicator-dots="false"
          :autoplay="true"
          @change="swiperChange"
        >
          <swiper-item v-for="(item, index) in topBanner" :key="index">
            <image
              class="top-banner"
              :src="item"
              mode="aspectFill"
              @click="previewImage(item)"
            ></image>
          </swiper-item>
        </swiper>

        <view class="dot-container">
          <view
            :class="['dot-line', index == swiperIndex ? 'active' : '']"
            v-for="(item, index) in topBanner"
            :key="index"
          ></view>
        </view>
      </view>

      <!-- 内容卡片 -->
      <view class="content-card">
        <!-- 作者信息 -->
        <view class="author-section">
          <image
            class="author-avatar"
            :src="noteDetail.headImg"
            mode="aspectFill"
          />
          <view class="author-info">
            <text class="author-name">{{ noteDetail.nickname }}</text>
          </view>
          <view
            class="follow-btn"
            :class="{ followed: noteDetail.user.isFollowed }"
            @click="toggleFollow"
          >
            {{ noteDetail.user.isFollowed ? "已关注" : "关注" }}
          </view>
        </view>
        <!-- 笔记标题 -->
        <view class="note-title">
          {{ noteDetail.title }}
        </view>

        <!-- 标签 -->
        <view
          class="tags-section"
          v-if="noteDetail.tags && noteDetail.tags.length"
        >
          <view class="tag-item" v-for="tag in noteDetail.tags" :key="tag">
            #{{ tag }}
          </view>
        </view>

        <!-- 笔记内容 -->
        <view class="note-content">
          <view class="content-text">{{ noteDetail.content }}</view>
          <!-- 标签名称 -->
          <view class="tag-names" v-if="noteDetail.tagNames">
            <text
              v-for="(tag, index) in noteDetail.tagNames"
              :key="index"
              class="tag-link"
              @click="handleTagClick(tag)"
              >#{{ tag }}</text
            >
          </view>
        </view>
      </view>
      <view
        class=""
        style="
          width: auto;
          height: 1rpx;
          background-color: #999999;
          margin: 60rpx 32rpx;
        "
      >
      </view>
      <!-- 评论区域 -->
      <view class="comments-section">
        <view class="comments-header">
          <text class="comments-title"
            >评论 ({{ noteDetail.commentCount || 0 }})</text
          >
        </view>

        <view
          class="comment-item"
          v-for="comment in noteDetail.comments"
          :key="comment.id"
        >
          <image
            class="comment-avatar"
            :src="showImg(comment.headImg)"
            mode="aspectFill"
          />
          <view class="comment-content">
            <view class="comment-header">
              <text class="comment-user">{{ comment.nickname }}</text>
              <text class="comment-time">{{
                formatTime(comment.createTime)
              }}</text>
            </view>
            <text class="comment-text">{{ comment.content }}</text>
          </view>
        </view>

        <!-- 加载更多提示 -->
        <view class="loading-more" v-if="loadingComments">
          <text>加载中...</text>
        </view>
        <view
          class="no-more-comments"
          v-if="!hasMoreComments && noteDetail.comments.length > 0"
        >
          <text>没有更多评论了</text>
        </view>
        <view
          class="no-comments"
          v-if="!hasMoreComments && noteDetail.comments.length === 0"
        >
          <text>暂无评论，快来发表第一条评论吧</text>
        </view>
      </view>

      <!-- 底部占位 -->
      <view class="bottom-placeholder"></view>
    </view>

    <!-- 底部评论输入框 -->
    <view class="comment-input-section-box">
      <view class="comment-input-section">
        <input
          class="comment-input"
          v-model="commentText"
          placeholder="写下你的想法..."
          @confirm="submitComment"
        />
        <button
          class="send-btn"
          @click="submitComment"
          :disabled="!commentText.trim()"
        >
          发送
        </button>
        <view class="like-section" @click="toggleLike">
          <image
            class="like-icon"
            mode="widthFix"
            :src="
              !noteDetail.userLiked
                ? 'https://epic.js-dyyj.com/uploads/20250728/2f3ae212c01fa3b67be81abc5723cf5c.png'
                : 'https://epic.js-dyyj.com/uploads/20250728/dd7ed269b24e84a2dd141da6ab980fd6.png'
            "
          ></image>
          <text
            class="like-count"
            :class="{ 'liked-text': noteDetail.userLiked }"
            >{{ noteDetail.likeCount || 0 }}</text
          >
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import headerVue from "@/components/header.vue";

export default {
  name: "NoteDetail",
  components: {
    headerVue,
  },
  onReachBottom() {
    // 触底加载更多评论
    if (this.hasMoreComments && !this.loadingComments) {
      this.loadCommentList(true);
    }
  },
  data() {
    return {
      noteId: "",
      commentText: "",
      topBanner: [],
      swiperIndex: 0,
      pageNum: 1,
      pageSize: 10,
      hasMoreComments: true,
      loadingComments: false,
      noteDetail: {
        id: "",
        title: "",
        content: "",
        image: "",
        tags: [],
        likes: 0,
        isLiked: false,
        createTime: "",
        tagNames: [],

        comments: [],
      },
    };
  },
  onLoad(options) {
    if (options.id) {
      this.noteId = options.id;
      this.loadNoteDetail();
    } else {
      uni.showToast({
        title: "笔记ID不存在",
        icon: "none",
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    }
  },
  methods: {
    swiperChange(e) {
      this.swiperIndex = e.detail.current;
    },
    // 加载笔记详情
    async loadNoteDetail() {
      try {
        uni.showLoading({ title: "加载中..." });
        // 调用真实API
        const res = await this.Post(
          { noteId: this.noteId },
          "/framework/note/getInfo/" + this.noteId,
          "DES"
        );
        if (res.code === 200) {
          this.noteDetail = res.data;
          this.noteDetail.tagNames = this.noteDetail.tagNames.split(",");
          console.log(this.noteDetail.tagNames);
          // 如果有图片，设置轮播图
          this.topBanner = this.noteDetail.coverImage.split(",");

          // 加载评论列表
          await this.loadCommentList();
        } else {
          uni.showToast({
            title: res.msg || "加载失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("加载笔记详情失败:", error);
        uni.showToast({
          title: "加载失败",
          icon: "none",
        });
      } finally {
        uni.hideLoading();
      }
    },

    // 加载评论列表
    async loadCommentList(isLoadMore = false) {
      if (this.loadingComments) return;

      try {
        this.loadingComments = true;

        // 如果不是加载更多，重置页码
        if (!isLoadMore) {
          this.pageNum = 1;
          this.hasMoreComments = true;
        }

        const res = await this.Post(
          {
            pageSize: this.pageSize,
            pageNum: this.pageNum,
            noteId: this.noteId,
          },
          "/framework/comment/pageList",
          "DES"
        );

        if (res.code === 200) {
          // 更新评论列表
          if (isLoadMore) {
            // 加载更多时，追加评论
            this.noteDetail.comments = [
              ...this.noteDetail.comments,
              ...(res.rows || []),
            ];
          } else {
            // 首次加载或刷新时，替换评论
            this.noteDetail.comments = res.rows || [];
          }

          // 更新评论数量
          this.noteDetail.commentCount = res.total || 0;

          // 判断是否还有更多评论
          this.hasMoreComments = this.noteDetail.comments.length < res.total;

          // 如果有更多评论，页码加1，为下次加载做准备
          if (this.hasMoreComments) {
            this.pageNum++;
          }
        } else {
          console.error("加载评论列表失败:", res.msg);
          uni.showToast({
            title: res.msg || "加载评论失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("加载评论列表失败:", error);
        uni.showToast({
          title: "加载评论失败",
          icon: "none",
        });
      } finally {
        this.loadingComments = false;
      }
    },
    // 预览图片
    previewImage(imageUrl) {
      uni.previewImage({
        urls: this.topBanner,
        current: imageUrl,
      });
    },

    // 切换关注状态
    async toggleFollow() {
      try {
        const action = this.noteDetail.user.isFollowed ? "cancel" : "follow";
        const res = await this.Post(
          {
            method: "POST",
            userId: this.noteDetail.user.id,
            action: action,
          },
          "/framework/user/follow",
          "DES"
        );

        if (res.code === 200) {
          this.noteDetail.user.isFollowed = !this.noteDetail.user.isFollowed;
          uni.showToast({
            title: this.noteDetail.user.isFollowed ? "已关注" : "取消关注",
            icon: "success",
          });
        } else {
          uni.showToast({
            title:
              res.msg || (action === "follow" ? "关注失败" : "取消关注失败"),
            icon: "none",
          });
        }
      } catch (error) {
        console.error("关注操作失败:", error);
        uni.showToast({
          title: "操作失败",
          icon: "none",
        });
      }
    },

    // 切换点赞状态
    async toggleLike() {
      if (!this.noteId) {
        uni.showToast({
          title: "笔记ID不存在",
          icon: "none",
        });
        return;
      }

      try {
        // 保存原始状态，用于出错时回滚
        const originalLiked = this.noteDetail.userLiked;
        const originalLikeCount = this.noteDetail.likeCount || 0;

        // 乐观更新UI
        this.noteDetail.userLiked = !this.noteDetail.userLiked;
        this.noteDetail.likeCount =
          (this.noteDetail.likeCount || 0) +
          (this.noteDetail.userLiked ? 1 : -1);

        // 根据当前状态决定调用哪个API
        const apiUrl = this.noteDetail.userLiked
          ? "/framework/noteLike/add/" + this.noteId
          : "/framework/noteLike/cancel/" + this.noteId;

        const res = await this.Post({}, apiUrl, "DES");

        if (res.code === 200) {
          // 成功时，如果API返回了准确的点赞数，则使用API返回的数据
          if (res.data && res.data.likeCount !== undefined) {
            this.noteDetail.likeCount = res.data.likeCount;
          }

          // 发送事件通知 timeShopBank 页面更新数据
          uni.$emit("note-like-change", {
            noteId: this.noteId,
            isLiked: this.noteDetail.userLiked,
            likeCount: this.noteDetail.likeCount,
          });

          // 可以在这里添加成功的提示或动画效果
        } else {
          // 失败时回滚UI状态
          this.noteDetail.userLiked = originalLiked;
          this.noteDetail.likeCount = originalLikeCount;

          uni.showToast({
            title:
              res.msg ||
              (this.noteDetail.userLiked ? "点赞失败" : "取消点赞失败"),
            icon: "none",
          });
        }
      } catch (error) {
        console.error("点赞操作失败:", error);

        // 发生异常时也需要回滚UI状态
        this.noteDetail.userLiked = !this.noteDetail.userLiked;
        this.noteDetail.likeCount =
          (this.noteDetail.likeCount || 0) +
          (this.noteDetail.userLiked ? 1 : -1);

        uni.showToast({
          title: "网络异常，请稍后重试",
          icon: "none",
        });
      }
    },

    // 提交评论
    async submitComment() {
      if (!this.commentText.trim()) {
        return;
      }

      try {
        uni.showLoading({ title: "提交中..." });
        const res = await this.Post(
          {
            noteId: this.noteId,
            content: this.commentText,
            method: "POST",
          },
          "/framework/comment/addComment",
          "DES"
        );
        if (res.code === 200) {
          // 清空评论输入框
          this.commentText = "";

          // 评论成功后只加载评论列表，不需要重新加载整个笔记详情
          await this.loadCommentList();

          uni.showToast({
            title: "评论成功",
            icon: "success",
          });
        } else {
          uni.showToast({
            title: res.msg || "评论失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("提交评论失败:", error);
        uni.showToast({
          title: "评论失败",
          icon: "none",
        });
      } finally {
        uni.hideLoading();
      }
    },

    // 格式化时间
    formatTime(timeString) {
      const time = new Date(timeString);
      const year = time.getFullYear();
      const month = String(time.getMonth() + 1).padStart(2, "0");
      const day = String(time.getDate()).padStart(2, "0");
      return `${year}/${month}/${day}`;
    },

    // 显示图片
    showImg(img) {
      if (!img) return "/static/image/default-avatar.png";
      if (img.indexOf("https://") !== -1 || img.indexOf("http://") !== -1) {
        return img;
      } else {
        return this.NEWAPIURLIMG + img;
      }
    },

    // 处理标签点击
    handleTagClick(tag) {
      console.log("标签点击:", tag);
      // 可以根据需求跳转到标签相关页面或执行其他操作
      // uni.showToast({
      //   title: `点击了标签: ${tag}`,
      //   icon: "none",
      // });

      // 如果需要跳转到标签相关页面，可以使用以下代码
      // uni.navigateTo({
      //   url: `/pages/tags/detail?tag=${encodeURIComponent(tag)}`
      // });
    },
  },
};
</script>

<style lang="scss" scoped>
.note-detail-container {
  min-height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.content-scroll {
  flex: 1;
  padding: 0;
}

// 笔记图片
.note-image-container {
  width: 100%;
  height: 500rpx;
  overflow: hidden;

  .note-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

// 作者信息
.author-section {
  display: flex;
  align-items: center;
  background: #fff;

  .author-avatar {
    width: 95rpx;
    height: 95rpx;
    border-radius: 50%;
    margin-right: 24rpx;
  }

  .author-info {
    flex: 1;

    .author-name {
      display: block;
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .follow-btn {
    border-radius: 30rpx;
    font-size: 28rpx;
    color: #fff;
    font-weight: bold;
    border: 2rpx solid #02fcfc;
    color: #333333;
    background-color: white;
    padding: 12rpx 30rpx;
    &.followed {
      background: #ccc;
    }
  }
}

// 内容卡片容器
.content-card {
  margin: 32rpx;
  background: #fff;
  border-radius: 0rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;
  padding: 40rpx;
}

// 笔记标题
.note-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
  margin-bottom: 14rpx;
  margin-top: 24rpx;
}

// 标签
.tags-section {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  margin-bottom: 32rpx;

  .tag-item {
    // background: #f8f9fa;
    // border-radius: 20rpx;
    font-size: 26rpx;
    color: #666;
  }
}

// 笔记内容
.note-content {
  .content-text {
    font-size: 30rpx;
    line-height: 1.6;
    color: #333;
    font-weight: 500;
    word-break: break-all;
  }

  .tag-names {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;
    margin-top: 24rpx;

    .tag-link {
      font-size: 28rpx;
      color: #0066cc;
      font-weight: 500;
    }
  }
}

// 评论区域
.comments-section {
  margin: 0 32rpx 32rpx;
  border-radius: 0rpx;
  .comments-header {
    margin-bottom: 32rpx;

    .comments-title {
      font-size: 34rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .comment-item {
    display: flex;
    margin-bottom: 32rpx;

    .comment-avatar {
      width: 64rpx;
      height: 64rpx;
      border-radius: 32rpx;
      margin-right: 24rpx;
    }

    .comment-content {
      flex: 1;

      .comment-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12rpx;

        .comment-user {
          font-size: 30rpx;
          font-weight: bold;
          color: #000000;
        }

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

      .comment-text {
        font-size: 28rpx;
        line-height: 1.5;
        color: #000000;
      }
    }
  }
}
.comment-input-section-box {
  position: fixed;
  bottom: -1px;
  left: 0;
  right: 0;
  z-index: 999;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
  border-top: 1rpx solid #f0f0f0;
  background: #fff;
}
// 底部评论输入
.comment-input-section {
  display: flex;
  align-items: center;
  padding: 24rpx 32rpx 0;
  padding-bottom: max(env(safe-area-inset-bottom), 24rpx);

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

  .send-btn {
    width: 140rpx;
    height: 67rpx;
    line-height: 67rpx;
    background: #94fafa;
    color: #000000;
    border-radius: 40rpx;
    font-size: 30rpx;
    border: none;
    font-weight: 500;
    margin-right: 24rpx;

    &:disabled {
      background: #ccc;
    }
  }

  .like-section {
    display: flex;
    align-items: center;
    gap: 8rpx;

    .like-icon {
      width: 36rpx;
      transition: color 0.3s;
      &.liked {
        color: #ff4757;
      }
    }

    .like-count {
      font-size: 30rpx;
      color: #666;
      font-weight: bold;

      &.liked-text {
        color: #ff4757;
      }
    }
  }
}

.bottom-placeholder {
  height: 130rpx;
  width: 100%;
  padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
  padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
  box-sizing: content-box;
}

// 加载更多和无更多评论提示样式
.loading-more,
.no-more-comments,
.no-comments {
  text-align: center;
  padding: 30rpx 0;

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

.no-comments {
  padding: 60rpx 0;

  text {
    font-size: 30rpx;
  }
}
.banner-content {
  width: 100%;
  height: 1000rpx;
  position: relative;

  .top-banner {
    width: 100%;
    height: 100%;
  }

  .dot-container {
    position: absolute;
    bottom: 43rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    left: 0;

    .dot-line {
      width: 52rpx;
      height: 4rpx;
      margin: 0 8rpx;
      background: RGBA(189, 170, 173, 0.8);

      &.active {
        background: white;
      }
    }
  }

  .page-indicator {
    position: absolute;
    bottom: 20rpx;
    right: 20rpx;
    // background: rgba(0, 0, 0, 0.5);
    border-radius: 10rpx;
    padding: 10rpx 20rpx;

    .page-text {
      font-size: 24rpx;
      color: #fff;
      font-weight: 500;
    }
  }
}
</style>
