<template>
  <div class="detail-container">
    <!-- 返回按钮 -->
    <div v-if="isFrom !== 'weixin'" class="back-button" @click="goBack">
      <img src="@/assets/indexPage/icon_back.png" alt="" />
    </div>

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

    <!-- 详情内容 -->
    <div v-else-if="detailData" :class="['detail-content', isFrom == 'weixin' ? 'notMargin' : '']">
      <!--标题 -->
      <div class="detail-title">
        {{
          isPreviewMode && detailData.titleB
            ? detailData.titleB
            : detailData.title || '克拉玛依市博物馆'
        }}
      </div>

      <!-- 时间 -->
      <div
        class="detail-time"
        v-if="fromtype != 'museum' && (detailData.publish || detailData.publishB)"
      >
        {{
          formatTimeWithDash(
            isPreviewMode ? detailData.publishB || detailData.publish : detailData.publish,
          )
        }}
      </div>
      <div v-else class="line"></div>
      <!-- 主图 -->
      <!-- <div class="detail-image" v-if="detailData.indexImg">
        <img :src="detailData.indexImg" :alt="detailData.title || '详情图片'" />
      </div> -->

      <!-- 处理后的内容 -->
      <div
        class="detail-text"
        v-if="isPreviewMode ? detailData.contextB || detailData.context : detailData.context"
      >
        <div v-html="processedContent" class="processed-html-content"></div>
      </div>

      <!-- 展览特有按钮 -->
      <div
        class="exhibition-actions"
        v-if="
          fromtype === 'exhibition' &&
          ((isPreviewMode && detailData.webSiteB) || detailData.webSite)
        "
      >
        <div class="online-exhibition-btn" @click="goToOnlineExhibition(detailData)">
          <img src="@/assets/exhibition/online-kz.png" alt="线上观展" class="btn-icon" />
          线上观展
        </div>
      </div>
      <div
        v-if="detailData.personCount > 0 && fromtype == 'activity' && isFrom != 'weixin'"
        class="active-preview-btn"
      >
        <a class="preview-btn"> 活动预约 </a>
      </div>
    </div>

    <!-- 错误状态 -->
    <div v-else class="error-state">
      <div class="error-text">加载失败，请重试</div>
      <button class="retry-button" @click="loadDetailData">重新加载</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { museumApi } from '@/api/indexPage'
import { processHtmlContent } from '@/utils/htmlProcessor'

const router = useRouter()
const route = useRoute()

// 响应式数据
const loading = ref(false)
const detailData = ref(null)
const fromtype = ref('')
const isFrom = ref('')

// 检查是否为预览模式
const isPreviewMode = computed(() => {
  return route.query.preview == '1'
})

// 处理后的HTML内容
const processedContent = computed(() => {
  let content
  if (isPreviewMode.value) {
    // 预览模式下优先使用带B后缀的字段
    content = detailData.value?.contextB || detailData.value?.context
  } else {
    content = detailData.value?.context
  }
  return content ? processHtmlContent(content) : ''
})

// 格式化时间（横线分隔）
const formatTimeWithDash = (timeStr) => {
  if (!timeStr) return ''
  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')
  return `${year}-${month}-${day}`
}

// 返回上一页
const goBack = () => {
  // 检查URL中是否有isFromPage参数
  const isFromPage = route.query.isFromPage

  if (isFromPage) {
    // 如果有isFromPage参数，直接跳转到指定页面并带上preview=1参数
    router.replace(`/${isFromPage}?preview=1`)
  } else {
    router.go(-1)
  }
}

// 跳转到线上观展
const goToOnlineExhibition = (detailData) => {
  let targetUrl
  // 如果URL包含preview=1参数，优先使用webSiteB
  if (isPreviewMode.value && detailData.webSiteB) {
    targetUrl = detailData.webSiteB
  } else {
    targetUrl = detailData.webSite
  }

  if (targetUrl) {
    window.open(targetUrl, '_blank')
  }
}

// 加载详情数据
const loadDetailData = async () => {
  let id, type
  // 从route.query获取id和type
  const routeParams = route.query
  isFrom.value = routeParams.isFrom
  id = routeParams.id
  type = routeParams.type

  fromtype.value = type
  if (!id) {
    console.error('缺少ID参数')
    return
  }

  loading.value = true

  try {
    let response

    // 根据类型调用不同的接口
    switch (type) {
      case 'information':
        response = await museumApi.getInformationDetail(id)
        break
      case 'exhibition':
        response = await museumApi.getExhibitDetail(id)
        break
      case 'activity':
        response = await museumApi.getActivityDetail(id)
        break
      case 'news':
        response = await museumApi.getNewsDetail(id)
        break
      case 'museum':
        response = await museumApi.getMuseumDetail(1)
        break
      default:
        console.error('未知的详情类型:', type)
        return
    }
    if (response) {
      detailData.value = response
    }
  } catch (error) {
    console.error('获取详情数据失败:', error)
    detailData.value = null
  } finally {
    loading.value = false
  }
}

// 页面初始化
onMounted(() => {
  loadDetailData()
})
</script>

<style lang="scss" scoped>
.detail-container {
  position: relative;
  height: 100vh;
  padding: 20px 20px 120px 20px; /* 增加底部padding，为按钮留出空间 */
  background: url('@/assets/indexPage/bg.png') no-repeat;
  background-size: cover;
  overflow-y: auto;
}

