<template>
  <div class="collect-detail-container">
    <!-- 顶部固定导航 -->
    <div class="top-navigation">
      <!-- 返回按钮 -->
      <div v-if="isFrom !== 'weixin'" class="back-button" @click="goBack">
        <img src="@/assets/indexPage/icon_back.png" alt="返回" />
      </div>
      <!-- 自定义标签页导航 -->
      <div class="custom-tabs">
        <div
          class="tab-item"
          :class="{ active: activeTab === 'model' }"
          @click="switchTab('model')"
        >
          模型
        </div>
        <div
          class="tab-item"
          :class="{ active: activeTab === 'video' }"
          @click="switchTab('video')"
        >
          视频
        </div>
        <div
          class="tab-item"
          :class="{ active: activeTab === 'image' }"
          @click="switchTab('image')"
        >
          图片
        </div>
      </div>
    </div>

    <!-- 内容展示区域 -->
    <div class="content-display" :class="{ zoomed: isZoomed }">
      <!-- 模型展示 -->
      <div v-if="activeTab === 'model'" class="model-viewer">
        <div class="model-container">
          <iframe
            id="ifr"
            v-if="getFieldValue(artifactData, 'modelFile')"
            :src="`${getFieldValue(artifactData, 'modelFile')}`"
            frameborder="0"
          ></iframe>
          <div v-else class="no-video">
            <div class="no-video-text">暂无模型</div>
          </div>
        </div>
        <!-- 放大镜图标 -->
        <div v-if="getFieldValue(artifactData, 'modelFile')" class="zoom-icon" @click="toggleZoom">
          <el-icon style="color: #EFDBAC" :size="24">
            <ZoomIn v-if="!isZoomed" />
            <ZoomOut v-else />
          </el-icon>
        </div>
      </div>

      <!-- 视频展示 -->
      <div v-if="activeTab === 'video'" class="video-viewer">
        <div class="video-container">
          <video
            width="320"
            height="240"
            v-if="getFieldValue(artifactData, 'videoFile')"
            controls
            x5-video-player-type="h5"
            playsinline
            webkit-playsinline
          >
            <source :src="getFieldValue(artifactData, 'videoFile')" type="video/mp4" />
            您的浏览器不支持视频播放。
          </video>
          <div v-else class="no-video">
            <div class="no-video-text">暂无视频资源</div>
          </div>
        </div>
      </div>

      <!-- 图片展示 -->
      <div v-if="activeTab === 'image'" class="image-viewer">
        <div class="image-container">
          <el-carousel
            v-if="
              getFieldValue(artifactData, 'imageFiles') &&
              getFieldValue(artifactData, 'imageFiles').length > 0
            "
            height="90%"
            arrow="hover"
            ref="slideCarousel"
            @change="setActiveItem"
            :autoplay="autoplayEnabled"
            :interval="4000"
            :pause-on-hover="false"
          >
            <el-carousel-item
              v-for="(image, index) in getFieldValue(artifactData, 'imageFiles')"
              :key="index"
            >
              <img :src="image" :alt="`文物图片${index + 1}`" class="carousel-image" />
            </el-carousel-item>
          </el-carousel>
          <div v-else class="no-video">
            <div class="no-video-text">暂无图片</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部固定信息卡片 -->
    <div class="artifact-info-card" :class="{ hidden: isZoomed }">
      <div class="card-content">
        <div class="artifact-title">{{ getFieldValue(artifactData, 'title') || '文物名称' }}</div>
        <div class="artifact-meta">
          <span class="year">{{ getFieldValue(artifactData, 'era') }}</span>
          <span class="source">{{ getFieldValue(artifactData, 'texture') }}</span>
          <span class="level">{{ getFieldValue(artifactData, 'level') || '等级不详' }}</span>
        </div>
        <div class="artifact-size">
          {{
            getFieldValue(artifactData, 'size') ||
            getFieldValue(artifactData, 'dimensions') ||
            '尺寸不详'
          }}
        </div>
        <div class="divider"></div>
        <div class="artifact-description">
          {{ getFieldValue(artifactData, 'remark') }}
        </div>
      </div>
    </div>

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

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

const router = useRouter()
const route = useRoute()
const activeTab = ref('model')
const loading = ref(false)
const artifactData = ref({})
const isZoomed = ref(false)
const isFrom = ref('')
const autoplayEnabled = ref(true)

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

// 获取字段值的通用方法，优先获取带B后缀的字段
const getFieldValue = (item, fieldName) => {
  if (isPreviewMode.value) {
    return item[fieldName + 'B'] || item[fieldName]
  }
  return item[fieldName]
}

