<template>
  <view class="page">
    <!-- 使用自定义导航栏组件 -->
    <custom-navbar ref="customNavbar" :title="tourDetail.title || '古刹巡礼'" />
    <tile-grid />

    <!-- 主要内容区域 -->
    <view class="content-container">
      <!-- 文章头部信息 -->
      <view class="article-header">
        <text class="article-title">{{ tourDetail.title || "加载中..." }}</text>
        <text class="article-time"
          >{{ formatTime(tourDetail.createTime) }}
        </text>
      </view>

      <!-- 封面图片 -->
      <view v-if="tourDetail.coverUrl" class="cover-image-container">
        <image
          :src="tourDetail.coverUrl"
          class="cover-image"
          mode="aspectFill"
          @error="handleImageError"
        >
        </image>
      </view>

      <!-- 文章内容 -->
      <view v-if="tourDetail.content" class="article-content">
        <rich-text :nodes="processedContent"></rich-text>
      </view>

      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 相关阅读区域 -->
      <view v-if="relevantArticles.length > 0" class="relevant-section">
        <view class="section-title">
          <text class="title-text">相关阅读</text>
        </view>
        <view class="relevant-list">
          <view
            v-for="(item, index) in relevantArticles"
            :key="index"
            class="relevant-item"
            @click="goToArticle(item)"
          >
            <view class="item-content">
              <text class="item-title">{{ item.title }}</text>
              <view class="item-meta">
                <text v-if="item.subtitle" class="item-subtitle"
                  >{{ item.subtitle }}
                </text>
                <text class="item-time">{{ formatTime(item.createTime) }}</text>
                <!-- 开发时显示文章ID -->
                <text v-if="!tourId" class="item-id">ID: {{ item.id }}</text>
              </view>
            </view>
            <view class="item-arrow">
              <text class="arrow">></text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { CommonEnum } from "@/enum/common.js";
import { getRelevantArticles, getTourById } from "@/api/article/article.js";
import CustomNavbar from "../../components/custom-navbar/custom-navbar.vue";