@media (min-width: 1024px) {
  .detail-container {
    width: 400px;
  }
}

.back-button {
  position: absolute;
  top: 20px;
  left: 20px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  cursor: pointer;
  z-index: 10;

  img {
    width: 40px;
    height: 40px;
  }
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;

  .loading-text {
    font-size: 16px;
    color: #666;
  }
}

.detail-content {
  margin-top: 40px;
  padding: 8px;
  border-radius: 10px;
}

.detail-title {
  font-size: 24px;
  font-weight: bold;
  color: #584735;
  margin-bottom: 10px;
  line-height: 1.4;
}

.detail-time {
  font-size: 14px;
  color: #584735;
  margin-bottom: 10px;
}

.line {
  height: 2px;
  background: linear-gradient(90deg, rgba(91, 71, 46, 0.5) 0%, rgba(91, 71, 46, 0) 100%);
}

.detail-image {
  text-align: center;

  img {
    max-width: 100%;
    height: auto;
  }
}

.detail-text {
  font-size: 16px;
  line-height: 1.6;
  color: #584735;
  margin-top: 20px;

  :deep(p) {
    margin-bottom: 15px;
  }

  :deep(img) {
    max-width: 100%;
    height: auto;
  }
}

.detail-description {
  font-size: 16px;
  line-height: 1.6;
  color: #584735;
  margin-top: 20px;
}

.error-state {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 200px;

  .error-text {
    font-size: 16px;
    color: #584735;
    margin-bottom: 20px;
  }

  .retry-button {
    padding: 10px 20px;
    background: #007bff;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 14px;

    &:hover {
      background: #0056b3;
    }
  }
}

/* 展览特有按钮样式 */
.exhibition-actions {
  position: fixed;
  bottom: 40px;
  left: 0;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;

  .online-exhibition-btn {
    width: 280px;
    height: 60px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 12px 40px;
    background: linear-gradient(135deg, #b8956a 0%, #a0845a 100%);
    color: white;
    border: none;
    border-radius: 50px;
    cursor: pointer;
    font-size: 16px;
    font-weight: 500;
    transition: all 0.3s ease;
    box-shadow: 0 4px 12px rgba(184, 149, 106, 0.3);

    .btn-icon {
      width: 20px;
      height: 20px;
      margin-right: 8px;
    }

    // &:hover {
    //   background: linear-gradient(135deg, #a0845a 0%, #8b7249 100%);
    //   transform: translateY(-2px);
    //   box-shadow: 0 6px 16px rgba(184, 149, 106, 0.4);
    // }

    // &:active {
    //   transform: translateY(0);
    // }
  }
}

.active-preview-btn {
  position: fixed;
  bottom: 40px;
  left: 0;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;

  .preview-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 280px;
    height: 60px;
    background: linear-gradient(135deg, #b1967b 0%, #9a7f69 100%);
    color: #fff;
    border-radius: 25px;
    font-size: 16px;
    font-weight: 500;
    transition: all 0.3s ease;
    box-shadow: 0 4px 12px rgba(177, 150, 123, 0.3);
    cursor: pointer;
    text-decoration: none;

    // &:hover {
    //   background: linear-gradient(135deg, #9a7f69 0%, #836c59 100%);
    //   transform: translateY(-2px);
    //   box-shadow: 0 6px 16px rgba(177, 150, 123, 0.4);
    // }

    // &:active {
    //   transform: translateY(0);
    // }
  }
}

/* 处理后的HTML内容样式 */
.processed-html-content {
  /* 缩进段落样式 */
  :deep(.indent) {
    text-indent: 2em;
    margin-bottom: 10px;
    line-height: 1.6;
    color: #584735;
  }

  /* 缩进文本样式 */
  :deep(.indent-text) {
    margin-left: 2em;
  }

  /* 处理后的图片容器样式 */
  :deep(.processed-image) {
    margin: 20px 0;
    text-align: center;
    border-radius: 8px;
  }

  /* 内容图片样式 */
  :deep(.content-image) {
    max-width: 100%;
    height: auto;
    transition: transform 0.3s ease;
  }

  :deep(.image-wrap) {
    width: 100%;
  }

  :deep(.content-image:hover) {
    transform: scale(1.02);
  }

  /* 处理后的音频容器样式 */
  :deep(.processed-audio) {
    margin: 15px 0;
    padding: 15px;
    text-align: center;
  }

  /* 处理后的视频容器样式 */
  :deep(.processed-video) {
    width: 100%;
    margin: 20px 0;
    text-align: center;
  }

  :deep(.video-wrap) {
    width: 100%;
  }

  /* 通用媒体容器样式 */
  :deep(.media-wrap) {
    position: relative;
    overflow: hidden;
  }

  /* 段落基础样式 */
  :deep(p) {
    margin-bottom: 10px;
    line-height: 1.6;
    color: #584735;
  }

  /* 图片基础样式 */
  :deep(img) {
    max-width: 100%;
    height: auto;
    margin: 10px 0;
  }
}

/* 响应式处理 */
@media (max-width: 768px) {
  .processed-html-content {
    :deep(.processed-image) {
      margin: 0;
      padding: 0;
    }

    :deep(.indent) {
      text-indent: 1.5em;
    }

    :deep(.indent-text) {
      margin-left: 1.5em;
    }
  }
}
</style>