// 返回上一页
const goBack = () => {
  // 如果当前URL包含preview=1参数，则在返回时保持该参数
  if (isPreviewMode.value) {
    router.replace('/collection?preview=1')
  } else {
    router.replace('/collection')
  }
}
// 获取文物详情数据
const getArtifactDetail = async () => {
  let id
  // 从route.query获取id和type
  const routeParams = route.query
  id = routeParams.id
  isFrom.value = routeParams.isFrom

  loading.value = true
  try {
    const response = await museumApi.getArtifactDetail(id)
    console.log('文物详情数据:', response)

    if (response) {
      artifactData.value = response
    }
  } catch (error) {
    console.error('获取文物详情失败:', error)
  } finally {
    loading.value = false
  }
}

// 切换标签页
const switchTab = (tab) => {
  activeTab.value = tab
  if (isZoomed.value) {
    toggleZoom()
  }
  if (activeTab.value === 'image') {
    slideBanner()
  }
}

// 切换放大缩小状态
const toggleZoom = () => {
  isZoomed.value = !isZoomed.value

  if (activeTab.value === 'model') {
    const dom = document.querySelector('#ifr')
    if (dom && dom.contentWindow && dom.contentWindow.webview) {
      if (isZoomed.value) {
        dom.contentWindow.webview.zoomIn()
      } else {
        dom.contentWindow.webview.zoomOut()
      }
    }
  }
}

// 轮播图引用
const slideCarousel = ref(null)

// 轮播图切换事件
const setActiveItem = (index) => {
  console.log('轮播图切换到:', index)
}

// 重新启动自动播放
const restartAutoplay = () => {
  // 通过动态控制autoplay属性来重新启动自动播放
  autoplayEnabled.value = false
  nextTick(() => {
    autoplayEnabled.value = true
  })
}

// 滑动切换
const slideBanner = () => {
  // 等待DOM更新后再添加事件监听
  nextTick(() => {
    const box = document.querySelector('.el-carousel__container')
    if (!box) return

    let startPoint = 0
    let stopPoint = 0
    let isDragging = false

    // 重置坐标
    const resetPoint = () => {
      startPoint = 0
      stopPoint = 0
      isDragging = false
    }

    // 处理滑动切换逻辑
    const handleSlideChange = () => {
      if (stopPoint === 0 || startPoint - stopPoint === 0) {
        resetPoint()
        return
      }

      if (slideCarousel.value) {
        if (startPoint - stopPoint > 0) {
          // 向左滑动，下一张
          slideCarousel.value.next()
        } else {
          // 向右滑动，上一张
          slideCarousel.value.prev()
        }
      }
      resetPoint()
    }

    // 移除之前的事件监听器（避免重复绑定）
    box.removeEventListener('touchstart', handleTouchStart)
    box.removeEventListener('touchmove', handleTouchMove)
    box.removeEventListener('touchend', handleTouchEnd)
    box.removeEventListener('mousedown', handleMouseDown)
    box.removeEventListener('mousemove', handleMouseMove)
    box.removeEventListener('mouseup', handleMouseUp)
    box.removeEventListener('mouseleave', handleMouseLeave)

    // === 触摸事件处理 ===
    // 手指按下
    function handleTouchStart(e) {
      startPoint = e.changedTouches[0].pageX
    }

    // 手指滑动
    function handleTouchMove(e) {
      stopPoint = e.changedTouches[0].pageX
    }

    // 手指抬起
    function handleTouchEnd() {
      handleSlideChange()
      // 重新启动自动播放
      restartAutoplay()
    }

    // === 鼠标事件处理 ===
    // 鼠标按下
    function handleMouseDown(e) {
      isDragging = true
      startPoint = e.pageX
      box.style.cursor = 'grabbing'
      // 阻止默认的拖拽行为
      e.preventDefault()
    }

    // 鼠标移动
    function handleMouseMove(e) {
      if (!isDragging) return
      stopPoint = e.pageX
      // 阻止默认行为
      e.preventDefault()
    }

    // 鼠标抬起
    function handleMouseUp() {
      if (!isDragging) return
      box.style.cursor = 'grab'
      handleSlideChange()
      // 重新启动自动播放
      restartAutoplay()
    }

    // 鼠标离开容器
    function handleMouseLeave() {
      if (!isDragging) return
      box.style.cursor = 'grab'
      handleSlideChange()
      // 重新启动自动播放
      restartAutoplay()
    }

    // 添加触摸事件监听器
    box.addEventListener('touchstart', handleTouchStart)
    box.addEventListener('touchmove', handleTouchMove)
    box.addEventListener('touchend', handleTouchEnd)

    // 添加鼠标事件监听器
    box.addEventListener('mousedown', handleMouseDown)
    box.addEventListener('mousemove', handleMouseMove)
    box.addEventListener('mouseup', handleMouseUp)
    box.addEventListener('mouseleave', handleMouseLeave)

    // 设置初始鼠标样式
    box.style.cursor = 'grab'
  })
}