export default {
  components: {
    CustomNavbar,
  },
  data() {
    return {
      CommonEnum,
      tourId: "24", // 巡礼ID，默认为24
      tourDetail: {
        title: "",
        content: "",
        createTime: "",
        coverUrl: "",
      },
      relevantArticles: [], // 相关文章列表
      loading: false,
    };
  },
  computed: {
    // 处理文章内容，确保HTML正确显示
    processedContent() {
      if (!this.tourDetail.content) return "";

      // 处理HTML内容，确保样式正确
      let content = this.tourDetail.content;

      // 添加基本样式
      content = `<div style="
        font-size: 28rpx; 
        line-height: 1.8; 
        color: #333; 
        word-wrap: break-word; 
        word-break: break-all;
        padding: 20rpx 0;
      ">${content}</div>`;

      return content;
    },
  },
  onLoad(options) {
    // 获取传递的参数，如果没有则使用默认值24
    if (options.id) {
      this.tourId = options.id;
    }
    // 无论是否有参数都加载数据
    this.fetchTourDetail();
    this.fetchRelevantArticles();
  },
  methods: {
    // 获取巡礼详情
    async fetchTourDetail() {
      try {
        this.loading = true;
        const res = await getTourById(this.tourId);

        if (res.code === 200 && res.data) {
          this.tourDetail = {
            title: res.data.title || "",
            content: res.data.content || "",
            createTime: res.data.createTime || "",
            coverUrl: res.data.coverUrl || "",
          };
        } else {
          uni.showToast({
            title: res.msg || "获取文章详情失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("获取文章详情失败:", error);
        uni.showToast({
          title: "网络错误",
          icon: "none",
        });
      } finally {
        this.loading = false;
      }
    },

    // 获取相关文章
    async fetchRelevantArticles() {
      try {
        const res = await getRelevantArticles(this.tourId);

        if (res.code === 200 && res.data) {
          this.relevantArticles = res.data.map((item) => ({
            id: item.id || item.articleId, // 兼容不同的ID字段名
            title: item.title || "",
            subtitle: item.subtitle || "",
            createTime: item.createTime || "",
          }));
        }
      } catch (error) {
        console.error("获取相关文章失败:", error);
        // 相关文章获取失败不影响主页面显示
      }
    },

    // 格式化时间
    formatTime(timeStr) {
      if (!timeStr) return "";

      try {
        const date = new Date(timeStr);
        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}`;
      } catch (error) {
        return timeStr;
      }
    },

    // 跳转到相关文章
    goToArticle(article) {
      console.log("点击相关文章:", article);

      if (article && article.id) {
        console.log("跳转到文章ID:", article.id);
        uni.navigateTo({
          url: `/pages/ancient/ancientTourById?id=${article.id}`,
          success: () => {
            console.log("跳转成功");
          },
          fail: (error) => {
            console.error("跳转失败:", error);
            uni.showToast({
              title: "跳转失败",
              icon: "none",
            });
          },
        });
      } else {
        console.warn("文章ID不存在:", article);
        uni.showToast({
          title: "文章信息不完整",
          icon: "none",
        });
      }
    },

    // 处理图片加载错误
    handleImageError() {
      console.log("封面图片加载失败");
      // 可以设置默认图片或隐藏图片容器
    },

    // 测试方法（开发时使用）
    testWithId(id) {
      this.tourId = id;
      this.fetchTourDetail();
      this.fetchRelevantArticles();
    },
  },
};
</script>

<style lang="scss">
.page {
  background: #f6f1e7;
  width: 100%;
  min-height: 100vh;
  flex-direction: column;

  align-items: center;
}

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

  box-sizing: border-box;
}

/* 文章头部样式 */
.article-header {
  background: #fff;
  padding: 40rpx 30rpx;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.article-title {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  line-height: 1.4;
  margin-bottom: 20rpx;
}

.article-time {
  display: block;
  font-size: 24rpx;
  color: #999;
  line-height: 1.2;
}

/* 封面图片样式 */
.cover-image-container {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.cover-image {
  width: 100%;
  height: 400rpx;
  display: block;
}

/* 文章内容样式 */
.article-content {
  background: #fff;
  padding: 30rpx;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  min-height: 200rpx;
}

/* 加载状态样式 */
.loading-container {
  background: #fff;
  padding: 60rpx 30rpx;
  border-radius: 16rpx;
  text-align: center;
  margin-bottom: 20rpx;
}

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

/* 相关阅读区域样式 */
.relevant-section {
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.section-title {
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  background: #f8f8f8;
}

.title-text {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.relevant-list {
  padding: 0;
}

.relevant-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  transition: background-color 0.3s ease;
}

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

.relevant-item:active {
  background-color: #f5f5f5;
}

.item-content {
  flex: 1;
  margin-right: 20rpx;
}

.item-title {
  display: block;
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
  line-height: 1.4;
  margin-bottom: 10rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.item-subtitle {
  font-size: 24rpx;
  color: #666;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 20rpx;
}

.item-time {
  font-size: 22rpx;
  color: #999;
  flex-shrink: 0;
}

.item-id {
  font-size: 20rpx;
  color: #666;
  background: #f0f0f0;
  padding: 4rpx 8rpx;
  border-radius: 4rpx;
  margin-left: 10rpx;
  flex-shrink: 0;
}

.item-arrow {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.arrow {
  font-size: 24rpx;
  color: #ccc;
  font-weight: bold;
}

/* 测试按钮样式 */
.test-buttons {
  position: fixed;
  top: 100rpx; /* 根据导航栏高度调整 */
  left: 20rpx;
  z-index: 10;
  background-color: #fff;
  padding: 20rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.test-btn {
  margin-bottom: 10rpx;
  background-color: #4caf50;
  color: #fff;
  font-size: 28rpx;
  padding: 15rpx 30rpx;
  border-radius: 8rpx;
  border: none;
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
}

.test-btn:last-child {
  margin-bottom: 0;
}
</style>
