<template>
  <div class="workflow-detail page-content" :class="{ protected: enablePageProtection }">
    <div class="workflow-container breadcrumb-container">
      <!-- 面包屑导航 -->
      <div class="breadcrumb">
        <span @click="goBack" class="back-link">← 返回</span>
        <span class="separator">/</span>
        <span class="current-page">{{ workflowData.name || '工作流详情' }}</span>
      </div>
    </div>

    <!-- 深色视频模块 -->
    <section class="video-module">
      <div class="video-inner">
        <!-- 视频播放区域 -->
        <div class="video-section">
          <div class="video-container">
            <!-- 视频播放器 -->
            <div class="video-player">
              <!-- 阿里云播放器 -->
              <AliyunPlayer
                v-if="workflowData.vodVideoId && showPlayer"
                ref="playerRef"
                :video-id="workflowData.vodVideoId"
                :workflow-id="workflowData.id || route.params.id"
                width="100%"
                height="100%"
                :autoplay="true"
                :controls="true"
                @play="handleVideoPlay"
                @pause="handleVideoPause"
                @ended="handleVideoEnded"
                @error="handleVideoError"
                @ready="handlePlayerReady"
              />
              
              <!-- 工作流封面显示（未开始播放时） -->
              <div v-else class="workflow-cover-display" @click="startVideoPlay">
                <img 
                  :src="workflowData.coverUrl || 'https://picsum.photos/980/666'" 
                  :alt="workflowData.name || '工作流封面'" 
                  class="workflow-main-cover"
                  @error="handleImageError"
                />
                <div class="cover-overlay-content">
                  <div v-if="workflowData.vodVideoId" class="play-icon">▶</div>
                  <div v-else class="workflow-icon">🔧</div>
                  
                  <p class="workflow-title">{{ workflowData.name || '工作流详情' }}</p>
                  <p class="workflow-subtitle">
                    {{ workflowData.vodVideoId ? '点击观看演示视频' : '查看工作流详情' }}
                  </p>
                </div>
              </div>
            </div>
            
            <!-- 工作流信息面板 -->
            <div v-if="isPermissionReady" class="workflow-info-panel">
              <!-- 创建者信息 -->
              <div class="creator-info-section">
                <div class="creator-info-left">
                  <div class="creator-avatar">
                    <img :src="workflowData.creator?.avatarUrl" :alt="workflowData.creator?.username" />
                  </div>
                  <div class="creator-info-text">
                    <div class="creator-name">作者：{{ workflowData.creator?.username }}</div>
                    <div class="workflow-category">分类：{{ workflowData.category }}</div>
                  </div>
                </div>
                <div class="creator-info-right">
                  <button class="favorite-btn" :class="{ favorited: isFavorited }" @click="toggleFavorite">
                    <svg v-if="!isFavorited" width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path d="M12 2L14.09 8.26L22 9.27L17 14.14L18.18 22.02L12 18.77L5.82 22.02L7 14.14L2 9.27L9.91 8.26L12 2Z" stroke="currentColor" stroke-width="2" fill="none"/>
                    </svg>
                    <svg v-else width="16" height="16" viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
                      <path d="M12 2L14.09 8.26L22 9.27L17 14.14L18.18 22.02L12 18.77L5.82 22.02L7 14.14L2 9.27L9.91 8.26L12 2Z"/>
                    </svg>
                    <span>{{ isFavorited ? '已收藏' : '收藏' }}</span>
                  </button>
                </div>
              </div>
              
              <!-- 工作流统计信息 -->
              <div class="workflow-stats">
                <div class="stat-item">
                  <span class="stat-label">收藏数：</span>
                  <span class="stat-value">{{ workflowData.likeCount || 0 }}</span>
                </div>
                <div class="stat-item">
                  <span class="stat-label">使用次数：</span>
                  <span class="stat-value">{{ workflowData.copyCount || 0 }}</span>
                </div>
                <div class="stat-item">
                  <span class="stat-label">评分：</span>
                  <div class="rating">
                    <span v-for="i in 5" :key="i" class="star" :class="{ active: i <= workflowData.rating }">⭐</span>
                    <span class="rating-text">{{ workflowData.rating }}/5</span>
                  </div>
                </div>
              </div>
              
                      <!-- 权限信息和操作按钮 -->
        <div class="workflow-actions">
          <!-- 权限信息显示（仅在权限不足时显示） -->
          <div v-if="userPermission.showPermissionInfo" class="permission-info">
            <div class="permission-item">
              <span class="permission-label">完整访问权限：</span>
              <span class="permission-value">{{ workflowData.fullAccessRoleName }}</span>
            </div>
            <div class="permission-item">
              <span class="permission-label">复制权限：</span>
              <span class="permission-value">{{ workflowData.copyAccessRoleName }}</span>
            </div>
          </div>
                
                <div class="action-buttons">
                  <button 
                    v-if="userPermission.hasFullAccess && workflowData.hasDataFile" 
                    class="action-btn download-btn" 
                    @click="downloadDataFile"
                    :disabled="downloadingDataFile"
                  >
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path d="M21 15V19C21 20.1046 20.1046 21 19 21H5C3.89543 21 3 20.1046 3 19V15M17 10L12 15L7 10M12 15V3" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                    {{ downloadingDataFile ? '下载中...' : '下载数据包' }}
                  </button>
                  
                  <button 
                    v-if="userPermission.hasCopyAccess && workflowData.hasJsonData" 
                    class="action-btn copy-btn" 
                    @click="copyJsonData"
                    :disabled="copyingJsonData"
                  >
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path d="M16 4H18C19.1046 4 20 4.89543 20 6V18C20 19.1046 19.1046 20 18 20H6C4.89543 20 4 19.1046 4 18V6C4 4.89543 4.89543 4 6 4H8" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                      <rect x="8" y="2" width="8" height="4" rx="1" ry="1" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                    {{ copyingJsonData ? '复制中...' : '复制JSON数据' }}
                  </button>
                  
                  <!-- 权限不足提示 -->
                  <div v-if="!userPermission.hasFullAccess || !userPermission.hasCopyAccess" class="permission-notice">
                    <!-- 赠送会员特殊提示（仅在VIP工作流中显示） -->
                    <div v-if="userPermission.isGiftMember && (!userPermission.hasFullAccess || !userPermission.hasCopyAccess) && 
                             (workflowData.fullAccessRole === 2 || workflowData.copyAccessRole === 2)" class="gift-member-notice">
                      <div class="gift-member-icon">🎁</div>
                      <p class="gift-member-title">赠送会员限制</p>
                      <p class="gift-member-desc">
                        您当前是赠送会员，可以观看所有视频内容，但暂不支持下载数据包和复制JSON数据功能
                      </p>
                    </div>
                    
                    <!-- 普通权限不足提示（包括SVIP工作流中的赠送会员） -->
                    <div v-else-if="!userPermission.isGiftMember || 
                                   (userPermission.isGiftMember && 
                                    workflowData.fullAccessRole > 2 || workflowData.copyAccessRole > 2)">
                      <p v-if="!userPermission.hasFullAccess">
                        需要{{ userPermission.requiredFullAccessLevelName || workflowData.fullAccessRoleName }}权限才能下载数据包
                      </p>
                      <p v-if="!userPermission.hasCopyAccess">
                        需要{{ userPermission.requiredCopyLevelName || workflowData.copyAccessRoleName }}权限才能复制JSON数据
                      </p>
                    </div>
                    
                    <!-- 显示升级按钮，让用户可以升级获得更多权限 -->
                    <div v-if="userPermission.accessDeniedReason || (!userPermission.hasFullAccess || !userPermission.hasCopyAccess)">
                      <p v-if="userPermission.accessDeniedReason" class="access-reason">
                        {{ userPermission.accessDeniedReason }}
                      </p>
                      <button class="upgrade-btn" @click="showMembershipPrompt">
                        {{ userPermission.isGiftMember && (workflowData.fullAccessRole === 2 || workflowData.copyAccessRole === 2) ? '升级为正式会员' : '升级权限' }}
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- 页面下方白色模块 -->
    <div class="workflow-container">
      <div class="below-module">
        <!-- 工作流简介 -->
        <div class="workflow-description">
          <h3>工作流简介</h3>
          <div 
            v-if="isRichText(workflowData.description)"
            class="rich-text-content"
            v-html="addRichTextStyles(workflowData.description)"
          ></div>
          <p v-else>{{ workflowData.description }}</p>
        </div>
        
        <!-- 详情图集 -->
        <div v-if="detailGallery.length > 0" class="detail-gallery-section">
          <!-- 图集网格内容 -->
          <div class="gallery-grid">
            <div 
              v-for="(imageUrl, index) in detailGallery" 
              :key="index"
              class="gallery-item"
              @click="openImageViewer(index)"
            >
              <!-- 图片骨架屏占位 -->
              <div v-if="galleryLoading" class="skeleton-image-placeholder">
                <div class="skeleton-image"></div>
              </div>
              
              <!-- 实际图片 -->
              <img 
                :src="imageUrl" 
                alt="工作流详细内容"
                @load="handleGalleryImageLoad"
                @error="handleGalleryImageError"
                class="gallery-image"
                :class="{ 'image-loaded': !galleryLoading }"
              />
              
              <div class="gallery-overlay" :class="{ 'overlay-visible': !galleryLoading }">
                <div class="gallery-zoom-icon">
                  <el-icon :size="24">
                    <ZoomIn />
                  </el-icon>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 会员开通提醒弹窗 -->
        <div v-if="showMembershipDialog" class="membership-dialog-overlay" @click="closeMembershipDialog">
          <div class="membership-dialog" @click.stop>
            <div class="dialog-header">
              <div class="dialog-icon">
                <svg width="48" height="48" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M12 2L14.09 8.26L22 9.27L17 14.14L18.18 22.02L12 18.77L5.82 22.02L7 14.14L2 9.27L9.91 8.26L12 2Z" fill="#3b82f6"/>
                </svg>
              </div>
              <h3>升级权限</h3>
              <button class="dialog-close" @click="closeMembershipDialog">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M18 6L6 18M6 6L18 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
              </button>
            </div>
            <div class="dialog-content">
              <!-- 赠送会员专门的提示内容（仅在VIP工作流中显示） -->
              <div v-if="userPermission.isGiftMember && (!userPermission.hasFullAccess || !userPermission.hasCopyAccess) &&
                         (workflowData.fullAccessRole === 2 || workflowData.copyAccessRole === 2)" class="gift-member-dialog-content">
                <div class="gift-member-badge">
                  <span class="gift-icon">🎁</span>
                  <span class="gift-text">赠送会员</span>
                </div>
                <p class="dialog-message">
                  感谢您使用我们的服务！您当前是赠送会员，享有2天的视频观看权限。
                </p>
                <p class="upgrade-message">
                  升级为正式会员，解锁完整功能：
                </p>
              </div>
              
              <!-- 普通用户提示内容 -->
              <p v-else class="dialog-message">
                {{ userPermission.accessDeniedReason || '该工作流需要更高权限才能访问，立即升级享受更多功能！' }}
              </p>
              
              <div class="membership-benefits">
                <div class="benefit-item">
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M20 6L9 17L4 12" stroke="#10b981" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                  </svg>
                  <span>无限制访问所有工作流</span>
                </div>
                <div class="benefit-item">
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M20 6L9 17L4 12" stroke="#10b981" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                  </svg>
                  <span>下载所有工作流数据包</span>
                </div>
                <div class="benefit-item">
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M20 6L9 17L4 12" stroke="#10b981" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                  </svg>
                  <span>复制JSON数据自由使用</span>
                </div>
                <div v-if="userPermission.isGiftMember && (!userPermission.hasFullAccess || !userPermission.hasCopyAccess) &&
                           (workflowData.fullAccessRole === 2 || workflowData.copyAccessRole === 2)" class="benefit-item">
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M20 6L9 17L4 12" stroke="#10b981" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                  </svg>
                  <span>长期会员权限，无时间限制</span>
                </div>
              </div>
            </div>
            <div class="dialog-actions">
              <button class="dialog-btn secondary" @click="closeMembershipDialog">
                稍后再说
              </button>
              <button class="dialog-btn primary" @click="goToMembership">
                {{ userPermission.isGiftMember && (!userPermission.hasFullAccess || !userPermission.hasCopyAccess) && 
                   (workflowData.fullAccessRole === 2 || workflowData.copyAccessRole === 2) ? '升级为正式会员' : '立即升级' }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <Footer />
    
    <!-- 登录弹窗 -->
    <LoginModal
      :visible="showLoginModal"
      mode="login"
      @close="closeLoginModal"
      @login="handleLoginSuccess"
    />
    
    <!-- 图片查看器 -->
    <div v-if="showImageViewer" class="image-viewer-overlay" @click="closeImageViewer">
      <div class="image-viewer" @click.stop>
        <div class="image-viewer-header">
          <span class="image-counter">{{ currentImageIndex + 1 }} / {{ detailGallery.length }}</span>
          <button class="image-viewer-close" @click="closeImageViewer">
            <el-icon :size="20">
              <Close />
            </el-icon>
          </button>
        </div>
        
        <div 
          class="image-viewer-content"
          @touchstart="handleTouchStart"
          @touchmove="handleTouchMove"
          @touchend="handleTouchEnd"
        >
          <button 
            v-if="detailGallery.length > 1" 
            class="image-nav-btn prev-btn" 
            @click="prevImage"
          >
            <el-icon :size="24">
              <ArrowLeft />
            </el-icon>
          </button>
          
          <img 
            :src="detailGallery[currentImageIndex]" 
            alt="工作流详细内容"
            class="viewer-image"
            @click.stop
          />
          
          <button 
            v-if="detailGallery.length > 1" 
            class="image-nav-btn next-btn" 
            @click="nextImage"
          >
            <el-icon :size="24">
              <ArrowRight />
            </el-icon>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import Footer from '@/components/Footer.vue'
import LoginModal from '@/components/LoginModal.vue'
import AliyunPlayer from '@/components/AliyunPlayer.vue'
import { 
  getWorkflowDetail, 
  toggleWorkflowFavorite, 
  getWorkflowDataFile, 
  getWorkflowJsonData,
  checkWorkflowLikeStatus
} from '@/api/workflow.js'
import { getPlayAuth } from '@/api/vod.js'
import { isLoggedIn, handleAuthFailure } from '@/utils/auth.js'
import { useUserStore } from '@/store/user.js'
import { getCurrentUser } from '@/api/user.js'
import { isRichText, addRichTextStyles } from '@/utils/richText.js'

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

// 工作流数据
const workflowData = ref({})

// 详情图集数据
const detailGallery = ref([])
const galleryLoading = ref(true)
const loadedImageCount = ref(0)
const successImageCount = ref(0)

// 图片查看器状态
const showImageViewer = ref(false)
const currentImageIndex = ref(0)

// 用户权限信息
const userPermission = ref({
  userRole: 0,
  userRoleName: '',
  requiredFullAccessLevel: 1,
  requiredFullAccessLevelName: '',
  requiredCopyLevel: 2,
  requiredCopyLevelName: '',
  hasFullAccess: false,
  hasCopyAccess: false,
  accessDeniedReason: null,
  showPermissionInfo: false, // 添加权限信息显示控制字段
  membershipExpiresAt: null
})

// 播放器相关状态
const showPlayer = ref(false)
const playerRef = ref(null)

// 收藏状态
const isFavorited = ref(false)

// 登录弹窗状态
const showLoginModal = ref(false)

// 会员开通弹窗状态
const showMembershipDialog = ref(false)

// 下载状态
const downloadingDataFile = ref(false)
const copyingJsonData = ref(false)

// 是否启用页面保护
const enablePageProtection = ref(false)

// 标识是否是首次加载
const isInitialLoad = ref(true)

// 请求状态管理
const isLoadingWorkflowDetail = ref(false)
const isLoadingUserInfo = ref(false)
const isLoadingFavoriteStatus = ref(false)

// 防抖定时器
let updatePermissionTimer = null

// 权限计算状态
const isPermissionReady = ref(false)
const isUserInfoReady = ref(false)

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 跳转到会员页面
const goToMembership = () => {
  closeMembershipDialog()
  router.push('/membership')
}

// 关闭会员开通弹窗
const closeMembershipDialog = () => {
  showMembershipDialog.value = false
}

// 显示会员开通弹窗
const showMembershipPrompt = () => {
  showMembershipDialog.value = true
}

// 解析详情图集数据
const parseDetailGallery = (galleryStr) => {
  if (!galleryStr) return []
  
  try {
    const parsed = JSON.parse(galleryStr)
    return Array.isArray(parsed) ? parsed : []
  } catch (error) {
    console.error('解析详情图集失败:', error)
    return []
  }
}

// 打开图片查看器
const openImageViewer = (index) => {
  currentImageIndex.value = index
  showImageViewer.value = true
}

// 关闭图片查看器
const closeImageViewer = () => {
  showImageViewer.value = false
}

// 切换到上一张图片
const prevImage = () => {
  currentImageIndex.value = currentImageIndex.value > 0 ? currentImageIndex.value - 1 : detailGallery.value.length - 1
}

// 切换到下一张图片
const nextImage = () => {
  currentImageIndex.value = currentImageIndex.value < detailGallery.value.length - 1 ? currentImageIndex.value + 1 : 0
}

// 处理详情图集图片加载完成
const handleGalleryImageLoad = (event) => {
  const img = event.target
  
  // 检查是否已经被标记过（避免重复计数）
  if (img.dataset.loaded) {
    return
  }
  
  // 标记为已处理
  img.dataset.loaded = 'true'
  
  loadedImageCount.value++
  successImageCount.value++
  console.log(`[WorkflowDetail] 图片加载成功: ${successImageCount.value}/${detailGallery.value.length}`)
  
  if (loadedImageCount.value >= detailGallery.value.length) {
    galleryLoading.value = false
    console.log(`[WorkflowDetail] 图集加载完成: 成功${successImageCount.value}张，失败${loadedImageCount.value - successImageCount.value}张`)
  }
}

// 处理详情图集图片加载错误
const handleGalleryImageError = (event) => {
  const img = event.target
  console.log(`[WorkflowDetail] 图片加载失败:`, img.src)
  
  // 检查是否已经被标记过（避免重复计数）
  if (img.dataset.loaded) {
    return
  }
  
  // 标记为已处理
  img.dataset.loaded = 'true'
  
  // 如果图片加载失败，隐藏该图片
  img.style.display = 'none'
  
  // 只更新已处理计数，不增加成功计数
  loadedImageCount.value++
  
  if (loadedImageCount.value >= detailGallery.value.length) {
    galleryLoading.value = false
    console.log(`[WorkflowDetail] 图集加载完成: 成功${successImageCount.value}张，失败${loadedImageCount.value - successImageCount.value}张`)
    
    // 如果所有图片都加载失败，显示提示信息
    if (successImageCount.value === 0) {
      console.warn('[WorkflowDetail] 所有图片加载失败')
    }
  }
}

// 检查已缓存的图片
const checkCachedImages = () => {
  console.log('[WorkflowDetail] 检查已缓存的图片')
  
  const galleryImages = document.querySelectorAll('.gallery-image')
  console.log(`[WorkflowDetail] 找到 ${galleryImages.length} 个图片元素`)
  
  let cachedCount = 0
  galleryImages.forEach((img, index) => {
    if (img.complete && img.naturalWidth > 0) {
      // 图片已经加载完成，标记避免重复计数
      if (!img.dataset.loaded) {
        img.dataset.loaded = 'true'
        loadedImageCount.value++
        successImageCount.value++
        cachedCount++
        console.log(`[WorkflowDetail] 图片 ${index + 1} 已缓存，直接标记为加载完成`)
      }
    }
  })
  
  console.log(`[WorkflowDetail] 发现 ${cachedCount} 张缓存图片`)
  
  // 检查是否所有图片都已处理
  if (loadedImageCount.value >= detailGallery.value.length) {
    galleryLoading.value = false
    console.log(`[WorkflowDetail] 图集加载完成（包含缓存图片）: 成功${successImageCount.value}张，失败${loadedImageCount.value - successImageCount.value}张`)
  } else {
    // 如果还有图片未加载完成，设置一个超时检查
    setTimeout(() => {
      if (galleryLoading.value && loadedImageCount.value < detailGallery.value.length) {
        console.log('[WorkflowDetail] 图片加载超时，强制结束加载状态')
        galleryLoading.value = false
      }
    }, 5000) // 5秒超时
  }
}

// 键盘事件处理
const handleKeyDown = (event) => {
  if (!showImageViewer.value) return
  
  switch (event.key) {
    case 'Escape':
      closeImageViewer()
      break
    case 'ArrowLeft':
      prevImage()
      break
    case 'ArrowRight':
      nextImage()
      break
  }
}

// 触摸事件处理（移动端滑动支持）
const touchStartX = ref(0)
const touchEndX = ref(0)

const handleTouchStart = (event) => {
  touchStartX.value = event.touches[0].clientX
}

const handleTouchMove = (event) => {
  touchEndX.value = event.touches[0].clientX
}

const handleTouchEnd = () => {
  if (!showImageViewer.value || detailGallery.value.length <= 1) return
  
  const swipeDistance = touchStartX.value - touchEndX.value
  const minSwipeDistance = 50
  
  if (Math.abs(swipeDistance) > minSwipeDistance) {
    if (swipeDistance > 0) {
      // 向左滑动，显示下一张
      nextImage()
    } else {
      // 向右滑动，显示上一张
      prevImage()
    }
  }
}

// 更新用户信息
const updateUserInfo = async () => {
  // 防止重复请求
  if (isLoadingUserInfo.value) {
    console.log('[WorkflowDetail] 用户信息正在加载中，跳过重复请求')
    return
  }
  
  try {
    isLoadingUserInfo.value = true
    console.log('[WorkflowDetail] 开始获取最新用户信息')
    const response = await getCurrentUser()
    console.log('[WorkflowDetail] API响应数据:', response)
    
    if (response.code === 200) {
      console.log('[WorkflowDetail] 更新用户信息到store:', response.data)
      userStore.updateUserInfo(response.data)
      console.log('[WorkflowDetail] 用户信息已更新到store')
      
      // 验证更新后的用户信息
      const updatedUserInfo = userStore.getUserInfo
      console.log('[WorkflowDetail] 验证更新后的用户信息:', updatedUserInfo)
      
      // 使用防抖机制更新权限信息，避免频繁调用
      if (updatePermissionTimer) {
        clearTimeout(updatePermissionTimer)
      }
      
      updatePermissionTimer = setTimeout(() => {
        if (workflowData.value.id) {
          console.log('[WorkflowDetail] 延迟更新权限信息')
          updateWorkflowPermission()
          // 用户信息更新后，立即检查权限准备状态
          checkAndSetPermissionReady()
        }
      }, 100) // 100ms防抖
      
    } else if (response.code === 500) {
      // 特别处理500错误
      console.error('[WorkflowDetail] /me接口返回500错误:', response.message)
      handleAuthFailure(router, response.message || '用户信息获取失败，请重新登录')
    } else {
      console.error('[WorkflowDetail] 获取用户信息失败:', response.message)
    }
  } catch (error) {
    console.error('[WorkflowDetail] 更新用户信息失败:', error)
    
    // 检查是否是500错误
    if (error.response && error.response.status === 500) {
      console.error('[WorkflowDetail] 捕获到/me接口500错误')
      const errorMessage = error.response.data?.message || '用户信息获取失败，请重新登录'
      handleAuthFailure(router, errorMessage)
    } else if (error.response && error.response.status === 401) {
      // 401错误说明认证失败
      console.error('[WorkflowDetail] 捕获到401认证错误，API拦截器应该已经处理，这里作为备用处理')
      // 确保用户信息被清空
      userStore.logout()
      // 跳转到首页并显示提示
      setTimeout(() => {
        router.replace('/')
        ElMessage.error('登录已过期，请重新登录')
      }, 100)
    }
  } finally {
    isLoadingUserInfo.value = false
  }
}

// 开始视频播放
const startVideoPlay = async () => {
  if (!workflowData.value.vodVideoId) {
    ElMessage.info('该工作流没有演示视频')
    return
  }
  
  // 检查用户是否有观看权限 - 使用 hasVideoAccess 判断视频播放权限
  // 赠送会员也可以观看视频，但不能下载和复制
  if (!userPermission.value.hasVideoAccess) {
    console.log('[WorkflowDetail] 用户无视频观看权限，需要', userPermission.value.requiredFullAccessLevelName, '权限，显示会员开通弹窗')
    showMembershipDialog.value = true
    return
  }
  
  // 如果是赠送会员，显示特殊提示但允许观看
  if (userPermission.value.isGiftMember) {
    console.log('[WorkflowDetail] 赠送会员观看视频，功能正常但下载复制受限')
  }
  
  try {
    console.log('[WorkflowDetail] 开始获取视频播放凭证')
    showPlayer.value = true
    
    // 等待DOM更新，确保播放器组件已挂载
    await nextTick()
    
    if (!playerRef.value) {
      console.error('[WorkflowDetail] 播放器引用不存在')
      ElMessage.error('播放器初始化失败')
      return
    }
    
    // 获取播放凭证
    const playAuthData = {
      videoId: workflowData.value.vodVideoId,
      authInfoTimeout: 3600,
      playDomain: window.location.hostname
    }
    
    console.log('[WorkflowDetail] 请求播放凭证:', playAuthData)
    const response = await getPlayAuth(playAuthData)
    
    console.log('[WorkflowDetail] 播放凭证API响应:', response)
    
    // 解析播放凭证数据
    let playAuth, videoMeta
    
    if (response.code === 200 && response.data) {
      // 标准格式
      playAuth = response.data.playAuth || response.data.PlayAuth
      videoMeta = response.data.videoMeta || response.data
    } else if (response.playAuth || response.PlayAuth) {
      // 直接格式
      playAuth = response.playAuth || response.PlayAuth
      videoMeta = response.videoMeta || response
    } else {
      throw new Error(response.message || '获取播放凭证失败')
    }
    
    console.log('[WorkflowDetail] 解析播放凭证:', { playAuth: !!playAuth, videoMeta })
    
    if (!playAuth) {
      throw new Error('播放凭证为空')
    }
    
    // 调用播放器播放视频
    const videoMetaData = {
      videoId: workflowData.value.vodVideoId,
      title: workflowData.value.name,
      coverURL: workflowData.value.coverUrl,
      duration: videoMeta?.duration
    }
    
    console.log('[WorkflowDetail] 调用播放器播放视频:', videoMetaData)
    await playerRef.value.playVideo(playAuth, videoMetaData)
    
    console.log('[WorkflowDetail] 视频播放启动成功')
    
  } catch (error) {
    console.error('[WorkflowDetail] 视频播放失败:', error)
    ElMessage.error(error.message || '视频播放失败，请稍后重试')
    // 播放失败时隐藏播放器，回到封面状态
    showPlayer.value = false
  }
}

// 视频播放器事件处理
const handleVideoPlay = () => {
  console.log('视频开始播放')
}

const handleVideoPause = () => {
  console.log('视频暂停')
}

const handleVideoEnded = () => {
  console.log('视频播放结束')
}

const handleVideoError = (error) => {
  console.error('视频播放错误:', error)
  ElMessage.error('视频播放失败')
}

const handlePlayerReady = (player) => {
  console.log('播放器准备就绪:', player)
  // 播放器准备就绪后，确保开始播放（双重保险）
  if (player && typeof player.play === 'function') {
    try {
      player.play()
    } catch (error) {
      console.log('自动播放可能被浏览器阻止:', error)
    }
  }
}

// 收藏/取消收藏
const toggleFavorite = async () => {
  // 检查用户是否登录
  if (!isLoggedIn()) {
    showLoginModal.value = true
    return
  }
  
  try {
    const workflowId = workflowData.value.id || parseInt(route.params.id)
    const response = await toggleWorkflowFavorite(workflowId)
    
    if (response.success) {
      isFavorited.value = response.isLiked
      ElMessage.success(response.message || (isFavorited.value ? '已添加到收藏' : '已取消收藏'))
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}

// 下载数据包
const downloadDataFile = async () => {
  // 重新检查权限，确保权限验证准确性
  const currentPermission = checkUserWorkflowPermission()
  
  if (!currentPermission.hasFullAccess) {
    ElMessage.warning('权限不足，无法下载数据包')
    showMembershipDialog.value = true
    return
  }
  
  try {
    downloadingDataFile.value = true
    const workflowId = workflowData.value.id || parseInt(route.params.id)
    const response = await getWorkflowDataFile(workflowId)
    
    if (response.code === 200 && response.data) {
      // 创建下载链接
      const link = document.createElement('a')
      link.href = response.data.dataFileUrl
      link.download = `${response.data.workflowName}-data.${response.data.fileFormat}`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      ElMessage.success('数据包下载已开始')
    } else {
      ElMessage.error(response.message || '获取下载地址失败')
    }
  } catch (error) {
    console.error('下载数据包失败:', error)
    ElMessage.error('下载失败，请重试')
  } finally {
    downloadingDataFile.value = false
  }
}

// 复制JSON数据
const copyJsonData = async () => {
  // 重新检查权限，确保权限验证准确性
  const currentPermission = checkUserWorkflowPermission()
  
  if (!currentPermission.hasCopyAccess) {
    ElMessage.warning('权限不足，无法复制JSON数据')
    showMembershipDialog.value = true
    return
  }
  
  try {
    copyingJsonData.value = true
    const workflowId = workflowData.value.id || parseInt(route.params.id)
    const response = await getWorkflowJsonData(workflowId)
    
    if (response.code === 200 && response.data) {
      // 复制到剪贴板
      await navigator.clipboard.writeText(response.data.jsonData)
      ElMessage.success('JSON数据已复制到剪贴板')
    } else {
      ElMessage.error(response.message || '获取JSON数据失败')
    }
  } catch (error) {
    console.error('复制JSON数据失败:', error)
    ElMessage.error('复制失败，请重试')
  } finally {
    copyingJsonData.value = false
  }
}

// 关闭登录弹窗
const closeLoginModal = () => {
  showLoginModal.value = false
}

// 登录成功回调
const handleLoginSuccess = () => {
  showLoginModal.value = false
  ElMessage.success('登录成功')
  
  // 登录成功后延迟更新权限信息，避免与监听器冲突
  setTimeout(() => {
    if (!isLoadingWorkflowDetail.value && !isLoadingUserInfo.value) {
      console.log('[WorkflowDetail] 登录成功，更新权限信息')
      updateWorkflowPermission()
      
      // 更新收藏状态
      if (!isLoadingFavoriteStatus.value) {
        initializeFavoriteStatus()
      }
    }
  }, 200)
}

// 处理图片加载错误
const handleImageError = (event) => {
  const img = event.target
  if (!img.src.includes('picsum.photos')) {
    img.src = 'https://picsum.photos/980/666'
  }
}

// 权限等级转换辅助函数
const convertPermissionLevel = (level) => {
  if (typeof level === 'string') {
    if (level.includes('SVIP') || level.includes('svip')) return 3
    if (level.includes('VIP') || level.includes('vip')) return 2
    return 1
  }
  return parseInt(level) || 1
}

// 生成权限拒绝原因
const getAccessDeniedReason = (hasFullAccess, hasCopyAccess, fullAccessRoleName, copyAccessRoleName) => {
  if (!hasFullAccess && !hasCopyAccess) {
    return {
      reason: `该工作流需要${copyAccessRoleName}及以上权限才能访问`,
      showInfo: true
    }
  }
  if (!hasFullAccess) {
    return {
      reason: `完整功能需要${fullAccessRoleName}权限，当前仅可部分访问`,
      showInfo: true
    }
  }
  if (!hasCopyAccess && hasFullAccess) {
    return {
      reason: `复制功能需要${copyAccessRoleName}权限`,
      showInfo: false
    }
  }
  return { reason: null, showInfo: false }
}

// 判断是否为赠送会员
const isGiftMember = (userInfo) => {
  if (!userInfo || !userInfo.createTime || !userInfo.membershipExpiresAt) {
    return false
  }
  
  try {
    const createTime = new Date(userInfo.createTime)
    const expiresAt = new Date(userInfo.membershipExpiresAt)
    
    // 计算创建时间 + 2天
    const createTimePlus2Days = new Date(createTime)
    createTimePlus2Days.setDate(createTime.getDate() + 2)
    
    // 判断会员过期时间是否等于创建时间 + 2天（允许一些时间误差，比如1小时内）
    const timeDifference = Math.abs(expiresAt.getTime() - createTimePlus2Days.getTime())
    const oneHourInMs = 60 * 60 * 1000 // 1小时的毫秒数
    
    const isGift = timeDifference <= oneHourInMs
    
    console.log('[WorkflowDetail] 赠送会员检查:', {
      createTime: createTime.toISOString(),
      expiresAt: expiresAt.toISOString(),
      createTimePlus2Days: createTimePlus2Days.toISOString(),
      timeDifference: timeDifference,
      isGift: isGift
    })
    
    return isGift
  } catch (error) {
    console.error('[WorkflowDetail] 赠送会员判断出错:', error)
    return false
  }
}

// 检查用户是否有权限访问工作流
const checkUserWorkflowPermission = () => {
  console.log('[WorkflowDetail] === 开始检查用户工作流权限 ===')
  
  // 检查登录状态
  if (!isLoggedIn()) {
    console.log('[WorkflowDetail] 用户未登录，无权限访问')
    return {
      hasFullAccess: false,
      hasCopyAccess: false,
      hasVideoAccess: false,
      accessDeniedReason: '请先登录后再查看工作流内容',
      showPermissionInfo: true,
      isGiftMember: false
    }
  }
  
  // 获取用户信息
  const userInfo = userStore.getUserInfo
  if (!userInfo) {
    console.log('[WorkflowDetail] 用户信息获取失败')
    return {
      hasFullAccess: false,
      hasCopyAccess: false,
      hasVideoAccess: false,
      accessDeniedReason: '用户信息获取失败，请重新登录',
      showPermissionInfo: true,
      isGiftMember: false
    }
  }
  
  // 判断是否为赠送会员
  const isGift = isGiftMember(userInfo)
  console.log('[WorkflowDetail] 用户是否为赠送会员:', isGift)
  
  // 优先使用API返回的权限信息（如果存在）
  if (userPermission.value && typeof userPermission.value.hasFullAccess !== 'undefined') {
    console.log('[WorkflowDetail] 使用API返回的权限信息')
    
    let hasFullAccess = userPermission.value.hasFullAccess
    let hasCopyAccess = userPermission.value.hasCopyAccess
    
    // 获取工作流权限要求
    const requiredFullAccessLevel = workflowData.value.fullAccessRole || userPermission.value.requiredFullAccessLevel || 1
    const requiredCopyLevel = workflowData.value.copyAccessRole || userPermission.value.requiredCopyLevel || 2
    
    console.log('[WorkflowDetail] 工作流权限要求:', {
      fullAccessRole: workflowData.value.fullAccessRole,
      copyAccessRole: workflowData.value.copyAccessRole,
      requiredFullAccessLevel,
      requiredCopyLevel,
      isGift
    })
    
    // 如果是赠送会员，需要覆盖API返回的权限
    if (isGift) {
      console.log('[WorkflowDetail] 检测到赠送会员（VIP等级），重新评估权限')
      
      // 赠送会员是VIP（role=2），只在VIP工作流中有特殊限制
      // 在SVIP工作流中，按正常权限不足处理
      if (requiredFullAccessLevel === 2) {
        console.log('[WorkflowDetail] VIP工作流，赠送会员禁止下载')
        hasFullAccess = false
      } else if (requiredFullAccessLevel > 2) {
        console.log('[WorkflowDetail] SVIP工作流，赠送会员按正常权限不足处理')
        // 不做特殊处理，保持API返回的权限不足状态
      } else {
        console.log('[WorkflowDetail] 免费工作流，赠送会员可以下载')
      }
      
      if (requiredCopyLevel === 2) {
        console.log('[WorkflowDetail] VIP复制功能，赠送会员禁止复制')
        hasCopyAccess = false
      } else if (requiredCopyLevel > 2) {
        console.log('[WorkflowDetail] SVIP复制功能，赠送会员按正常权限不足处理')
        // 不做特殊处理，保持API返回的权限不足状态
      } else {
        console.log('[WorkflowDetail] 免费复制功能，赠送会员可以复制')
      }
    }
    
    // 生成拒绝原因
    let accessDeniedReason = userPermission.value.accessDeniedReason
    let showPermissionInfo = false
    
    if (isGift && (!hasFullAccess || !hasCopyAccess)) {
      // 只有在VIP等级的工作流中，赠送会员才显示特殊限制提示
      // 在SVIP工作流中，显示正常的权限不足信息
      const isVipWorkflow = (requiredFullAccessLevel === 2 || requiredCopyLevel === 2)
      
      if (isVipWorkflow) {
        const restrictedFeatures = []
        if (!hasFullAccess) restrictedFeatures.push('下载数据包')
        if (!hasCopyAccess) restrictedFeatures.push('复制JSON数据')
        
        if (restrictedFeatures.length > 0) {
          accessDeniedReason = `赠送会员暂不支持${restrictedFeatures.join('和')}功能，请升级为正式会员`
          showPermissionInfo = true
        }
      } else {
        // SVIP工作流，显示正常权限不足信息
        showPermissionInfo = true
        // 保持API返回的accessDeniedReason
      }
    } else if (!hasFullAccess || !hasCopyAccess) {
      showPermissionInfo = true
    }
    
    const result = {
      userRole: userPermission.value.userRole,
      userRoleName: userPermission.value.userRoleName,
      requiredFullAccessLevel,
      requiredFullAccessLevelName: userPermission.value.requiredFullAccessLevelName,
      requiredCopyLevel,
      requiredCopyLevelName: userPermission.value.requiredCopyLevelName,
      hasFullAccess,
      hasCopyAccess,
      hasVideoAccess: true, // 所有已登录用户都可以观看视频
      accessDeniedReason,
      showPermissionInfo,
      isGiftMember: isGift
    }
    
    console.log('[WorkflowDetail] 最终权限结果:', result)
    return result
  }
  
  // 如果没有API权限信息，使用本地计算（保留原有逻辑作为fallback）
  console.log('[WorkflowDetail] API未返回权限信息，使用本地计算')
  
  const userRole = userInfo.role || 1
  const userRoleName = userInfo.roleName || '免费用户'
  
  // 处理权限等级
  let requiredFullAccessLevel = workflowData.value.fullAccessRole || workflowData.value.requiredFullAccessLevel || 1
  let requiredCopyLevel = workflowData.value.copyAccessRole || workflowData.value.requiredCopyLevel || 2
  
  // 确保是数字类型
  if (typeof requiredFullAccessLevel !== 'number') {
    requiredFullAccessLevel = convertPermissionLevel(requiredFullAccessLevel)
  }
  if (typeof requiredCopyLevel !== 'number') {
    requiredCopyLevel = convertPermissionLevel(requiredCopyLevel) || 2
  }
  
  const fullAccessRoleName = workflowData.value.fullAccessRoleName || '免费用户'
  const copyAccessRoleName = workflowData.value.copyAccessRoleName || 'VIP用户'
  
  // 计算权限
  let hasFullAccess = userRole >= requiredFullAccessLevel
  let hasCopyAccess = userRole >= requiredCopyLevel
  
  // 如果是赠送会员，需要根据工作流权限要求判断
  if (isGift) {
    // 赠送会员是VIP（role=2），只在VIP工作流中有特殊限制
    if (requiredFullAccessLevel === 2) {
      hasFullAccess = false
    }
    if (requiredCopyLevel === 2) {
      hasCopyAccess = false
    }
    // SVIP工作流（level=3）保持正常权限不足处理
  }
  
  // 生成拒绝原因
  let accessDeniedReason = null
  let showPermissionInfo = false
  
  if (isGift && (!hasFullAccess || !hasCopyAccess)) {
    // 只有在VIP等级的工作流中，赠送会员才显示特殊限制提示
    const isVipWorkflow = (requiredFullAccessLevel === 2 || requiredCopyLevel === 2)
    
    if (isVipWorkflow) {
      const restrictedFeatures = []
      if (!hasFullAccess) restrictedFeatures.push('下载数据包')
      if (!hasCopyAccess) restrictedFeatures.push('复制JSON数据')
      
      if (restrictedFeatures.length > 0) {
        accessDeniedReason = `赠送会员暂不支持${restrictedFeatures.join('和')}功能，请升级为正式会员`
        showPermissionInfo = true
      }
    } else {
      // SVIP工作流，显示正常权限不足信息
      const { reason, showInfo } = getAccessDeniedReason(hasFullAccess, hasCopyAccess, fullAccessRoleName, copyAccessRoleName)
      accessDeniedReason = reason
      showPermissionInfo = showInfo
    }
  } else if (!isGift) {
    const { reason, showInfo } = getAccessDeniedReason(hasFullAccess, hasCopyAccess, fullAccessRoleName, copyAccessRoleName)
    accessDeniedReason = reason
    showPermissionInfo = showInfo
  }
  
  const result = {
    userRole,
    userRoleName,
    requiredFullAccessLevel,
    requiredFullAccessLevelName: fullAccessRoleName,
    requiredCopyLevel,
    requiredCopyLevelName: copyAccessRoleName,
    hasFullAccess,
    hasCopyAccess,
    hasVideoAccess: true, // 所有已登录用户都可以观看视频
    accessDeniedReason,
    showPermissionInfo,
    isGiftMember: isGift
  }
  
  console.log('[WorkflowDetail] 权限检查结果:', result)
  return result
}

// 检查并设置权限准备状态
const checkAndSetPermissionReady = () => {
  console.log('[WorkflowDetail] 检查权限准备状态')
  
  // 检查工作流数据是否已加载
  if (!workflowData.value.id) {
    console.log('[WorkflowDetail] 工作流数据未加载，权限未准备好')
    return
  }
  
  // 如果用户已登录，需要确保用户信息已准备好
  if (isLoggedIn()) {
    const userInfo = userStore.getUserInfo
    if (!userInfo || !userInfo.createTime) {
      console.log('[WorkflowDetail] 用户已登录但信息未完全准备好，权限未准备好')
      return
    }
    
    console.log('[WorkflowDetail] 用户信息已准备好')
    isUserInfoReady.value = true
  } else {
    console.log('[WorkflowDetail] 用户未登录，跳过用户信息检查')
    isUserInfoReady.value = true
  }
  
  // 所有必要信息都准备好了，可以设置权限准备完成
  if (!isPermissionReady.value) {
    console.log('[WorkflowDetail] 所有必要信息已准备好，标记权限计算完成')
    isPermissionReady.value = true
  }
}

// 更新工作流权限信息
const updateWorkflowPermission = () => {
  console.log('[WorkflowDetail] === 开始更新工作流权限信息 ===')
  
  if (!workflowData.value.id) {
    console.log('[WorkflowDetail] 工作流数据未加载，跳过权限更新')
    return
  }
  
  const permission = checkUserWorkflowPermission()
  console.log('[WorkflowDetail] 权限检查结果:', permission)
  
  // 更新权限状态
  userPermission.value = {
    ...userPermission.value,
    ...permission
  }
  
  console.log('[WorkflowDetail] 更新后的工作流权限信息:', userPermission.value)
  
  // 检查是否所有必要信息都准备好了
  checkAndSetPermissionReady()
  
  // 只有在用户完全无权限访问时才自动弹窗
  // 如果用户有部分权限（比如有完整访问权限但没有复制权限），则不自动弹窗
  if (!permission.hasFullAccess && !permission.hasCopyAccess) {
    console.log('[WorkflowDetail] 用户完全无权限，自动显示会员开通弹窗')
    // 延迟一点时间显示弹窗，确保页面已经渲染完成
    setTimeout(() => {
      showMembershipDialog.value = true
    }, 500)
  } else if (!permission.hasFullAccess || !permission.hasCopyAccess) {
    console.log('[WorkflowDetail] 用户部分权限不足，显示权限信息但不自动弹窗')
  } else {
    console.log('[WorkflowDetail] 用户权限足够，不显示弹窗')
  }
}

// 处理工作流重新获取
const handleWorkflowRefresh = async (isUserLogin = false) => {
  if (!workflowData.value.id) return
  
  console.log('[WorkflowDetail] 处理工作流刷新，登录状态:', isUserLogin)
  
  if (isUserLogin) {
    // 用户登录时，只更新用户信息和收藏状态，不重新获取工作流详情
    console.log('[WorkflowDetail] 用户已登录，仅更新用户信息和收藏状态')
    
    // 使用 Promise.all 并行执行，但避免重复请求
    const promises = []
    
    if (!isLoadingUserInfo.value) {
      promises.push(updateUserInfo())
    }
    
    if (!isLoadingFavoriteStatus.value) {
      promises.push(initializeFavoriteStatus())
    }
    
    if (promises.length > 0) {
      await Promise.all(promises)
    }
  } else {
    // 用户未登录时，仅更新权限信息
    console.log('[WorkflowDetail] 用户未登录，更新权限信息')
    updateWorkflowPermission()
  }
}

// 监听用户状态变化，动态更新权限
const watchUserStatus = () => {
  // 防抖机制，避免监听器同时触发
  let statusUpdateTimer = null
  
  const debouncedUpdate = (action, delay = 200) => {
    if (statusUpdateTimer) {
      clearTimeout(statusUpdateTimer)
    }
    statusUpdateTimer = setTimeout(action, delay)
  }
  
  // 监听登录状态变化（优先级最高）
  watch(() => userStore.getIsLoggedIn, (isLoggedIn, oldIsLoggedIn) => {
    if (isLoggedIn !== oldIsLoggedIn && workflowData.value.id) {
      console.log('[WorkflowDetail] 登录状态变化:', oldIsLoggedIn, '→', isLoggedIn)
      
      // 清理其他定时器，优先处理登录状态变化
      if (statusUpdateTimer) {
        clearTimeout(statusUpdateTimer)
      }
      
      debouncedUpdate(() => {
        handleWorkflowRefresh(isLoggedIn)
        
        // 更新收藏状态
        if (!isLoggedIn) {
          isFavorited.value = false
        } else {
          // 登录时重新获取收藏状态
          initializeFavoriteStatus()
        }
      }, 100)
    }
  })
  
  // 监听用户角色变化（仅在已登录时）
  watch(() => userStore.getUserInfo?.role, (newRole, oldRole) => {
    if (newRole !== oldRole && workflowData.value.id && userStore.getIsLoggedIn) {
      console.log('[WorkflowDetail] 用户角色变化，从', oldRole, '变为', newRole)
      
      debouncedUpdate(() => {
        // 只更新权限，不重新获取全部数据
        updateWorkflowPermission()
      }, 150)
    }
  })
}

// 初始化收藏状态
const initializeFavoriteStatus = async () => {
  // 如果用户未登录，则收藏状态为false
  if (!isLoggedIn()) {
    isFavorited.value = false
    return
  }
  
  // 防止重复请求
  if (isLoadingFavoriteStatus.value) {
    console.log('[WorkflowDetail] 收藏状态正在加载中，跳过重复请求')
    return
  }
  
  try {
    isLoadingFavoriteStatus.value = true
    const workflowId = parseInt(route.params.id)
    console.log('[WorkflowDetail] 开始检查收藏状态，工作流ID:', workflowId)
    const response = await checkWorkflowLikeStatus(workflowId)
    
    if (response.success) {
      isFavorited.value = response.isLiked || false
      console.log('[WorkflowDetail] 收藏状态初始化:', isFavorited.value)
    } else {
      isFavorited.value = false
      console.log('[WorkflowDetail] 获取收藏状态失败，默认为未收藏')
    }
  } catch (error) {
    console.error('[WorkflowDetail] 获取收藏状态失败:', error)
    isFavorited.value = false
  } finally {
    isLoadingFavoriteStatus.value = false
  }
}

// 处理工作流数据初始化
const initializeWorkflowData = async (workflowData, userPermission, forceResetGallery = false) => {
  // 解析详情图集数据
  const newDetailGallery = parseDetailGallery(workflowData.detailGallery)
  
  // 检查图集是否发生变化
  const galleryChanged = JSON.stringify(detailGallery.value) !== JSON.stringify(newDetailGallery)
  
  if (galleryChanged || forceResetGallery) {
    console.log('[WorkflowDetail] 图集数据变化，重新初始化')
    detailGallery.value = newDetailGallery
    
    // 重置图集加载状态
    if (detailGallery.value.length > 0) {
      galleryLoading.value = true
      loadedImageCount.value = 0
      successImageCount.value = 0
      console.log(`[WorkflowDetail] 开始加载${detailGallery.value.length}张图片`)
      
      // 等待DOM更新后检查已缓存的图片
      await nextTick()
      checkCachedImages()
    } else {
      galleryLoading.value = false
      loadedImageCount.value = 0
      successImageCount.value = 0
      console.log('[WorkflowDetail] 没有图集数据')
    }
  } else {
    console.log('[WorkflowDetail] 图集数据未变化，保持当前状态')
  }
  
  console.log('[WorkflowDetail] 工作流数据加载成功:', workflowData)
  console.log('[WorkflowDetail] 权限信息:', userPermission)
  console.log('[WorkflowDetail] 详情图集:', detailGallery.value)
  
  // 初始化收藏状态
  await initializeFavoriteStatus()
}

// 检查权限弹窗显示
const checkPermissionDialog = (userPermission) => {
  if (!userPermission.hasFullAccess && !userPermission.hasCopyAccess) {
    console.log('[WorkflowDetail] 用户完全无权限，自动显示会员开通弹窗')
    setTimeout(() => {
      showMembershipDialog.value = true
    }, 500)
  } else {
    console.log('[WorkflowDetail] 用户权限足够或有部分权限，不自动弹窗')
  }
}

// 获取工作流详情数据
const fetchWorkflowDetail = async () => {
  // 防止重复请求
  if (isLoadingWorkflowDetail.value) {
    console.log('[WorkflowDetail] 工作流详情正在加载中，跳过重复请求')
    return
  }
  
  try {
    isLoadingWorkflowDetail.value = true
    
    // 验证当前路由是否是工作流详情页，防止 bfcache 导致的错误调用
    if (route.name !== 'WorkflowDetail') {
      console.warn('[WorkflowDetail] 路由不匹配，当前路由:', route.name, '跳过请求')
      return
    }
    
    const workflowId = route.params.id
    if (!workflowId) {
      console.error('[WorkflowDetail] 工作流ID不存在')
      return
    }
    
    // 验证 workflowId 格式：工作流ID应该是纯数字，不是 WORK-xxx 格式
    if (typeof workflowId === 'string' && workflowId.startsWith('WORK-')) {
      console.error('[WorkflowDetail] 错误：收到作品ID而非工作流ID，跳过请求', workflowId)
      return
    }

    // 验证当前路由是否正确
    const currentPath = route.path
    console.log('[WorkflowDetail] 获取工作流详情:', {
      workflowId,
      currentPath,
      expectedPath: `/workflow/${workflowId}`,
      routeName: route.name
    })
    
    // 如果路由名称不匹配，可能是路由错误
    if (route.name !== 'WorkflowDetail') {
      console.warn('[WorkflowDetail] 警告：路由名称不匹配!', route.name)
    }

    console.log('[WorkflowDetail] 开始获取工作流详情，ID:', workflowId)
    const response = await getWorkflowDetail(workflowId)
    
    if (response.code === 200 && response.data) {
      workflowData.value = response.data.workflow
      userPermission.value = response.data.userPermission
      
      // 如果API返回了权限信息，但不要立即标记完成，需要等待用户信息验证
      if (response.data.userPermission) {
        console.log('[WorkflowDetail] API返回权限信息，等待用户信息验证后再标记完成')
        // 不要在这里设置 isPermissionReady，等待完整的权限验证
      }
      
      await initializeWorkflowData(response.data.workflow, response.data.userPermission, isInitialLoad.value)
      
      // 工作流数据加载完成后，立即检查权限准备状态
      updateWorkflowPermission()
      checkAndSetPermissionReady()
      
      // 检查权限弹窗
      if (workflowData.value.id && userPermission.value) {
        console.log('[WorkflowDetail] 数据加载完成，使用API返回的权限信息')
        checkPermissionDialog(userPermission.value)
      }
    } else {
      ElMessage.error(response.message || '获取工作流详情失败')
    }
    
  } catch (error) {
    console.error('获取工作流详情失败:', error)
    ElMessage.error('获取工作流详情失败，请稍后重试')
  } finally {
    isLoadingWorkflowDetail.value = false
  }
}

// 组件挂载时获取数据
onMounted(async () => {
  console.log('[WorkflowDetail] 组件挂载开始')
  
  // 先获取工作流详情
  await fetchWorkflowDetail()
  
  // 如果用户已经登录，并行更新用户信息和收藏状态
  if (isLoggedIn()) {
    console.log('[WorkflowDetail] 页面加载时用户已登录，并行更新用户信息和收藏状态')
    
    // 检查用户信息是否已经准备好
    const userInfo = userStore.getUserInfo
    if (userInfo && userInfo.createTime) {
      console.log('[WorkflowDetail] 用户信息已存在，立即检查权限')
      isUserInfoReady.value = true
      checkAndSetPermissionReady()
    } else {
      console.log('[WorkflowDetail] 用户信息不完整，需要重新获取')
      // 并行执行，提高性能
      const promises = []
      
      if (!isLoadingUserInfo.value) {
        promises.push(updateUserInfo())
      }
      
      // 收藏状态会在 initializeWorkflowData 中调用，这里避免重复调用
      
      if (promises.length > 0) {
        await Promise.all(promises)
      }
    }
  } else {
    console.log('[WorkflowDetail] 用户未登录，立即检查权限')
    isUserInfoReady.value = true
    checkAndSetPermissionReady()
  }
  
  // 标记首次加载完成
  isInitialLoad.value = false
  
  // 监听用户状态变化
  watchUserStatus()
  
  // 监听路由参数变化
  watch(() => route.params.id, (newId, oldId) => {
    if (newId !== oldId) {
      console.log('[WorkflowDetail] 路由参数变化，重新加载工作流详情')
      
      // 重置状态
      isInitialLoad.value = true
      isLoadingWorkflowDetail.value = false
      isLoadingUserInfo.value = false
      isLoadingFavoriteStatus.value = false
      isPermissionReady.value = false
      isUserInfoReady.value = false
      
      // 清理定时器
      if (updatePermissionTimer) {
        clearTimeout(updatePermissionTimer)
        updatePermissionTimer = null
      }
      
      fetchWorkflowDetail()
    }
  })
  
  // 添加键盘事件监听
  document.addEventListener('keydown', handleKeyDown)
  
  console.log('[WorkflowDetail] 组件挂载完成')
})

// 清理函数
const cleanup = () => {
  console.log('[WorkflowDetail] 清理工作流详情页面资源')
  
  // 清理所有定时器
  if (updatePermissionTimer) {
    clearTimeout(updatePermissionTimer)
    updatePermissionTimer = null
  }
  
  // 重置请求状态
  isLoadingWorkflowDetail.value = false
  isLoadingUserInfo.value = false
  isLoadingFavoriteStatus.value = false
  isPermissionReady.value = false
  isUserInfoReady.value = false
  
  console.log('[WorkflowDetail] 资源清理完成')
}

// 页面卸载时清理资源
onUnmounted(() => {
  // 移除键盘事件监听
  document.removeEventListener('keydown', handleKeyDown)
  
  cleanup()
})


</script>

<style scoped>
.workflow-detail {
  font-family: 'Microsoft YaHei', Arial, sans-serif;
  margin: 0;
  padding: 0;
  width: 100%;
  min-height: 100vh;
  background-color: #1a1a1a;
  padding-top: 60px;
  text-align: left;
}

.workflow-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.breadcrumb-container {
  background-color: #2a2a2a;
  border-bottom: 1px solid #404040;
}

.breadcrumb {
  display: flex;
  align-items: center;
  padding: 12px 0;
  font-size: 14px;
  color: #ccc;
  text-align: left;
}

.back-link {
  color: #60a5fa;
  cursor: pointer;
  transition: color 0.2s;
  text-align: left;
}

.back-link:hover {
  color: #93c5fd;
}

.separator {
  margin: 0 8px;
}

.current-page {
  color: #e5e5e5;
  font-weight: 500;
  text-align: left;
}

/* 视频模块 */
.video-module {
  background: linear-gradient(135deg, #1e293b 0%, #334155 100%);
  width: 100%;
  padding: 0;
  margin: 0;
}

.video-inner {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;
}

.video-section {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.video-container {
  display: flex;
  gap: 30px;
  width: 100%;
}

.video-player {
  flex: 2;
  aspect-ratio: 16/9;
  border-radius: 12px;
  overflow: hidden;
  position: relative;
  background: #000;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}

.workflow-cover-display {
  width: 100%;
  height: 100%;
  position: relative;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.workflow-cover-display:hover {
  transform: scale(1.02);
}

.workflow-main-cover {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.cover-overlay-content {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(to bottom, rgba(0,0,0,0.3) 0%, rgba(0,0,0,0.7) 100%);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  color: white;
  padding: 20px;
}

.play-icon, .workflow-icon {
  font-size: 64px;
  margin-bottom: 20px;
  opacity: 0.9;
}

.workflow-title {
  font-size: 24px;
  font-weight: bold;
  margin: 0 0 10px 0;
  text-shadow: 0 2px 4px rgba(0,0,0,0.5);
  text-align: left;
}

.workflow-subtitle {
  font-size: 16px;
  margin: 0;
  opacity: 0.8;
  text-align: left;
}

/* 工作流信息面板 */
.workflow-info-panel {
  flex: 1;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 24px;
  color: white;
  min-height: 400px;
}

.creator-info-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.creator-info-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.creator-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  overflow: hidden;
}

.creator-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.creator-info-text {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.creator-name, .workflow-category {
  font-size: 14px;
  opacity: 0.9;
  text-align: left;
}

.creator-name {
  font-weight: 500;
  text-align: left;
}

.favorite-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 20px;
  color: white;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
}

.favorite-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.favorite-btn.favorited {
  background: #fbbf24;
  border-color: #fbbf24;
  color: #1f2937;
}

/* 统计信息 */
.workflow-stats {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.stat-item {
  display: flex;
  align-items: center;
  font-size: 14px;
  text-align: left;
}

.stat-label {
  color: rgba(255, 255, 255, 0.7);
  min-width: 80px;
  text-align: left;
}

.stat-value {
  color: #3b82f6;
  font-weight: 500;
  text-align: left;
}

.rating {
  display: flex;
  align-items: center;
  gap: 4px;
}

.star {
  font-size: 16px;
  opacity: 0.3;
}

.star.active {
  opacity: 1;
}

.rating-text {
  margin-left: 8px;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
}

/* 权限和操作 */
.workflow-actions {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.permission-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.permission-item {
  display: flex;
  align-items: center;
  font-size: 12px;
  text-align: left;
}

.permission-label {
  color: rgba(255, 255, 255, 0.6);
  min-width: 100px;
  text-align: left;
}

.permission-value {
  color: #10b981;
  font-weight: 500;
  text-align: left;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 10px 16px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
}

.download-btn {
  background: #3b82f6;
  color: white;
}

.download-btn:hover:not(:disabled) {
  background: #2563eb;
}

.copy-btn {
  background: #10b981;
  color: white;
}

.copy-btn:hover:not(:disabled) {
  background: #059669;
}

.action-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.permission-notice {
  padding: 16px;
  background: rgba(239, 68, 68, 0.1);
  border: 1px solid rgba(239, 68, 68, 0.2);
  border-radius: 8px;
  font-size: 12px;
  color: #fca5a5;
  text-align: left;
}

.permission-notice p {
  margin: 0 0 8px 0;
  text-align: left;
}

  .permission-notice p:last-of-type {
    margin-bottom: 12px;
    text-align: left;
  }
  
  .permission-notice .access-reason {
    color: #fbbf24;
    font-weight: 500;
    text-align: left;
  }
  
  .upgrade-btn {
  background: #f59e0b;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 12px;
  cursor: pointer;
  transition: background 0.2s;
}

.upgrade-btn:hover {
  background: #d97706;
}

/* 赠送会员样式 */
.gift-member-notice {
  text-align: center;
  padding: 8px 0;
}

.gift-member-icon {
  font-size: 32px;
  margin-bottom: 8px;
}

.gift-member-title {
  font-size: 14px;
  font-weight: 600;
  color: #fbbf24;
  margin: 0 0 8px 0;
  text-align: center;
}

.gift-member-desc {
  font-size: 12px;
  color: #fca5a5;
  margin: 0;
  line-height: 1.4;
  text-align: center;
}

/* 会员弹窗中的赠送会员样式 */
.gift-member-dialog-content {
  text-align: center;
  margin-bottom: 16px;
}

.gift-member-badge {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  background: linear-gradient(135deg, #fbbf24, #f59e0b);
  border-radius: 20px;
  padding: 8px 16px;
  margin: 0 auto 16px auto;
  width: fit-content;
  color: #1f2937;
  font-weight: 600;
  font-size: 14px;
}

.gift-icon {
  font-size: 16px;
}

.gift-text {
  font-size: 14px;
}

.upgrade-message {
  font-size: 14px;
  color: #e5e5e5;
  margin: 8px 0 16px 0;
  font-weight: 500;
  text-align: center;
}

/* 下方深色模块 */
.below-module {
  background: #2a2a2a;
  padding: 40px 0;
}

.workflow-description {
  margin-bottom: 40px;
}

.workflow-description h3 {
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 16px 0;
  color: #e5e5e5;
  text-align: left;
}

.workflow-description p {
  font-size: 14px;
  line-height: 1.6;
  color: #cccccc;
  margin: 0;
  text-align: left;
}

/* 富文本内容样式 */
.rich-text-content {
  font-size: 14px;
  line-height: 1.6;
  color: #cccccc;
  text-align: left;
}

.rich-text-content h1,
.rich-text-content h2,
.rich-text-content h3,
.rich-text-content h4,
.rich-text-content h5,
.rich-text-content h6 {
  color: #e5e5e5;
  margin: 16px 0 8px 0;
  font-weight: 600;
}

.rich-text-content h1 { font-size: 24px; }
.rich-text-content h2 { font-size: 20px; }
.rich-text-content h3 { font-size: 18px; }
.rich-text-content h4 { font-size: 16px; }
.rich-text-content h5 { font-size: 14px; }
.rich-text-content h6 { font-size: 12px; }

.rich-text-content p {
  margin: 8px 0;
  color: #cccccc;
}

.rich-text-content ul,
.rich-text-content ol {
  margin: 8px 0;
  padding-left: 20px;
  color: #cccccc;
}

.rich-text-content li {
  margin: 4px 0;
}

.rich-text-content blockquote {
  margin: 16px 0;
  padding: 12px 16px;
  border-left: 4px solid #409eff;
  background: rgba(64, 158, 255, 0.1);
  color: #cccccc;
  border-radius: 0 4px 4px 0;
}

.rich-text-content code {
  background: rgba(255, 255, 255, 0.1);
  color: #e6a23c;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: 'Courier New', Courier, monospace;
  font-size: 13px;
}

.rich-text-content pre {
  background: rgba(0, 0, 0, 0.3);
  color: #e5e5e5;
  padding: 12px;
  border-radius: 6px;
  overflow-x: auto;
  margin: 12px 0;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.rich-text-content pre code {
  background: none;
  color: inherit;
  padding: 0;
}

.rich-text-content .rich-text-image {
  max-width: 100%;
  max-height: 600px;
  height: auto;
  border-radius: 8px;
  margin: 12px 0;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  display: block;
  object-fit: contain;
}

/* 支持用户设置的对齐方式 */
.rich-text-content p[style*="text-align: center"] .rich-text-image,
.rich-text-content div[style*="text-align: center"] .rich-text-image,
.rich-text-content .rich-text-image[style*="text-align: center"] {
  margin-left: auto;
  margin-right: auto;
}

.rich-text-content p[style*="text-align: left"] .rich-text-image,
.rich-text-content div[style*="text-align: left"] .rich-text-image,
.rich-text-content .rich-text-image[style*="text-align: left"] {
  margin-left: 0;
  margin-right: auto;
}

.rich-text-content p[style*="text-align: right"] .rich-text-image,
.rich-text-content div[style*="text-align: right"] .rich-text-image,
.rich-text-content .rich-text-image[style*="text-align: right"] {
  margin-left: auto;
  margin-right: 0;
}

/* 支持富文本编辑器的对齐类 */
.rich-text-content .ql-align-center .rich-text-image,
.rich-text-content .rich-text-image.ql-align-center {
  margin-left: auto;
  margin-right: auto;
}

.rich-text-content .ql-align-left .rich-text-image,
.rich-text-content .rich-text-image.ql-align-left {
  margin-left: 0;
  margin-right: auto;
}

.rich-text-content .ql-align-right .rich-text-image,
.rich-text-content .rich-text-image.ql-align-right {
  margin-left: auto;
  margin-right: 0;
}

/* 支持标准HTML对齐类 */
.rich-text-content .text-center .rich-text-image,
.rich-text-content .rich-text-image.text-center {
  margin-left: auto;
  margin-right: auto;
}

.rich-text-content .text-left .rich-text-image,
.rich-text-content .rich-text-image.text-left {
  margin-left: 0;
  margin-right: auto;
}

.rich-text-content .text-right .rich-text-image,
.rich-text-content .rich-text-image.text-right {
  margin-left: auto;
  margin-right: 0;
}

/* 支持内联样式的对齐 */
.rich-text-content .rich-text-image[style*="float: left"] {
  float: left;
  margin-right: 16px;
  margin-left: 0;
}

.rich-text-content .rich-text-image[style*="float: right"] {
  float: right;
  margin-left: 16px;
  margin-right: 0;
}

.rich-text-content .rich-text-image[style*="display: block"][style*="margin-left: auto"][style*="margin-right: auto"] {
  margin-left: auto;
  margin-right: auto;
}

/* 图片容器对齐 */
.rich-text-content p,
.rich-text-content div {
  overflow-wrap: break-word;
  word-wrap: break-word;
}

.rich-text-content p[style*="text-align: center"],
.rich-text-content div[style*="text-align: center"] {
  text-align: center;
}

.rich-text-content p[style*="text-align: left"],
.rich-text-content div[style*="text-align: left"] {
  text-align: left;
}

.rich-text-content p[style*="text-align: right"],
.rich-text-content div[style*="text-align: right"] {
  text-align: right;
}

/* 支持Quill编辑器的对齐类 */
.rich-text-content .ql-align-center {
  text-align: center;
}

.rich-text-content .ql-align-left {
  text-align: left;
}

.rich-text-content .ql-align-right {
  text-align: right;
}

.rich-text-content .ql-align-justify {
  text-align: justify;
}

.rich-text-content .rich-text-table {
  width: 100%;
  border-collapse: collapse;
  margin: 16px 0;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 6px;
  overflow: hidden;
}

.rich-text-content .rich-text-table th,
.rich-text-content .rich-text-table td {
  padding: 8px 12px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  text-align: left;
}

.rich-text-content .rich-text-table th {
  background: rgba(255, 255, 255, 0.1);
  color: #e5e5e5;
  font-weight: 600;
}

.rich-text-content .rich-text-table td {
  color: #cccccc;
}

.rich-text-content a {
  color: #409eff;
  text-decoration: none;
  transition: color 0.2s;
}

.rich-text-content a:hover {
  color: #66b1ff;
  text-decoration: underline;
}

.rich-text-content strong {
  color: #e5e5e5;
  font-weight: 600;
}

.rich-text-content em {
  color: #f0f0f0;
  font-style: italic;
}

/* 图片尺寸控制 */
.rich-text-content .rich-text-image[style*="width"] {
  max-width: 100% !important;
}

.rich-text-content .rich-text-image[width] {
  max-width: 100% !important;
  width: auto !important;
}

/* 防止图片超出容器 */
.rich-text-content {
  overflow-x: auto;
  word-wrap: break-word;
}

.rich-text-content img:not(.rich-text-image) {
  max-width: 100%;
  max-height: 600px;
  height: auto;
  object-fit: contain;
}

/* 清除浮动影响 */
.rich-text-content::after {
  content: "";
  display: table;
  clear: both;
}

/* 移动端富文本适配 */
@media (max-width: 768px) {
  .rich-text-content {
    font-size: 13px;
  }
  
  .rich-text-content h1 { font-size: 20px; }
  .rich-text-content h2 { font-size: 18px; }
  .rich-text-content h3 { font-size: 16px; }
  .rich-text-content h4 { font-size: 14px; }
  .rich-text-content h5 { font-size: 13px; }
  .rich-text-content h6 { font-size: 12px; }
  
  .rich-text-content .rich-text-table {
    font-size: 12px;
  }
  
  .rich-text-content .rich-text-table th,
  .rich-text-content .rich-text-table td {
    padding: 6px 8px;
  }
  
  /* 移动端图片优化 */
  .rich-text-content .rich-text-image {
    margin: 8px 0;
    border-radius: 6px;
    max-height: 400px;
  }
  
  /* 移动端取消浮动 */
  .rich-text-content .rich-text-image[style*="float"] {
    float: none !important;
    margin: 8px auto !important;
    display: block !important;
  }
}

/* 会员弹窗 */
.membership-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.membership-dialog {
  background: #333333;
  border-radius: 12px;
  width: 90%;
  max-width: 480px;
  max-height: 90vh;
  overflow-y: auto;
  border: 1px solid #555555;
}

.dialog-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24px 24px 0 24px;
}

.dialog-icon {
  display: flex;
  align-items: center;
}

.dialog-header h3 {
  font-size: 20px;
  font-weight: 600;
  margin: 0;
  color: #e5e5e5;
  text-align: left;
}

.dialog-close {
  background: none;
  border: none;
  padding: 8px;
  cursor: pointer;
  color: #cccccc;
  border-radius: 4px;
  transition: background 0.2s;
}

.dialog-close:hover {
  background: #444444;
}

.dialog-content {
  padding: 24px;
}

.dialog-message {
  font-size: 16px;
  line-height: 1.5;
  color: #cccccc;
  margin: 0 0 24px 0;
  text-align: left;
}

.membership-benefits {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.benefit-item {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 14px;
  color: #cccccc;
  text-align: left;
}

.dialog-actions {
  display: flex;
  gap: 12px;
  padding: 0 24px 24px 24px;
}

.dialog-btn {
  flex: 1;
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  text-align: center;
}

.dialog-btn.secondary {
  background: #555555;
  color: #cccccc;
}

.dialog-btn.secondary:hover {
  background: #666666;
}

.dialog-btn.primary {
  background: #3b82f6;
  color: white;
}

.dialog-btn.primary:hover {
  background: #2563eb;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .breadcrumb-container .workflow-container {
    padding: 0 15px;
  }
  
  .video-container {
    flex-direction: column;
    gap: 20px;
  }
  
  .video-player {
    width: 100%;
    box-sizing: border-box;
  }
  
  .workflow-info-panel {
    width: 100%;
    min-height: auto;
    padding: 16px;
    margin: 0;
    flex: none;
    box-sizing: border-box;
  }
  
  /* 创建者信息区域移动端适配 */
  .creator-info-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
    margin-bottom: 16px;
    padding-bottom: 12px;
  }
  
  .creator-info-left {
    width: 100%;
  }
  
  .creator-info-right {
    width: 100%;
    display: flex;
    justify-content: flex-start;
  }
  
  .favorite-btn {
    padding: 10px 16px;
    font-size: 14px;
  }
  
  /* 统计信息移动端适配 */
  .workflow-stats {
    gap: 10px;
    margin-bottom: 20px;
    padding-bottom: 16px;
  }
  
  .stat-item {
    font-size: 13px;
  }
  
  .stat-label {
    min-width: 60px;
  }
  
  /* 权限信息移动端适配 */
  .permission-item {
    font-size: 11px;
    flex-wrap: wrap;
    flex-direction: column;
    align-items: flex-start;
  }
  
  .permission-label {
    min-width: auto;
    margin-bottom: 2px;
  }
  
  /* 操作按钮移动端适配 */
  .action-buttons {
    gap: 10px;
  }
  
  .action-btn {
    padding: 12px 16px;
    font-size: 13px;
    min-height: 44px;
    word-break: break-word;
  }
  
  .permission-notice {
    padding: 12px;
    font-size: 11px;
  }
  
  .upgrade-btn {
    padding: 10px 16px;
    font-size: 12px;
    min-height: 40px;
  }
  
  .video-inner {
    padding: 20px 15px;
  }
  
  .workflow-container {
    padding: 0 15px;
  }
  
  .below-module .workflow-container {
    padding: 0 15px;
  }
}

/* 更小屏幕设备适配 */
@media (max-width: 480px) {
  .breadcrumb-container .workflow-container {
    padding: 0 10px;
  }
  
  .video-player {
    width: 100%;
    box-sizing: border-box;
  }
  
  .workflow-info-panel {
    width: 100%;
    padding: 12px;
    margin: 0;
    flex: none;
    box-sizing: border-box;
  }
  
  .creator-avatar {
    width: 40px;
    height: 40px;
  }
  
  .creator-info-text {
    gap: 2px;
  }
  
  .creator-name, .workflow-category {
    font-size: 13px;
  }
  
  .favorite-btn {
    padding: 8px 12px;
    font-size: 13px;
  }
  
  .stat-item {
    font-size: 12px;
  }
  
  .stat-label {
    min-width: 50px;
  }
  
  .permission-item {
    font-size: 10px;
    flex-direction: column;
    align-items: flex-start;
  }
  
  .permission-label {
    min-width: auto;
  }
  
  .action-btn {
    padding: 10px 14px;
    font-size: 12px;
    word-break: break-word;
  }
  
  .video-inner {
    padding: 15px 10px;
  }
  
  .workflow-container {
    padding: 0 10px;
  }
  
  .below-module .workflow-container {
    padding: 0 10px;
  }
}

/* 详情图集样式 */
.detail-gallery-section {
  margin-top: 32px;
}

.gallery-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;
  margin-top: 20px;
}

.gallery-item {
  position: relative;
  aspect-ratio: 16/9;
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  border: 1px solid #555;
  transition: all 0.3s ease;
  background: #333;
}

.gallery-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
  border-color: #666;
}

.gallery-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
  object-position: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.gallery-image.image-loaded {
  opacity: 1;
}

.gallery-overlay {
  position: absolute;
  inset: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.gallery-item:hover .gallery-overlay.overlay-visible {
  opacity: 1;
}

.gallery-zoom-icon {
  color: #fff;
  background: rgba(0, 0, 0, 0.7);
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid rgba(255, 255, 255, 0.8);
  transition: all 0.2s ease;
  backdrop-filter: blur(8px);
}

.gallery-zoom-icon .el-icon {
  color: #fff;
}

.gallery-item:hover .gallery-zoom-icon {
  transform: scale(1.1);
  background: rgba(0, 0, 0, 0.8);
}

/* 图片骨架屏样式 */
.skeleton-image-placeholder {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 2;
  border-radius: 12px;
  overflow: hidden;
}

.skeleton-image {
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, #444 25%, #555 50%, #444 75%);
  background-size: 200% 100%;
  animation: skeletonLoading 1.5s infinite;
  border-radius: 12px;
}

@keyframes skeletonLoading {
  0% {
    background-position: -200% 0;
  }
  100% {
    background-position: 200% 0;
  }
}

/* 图片查看器样式 */
.image-viewer-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.95);
  backdrop-filter: blur(8px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10000;
  padding: 20px;
  animation: fadeIn 0.3s ease-out;
  cursor: pointer;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.image-viewer {
  position: relative;
  max-width: 95vw;
  max-height: 95vh;
  background: #333;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.5);
  animation: slideIn 0.3s ease-out;
  cursor: default;
}

@keyframes slideIn {
  from { transform: scale(0.9) translateY(-20px); opacity: 0; }
  to { transform: scale(1) translateY(0); opacity: 1; }
}

.image-viewer-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background: rgba(0, 0, 0, 0.05);
  border-bottom: 1px solid #555;
}

.image-counter {
  font-size: 14px;
  color: #ccc;
  font-weight: 500;
}

.image-viewer-close {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: #ccc;
  cursor: pointer;
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  transition: all 0.2s ease;
}

.image-viewer-close .el-icon {
  color: #ccc;
}

.image-viewer-close:hover .el-icon {
  color: #fff;
}

.image-viewer-close:hover {
  background: rgba(255, 255, 255, 0.2);
  color: #fff;
}

.image-viewer-content {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #222;
}

.viewer-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
  display: block;
}

.image-nav-btn {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background: rgba(255, 255, 255, 0.9);
  color: #333;
  border: 1px solid rgba(0, 0, 0, 0.1);
  width: 52px;
  height: 52px;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  z-index: 10;
  backdrop-filter: blur(8px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.image-nav-btn .el-icon {
  color: #333;
}

.image-nav-btn:hover .el-icon {
  color: #000;
}

.image-nav-btn:hover {
  background: #fff;
  color: #000;
  transform: translateY(-50%) scale(1.1);
  box-shadow: 0 6px 30px rgba(0, 0, 0, 0.25);
}

.prev-btn {
  left: 20px;
}

.next-btn {
  right: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .detail-gallery-section {
    margin-top: 24px;
  }
  
  .gallery-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .gallery-item {
    border-radius: 8px;
  }
  
  .gallery-zoom-icon {
    width: 40px;
    height: 40px;
  }
  
  .image-viewer {
    max-width: 95vw;
    max-height: 95vh;
    border-radius: 8px;
  }
  
  .image-viewer-header {
    padding: 12px 16px;
  }
  
  .image-counter {
    font-size: 12px;
  }
  
  .image-viewer-close {
    font-size: 20px;
    width: 28px;
    height: 28px;
  }
  
  .viewer-image {
    max-height: 60vh;
  }
  
  .image-nav-btn {
    width: 40px;
    height: 40px;
  }
  
  .prev-btn {
    left: 12px;
  }
  
  .next-btn {
    right: 12px;
  }
}

@media (max-width: 480px) {
  .gallery-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }
  
  .gallery-zoom-icon {
    width: 36px;
    height: 36px;
  }
  
  .image-viewer-header {
    padding: 10px 12px;
  }
  
  .image-nav-btn {
    width: 36px;
    height: 36px;
  }
  
  .prev-btn {
    left: 8px;
  }
  
  .next-btn {
    right: 8px;
  }
}
</style>