// 初始化
onMounted(() => {
  getArtifactDetail()
})
</script>

<style lang="scss" scoped>
.collect-detail-container {
  position: relative;
  height: 100vh;
  background: #fff;
  background-size: cover;
}

.top-navigation {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  padding: 20px;
  z-index: 100;
}

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

  .top-navigation {
    max-width: 400px;
  }
}

.back-button {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  cursor: pointer;
  margin-right: 20px;

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

.custom-tabs {
  flex: 1;
  display: flex;
  justify-content: center;
  max-width: 200px;
  margin: 0 auto;

  .tab-item {
    width: 72px;
    text-align: center;
    color: #ffffff;
    font-size: 16px;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
    border-bottom: 2px solid transparent;

    &.active {
      color: #ffffff;
      font-weight: bold;
      border-bottom-color: #f3b200;
    }

    &:hover:not(.active) {
      color: rgba(245, 245, 220, 1);
    }
  }
}

.content-display {
  height: 55%;
  background: linear-gradient(180deg, #372918 0%, #776655 100%);
  padding: 20px 0;
  transition: height 0.3s ease;

  &.zoomed {
    height: 100%;
  }
}

.content-area {
  margin: 20px 0;
  display: flex;
  justify-content: center;
}

.model-viewer,
.video-viewer,
.image-viewer {
  position: relative;
  width: 100%;
  height: 100%;
}

.model-container,
.video-container,
.image-container {
  height: 100%;
  position: relative;
  overflow: hidden;

  img,
  video {
    width: 100%;
    height: auto;
    display: block;
  }

  iframe {
    width: 100%;
    height: 100%;
  }

  .el-carousel {
    height: 96%;

    .el-carousel__container {
      height: 100%;
    }

    .el-carousel__item {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100%;
    }

    /*指示器按钮*/
    :deep(.el-carousel__button) {
      width: 10px;
      height: 10px;
      border: none;
      border-radius: 50%;
      background-color: rgba(255, 255, 255, 0.5);
      // margin-left: 6px;
    }

    /*指示器激活按钮*/
    :deep(.is-active) {
      .el-carousel__button {
        background-color: #fff;
      }
    }
  }

  .carousel-image {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
  }

  .no-image {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
  }

  .placeholder-image {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
    opacity: 0.6;
  }
}

.video-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.zoom-icon {
  position: absolute;
  bottom: 36px;
  right: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.artifact-info-card {
  position: absolute;
  top: 48%;
  max-height: 52%;
  width: 100%;
  background: #fff;
  border-radius: 15px;
  padding: 20px;
  margin: 20px 0;
  overflow: auto;
  transition:
    opacity 0.3s ease,
    visibility 0.3s ease;

  &.hidden {
    opacity: 0;
    visibility: hidden;
  }

  .artifact-title {
    font-size: 20px;
    font-weight: bold;
    color: #584735;
    margin-bottom: 10px;
  }

  .artifact-meta {
    display: flex;
    gap: 15px;
    margin-bottom: 8px;
    font-size: 14px;
    color: #666;

    .year {
      color: #8b5d3b;
      font-weight: 500;
    }

    .source {
      color: #666;
    }

    .level {
      color: #8b5d3b;
      font-weight: 500;
    }
  }

  .artifact-size {
    font-size: 14px;
    color: #666;
    margin-bottom: 15px;
  }

  .divider {
    width: 100%;
    height: 2px;
    background: linear-gradient(to right, #8b5d3b, transparent);
    margin-bottom: 15px;
  }

  .artifact-description {
    font-size: 13px;
    line-height: 1.6;
    color: #444;
    text-align: justify;
  }
}

@media (max-width: 480px) {
  .collect-detail-container {
  }

  .tab-navigation {
    max-width: 280px;
    margin: 50px auto 15px;

    .tab-item {
      padding: 8px 15px;
      font-size: 13px;
    }
  }

  .artifact-info {
    padding: 15px;

    .artifact-title {
      font-size: 18px;
    }

    .artifact-description {
      font-size: 12px;
    }
  }
}

.no-video {
  height: 96%;
  display: flex;
  justify-content: center;
  align-items: center;

  .no-video-text {
    color: #fff;
  }
}
</style>
