<template>
  <div class="workflow-recommend">
    <div class="workflow-container">
      <!-- 标题 -->
      <div class="section-title">
        <div class="title-bar"></div>
        <h2 class="title-text">热门工作流</h2>
      </div>
      
      <!-- 分类标签 -->
      <div class="category-tabs">
        <div 
          v-for="category in categories" 
          :key="category.id"
          class="category-tab"
          :class="{ active: currentCategory === category.id }"
          @click="switchCategory(category.id)"
        >
          {{ category.name }}
        </div>
      </div>
      
      <!-- 骨架屏加载状态 -->
      <div v-if="loading" class="workflow-list">
        <div 
          v-for="i in 8" 
          :key="`skeleton-${i}`"
          class="workflow-item skeleton-item"
        >
          <!-- 封面骨架屏 -->
          <div class="workflow-cover skeleton-cover">
            <el-skeleton-item variant="image" style="width: 100%; height: 100%; border-radius: 0;" />
            <!-- 渐变遮罩层 -->
            <div class="gradient-overlay"></div>
            <!-- VIP标签骨架屏 -->
            <el-skeleton-item variant="text" style="position: absolute; top: 12px; right: 12px; width: 54px; height: 26px; border-radius: 4px;" />
            <!-- 使用次数骨架屏 -->
            <el-skeleton-item variant="text" style="position: absolute; bottom: 80px; right: 12px; width: 60px; height: 20px; border-radius: 4px;" />
            <!-- 内容骨架屏 -->
            <div class="workflow-info">
              <el-skeleton-item variant="h3" style="width: 80%; height: 16px; margin-bottom: 12px; background: rgba(255,255,255,0.3);" />
              <div class="user-info">
                <div class="user-left">
                  <el-skeleton-item variant="circle" style="width: 28px; height: 28px; background: rgba(255,255,255,0.3);" />
                  <el-skeleton-item variant="text" style="width: 60px; height: 12px; background: rgba(255,255,255,0.3);" />
                </div>
                <el-skeleton-item variant="text" style="width: 68px; height: 28px; border-radius: 4px; background: rgba(255,255,255,0.3);" />
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 错误提示 -->
      <div v-if="error" class="error-message">
        <p>{{ error }}</p>
        <button @click="initData" class="retry-button">重试</button>
      </div>
      
      <!-- 工作流列表 -->
      <div v-else-if="!loading && filteredWorkflows.length > 0" class="workflow-list">
        <div 
          v-for="workflow in filteredWorkflows" 
          :key="workflow.id"
          class="workflow-item"
          @click="handleWorkflowClick(workflow)"
        >
          <!-- 工作流封面 -->
          <div class="workflow-cover">
            <img :src="workflow.cover" :alt="workflow.title" />
            <!-- 渐变遮罩层 -->
            <div class="gradient-overlay"></div>
            <!-- VIP标签 - 右上角 -->
            <div class="vip-badge" :class="workflow.type">
              <img 
                v-if="workflow.type === 'free'" 
                src="../assets/vip_icon/免费.svg" 
                alt="免费" 
                class="vip-icon"
              />
              <img 
                v-else-if="workflow.type === 'vip'" 
                src="../assets/vip_icon/VIP.svg" 
                alt="VIP" 
                class="vip-icon"
              />
              <img 
                v-else-if="workflow.type === 'svip'" 
                src="../assets/vip_icon/SVIP.svg" 
                alt="SVIP" 
                class="vip-icon"
              />
            </div>
            <!-- 使用次数 -->
            <!-- <div class="usage-count">{{ workflow.usageCount || 0 }}次使用</div> -->
            <!-- 工作流信息 -->
            <div class="workflow-info">
              <h3 class="workflow-title">{{ workflow.title }}</h3>
              <div class="user-info">
                <div class="user-left">
                  <img :src="workflow.userAvatar" :alt="workflow.userName" class="user-avatar" />
                  <span class="user-name">{{ workflow.userName }}</span>
                </div>
                <div class="tag-button" @click.stop="handleWorkflowClick(workflow)">
                  <span>立即使用</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 空状态 -->
      <div v-else-if="!loading && filteredWorkflows.length === 0" class="empty-state">
        <div class="empty-icon"></div>
        <p class="empty-text">暂无工作流数据</p>
      </div>
      
      <!-- 分页组件 -->
      <div v-if="showPagination && !loading && filteredWorkflows.length > 0" class="pagination-container">
        <div class="pagination">
          <button 
            v-for="page in getPageNumbers()" 
            :key="page"
            class="page-button"
            :class="{ active: page === pagination.current, ellipsis: page === '...' }"
            @click="page !== '...' && handlePageChange(page)"
            :disabled="page === '...'"
          >
            {{ page }}
          </button>
          <button 
            v-if="pagination.current < pagination.pages"
            class="page-button next-button"
            @click="handlePageChange(pagination.current + 1)"
          >
            &gt;
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

import { getWorkflowCategories, getHotWorkflows, getWorkflowsByCategory } from '../api/workflow.js'
import { useRouter } from 'vue-router'
import { isLoggedIn } from '../utils/auth.js'

// 定义props
const props = defineProps({
  showPagination: {
    type: Boolean,
    default: false
  }
})

// 定义emits
const emit = defineEmits(['showLoginModal'])

// 路由实例
const router = useRouter()

// 根据fullAccessRole获取工作流类型
const getWorkflowType = (fullAccessRole) => {
  switch (fullAccessRole) {
    case 1:
      return 'free'  // 普通用户可访问，显示免费标签
    case 2:
      return 'vip'   // VIP用户可访问，显示VIP标签
    case 3:
      return 'svip'  // SVIP用户可访问，显示SVIP标签
    default:
      return 'free'  // 默认显示免费标签
  }
}

// 加载状态
const loading = ref(true)

// 当前选中的分类
const currentCategory = ref('hot')

// 分类数据
const categories = ref([
])

// 工作流数据
const workflows = ref([])

// 错误状态
const error = ref(null)

// 分页数据
const pagination = ref({
  current: 1,
  size: 32,
  total: 0,
  pages: 0
})

// 是否显示分页
const showPagination = computed(() => {
  return props.showPagination && pagination.value.total > pagination.value.size
})

// 获取分类列表
const fetchCategories = async () => {
  try {
    const response = await getWorkflowCategories()
    if (response.code === 200) {
      categories.value = [
       
        ...response.data.map(category => ({
          id: category.id,
          name: category.name
        }))
      ]
    }
  } catch (err) {
    console.error('获取分类列表失败:', err)
    error.value = '获取分类列表失败'
  }
}

// 获取热门工作流
const fetchHotWorkflows = async () => {
  try {
    loading.value = true
    const response = await getHotWorkflows({
      page: pagination.value.current,
      size: pagination.value.size
    })
    if (response.code === 200) {
      // 处理分页数据结构
      const records = response.data?.records || response.data || []
      workflows.value = records.map(workflow => ({
        id: workflow.id,
        title: workflow.name,
        cover: workflow.coverUrl,
        type: getWorkflowType(workflow.fullAccessRole),
        usageCount: workflow.likeCount || 0,
        userAvatar: workflow.creator?.avatarUrl,
        userName: workflow.creator?.username,
        category: workflow.category
      }))
      
      // 更新分页信息
      if (response.data) {
        pagination.value.total = response.data.total || 0
        pagination.value.pages = response.data.pages || 0
      }
    }
  } catch (err) {
    console.error('获取热门工作流失败:', err)
    error.value = '获取热门工作流失败'
  } finally {
    loading.value = false
  }
}

// 根据分类获取工作流
const fetchWorkflowsByCategory = async (categoryId) => {
  try {
    loading.value = true
    const response = await getWorkflowsByCategory(categoryId, {
      page: pagination.value.current,
      size: pagination.value.size
    })
    if (response.code === 200) {
      // 处理分页数据结构
      const records = response.data?.records || response.data || []
      workflows.value = records.map(workflow => ({
        id: workflow.id,
        title: workflow.name,
        cover: workflow.coverUrl,
        type: getWorkflowType(workflow.fullAccessRole),
        usageCount: workflow.likeCount || 0,
        userAvatar: workflow.creator?.avatarUrl,
        userName: workflow.creator?.username,
        category: workflow.category
      }))
      
      // 更新分页信息
      if (response.data) {
        pagination.value.total = response.data.total || 0
        pagination.value.pages = response.data.pages || 0
      }
    }
  } catch (err) {
    console.error('获取分类工作流失败:', err)
    error.value = '获取分类工作流失败'
  } finally {
    loading.value = false
  }
}

// 根据分类筛选工作流
const filteredWorkflows = computed(() => {
  return workflows.value
})

// 切换分类
const switchCategory = async (categoryId) => {
  currentCategory.value = categoryId
  pagination.value.current = 1
  error.value = null
  
  if (categoryId === 'hot') {
    await fetchHotWorkflows()
  } else {
    await fetchWorkflowsByCategory(categoryId)
  }
}

// 切换页码
const handlePageChange = async (page) => {
  pagination.value.current = page
  if (currentCategory.value === 'hot') {
    await fetchHotWorkflows()
  } else {
    await fetchWorkflowsByCategory(currentCategory.value)
  }
}

// 生成页码数组
const getPageNumbers = () => {
  const pages = []
  const current = pagination.value.current
  const total = pagination.value.pages
  
  if (total <= 7) {
    // 如果总页数小于等于7，显示所有页码
    for (let i = 1; i <= total; i++) {
      pages.push(i)
    }
  } else {
    // 如果总页数大于7，显示部分页码
    if (current <= 4) {
      // 当前页在前4页
      for (let i = 1; i <= 7; i++) {
        pages.push(i)
      }
      pages.push('...')
      pages.push(total)
    } else if (current >= total - 3) {
      // 当前页在后4页
      pages.push(1)
      pages.push('...')
      for (let i = total - 6; i <= total; i++) {
        pages.push(i)
      }
    } else {
      // 当前页在中间
      pages.push(1)
      pages.push('...')
      for (let i = current - 2; i <= current + 2; i++) {
        pages.push(i)
      }
      pages.push('...')
      pages.push(total)
    }
  }
  
  return pages
}

// 处理工作流卡片点击
const handleWorkflowClick = (workflow) => {
  // 检查用户是否已登录
  if (!isLoggedIn()) {
    // 未登录，触发显示登录弹窗事件
    emit('showLoginModal', '请先登录后查看工作流详情')
    return
  }
  
  // 数据类型验证 - 确保这是工作流数据
  console.log('[WorkflowRecommend] 点击工作流详情:', {
    id: workflow.id,
    title: workflow.title || workflow.name,
    type: workflow.type || 'workflow',
    dataSource: 'WorkflowRecommend'
  })
  
  // 强制确保跳转到工作流页面
  if (workflow.type === 'course' || workflow.type === 'video') {
    console.warn('[WorkflowRecommend] 警告：工作流组件中发现课程数据!', workflow)
    router.push(`/course/${workflow.id}`)
  } else {
    // 已登录，跳转到工作流详情页
    router.push(`/workflow/${workflow.id}`)
  }
}

// 初始化数据
const initData = async () => {
  await fetchCategories()
  await fetchHotWorkflows()
}

// 组件挂载时初始化
onMounted(() => {
  initData()
})
</script>

<style scoped>
.workflow-recommend {
  width: 100%;
  min-height: 800px;
  background: rgba(247, 248, 250, 1);
  padding: 0px 40px 80px 40px;
  overflow: hidden;
  box-sizing: border-box;
}

.workflow-container {
  width: 100%;
  max-width: 1440px;
  margin: 0 auto;
  box-sizing: border-box;
}

/* 标题样式 */
.section-title {
  width: 312px;
  display: flex;
  align-items: center;
  gap: 12px;
  margin-top: 70px;
  margin-bottom: 20px;
}

.title-bar {
  width: 4px;
  height: 24px;
  background: #333;
  border-radius: 2px;
}

.title-text {
  font-family: Arial, sans-serif;
  font-weight: 600;
  font-size: 24px;
  line-height: 28px;
  letter-spacing: 0px;
  color: #333;
  margin: 0;
  text-align: left;
}

/* 分类标签样式 */
.category-tabs {
  display: flex;
  gap: 20px;
  margin-bottom: 40px;
  padding-bottom: 20px;
  border-bottom: 2px solid rgba(0, 0, 0, 0.1);
  flex-wrap: wrap;
  justify-content: flex-start;
  width: 100%;
}

.category-tab {
  width: 120px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  border: 1px solid #e0e0e0;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
  font-weight: 500;
  color: #666;
  flex-shrink: 0;
}

.category-tab:hover {
  background: #f5f5f5;
  border-color: #d0d0d0;
}

.category-tab.active {
  background: #333;
  color: white;
  border-color: #333;
}

/* 工作流列表样式 */
.workflow-list {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 24px;
  justify-content: start;
  overflow-y: auto;
  padding-bottom: 0px;
  min-height: 500px;
  width: 100%;
  box-sizing: border-box;
  -ms-overflow-style: none;  /* IE and Edge */
  scrollbar-width: none;  /* Firefox */
}

.workflow-list::-webkit-scrollbar {
  display: none;
}

/* 工作流卡片样式 */
.workflow-item {
  width: 100%;
  height: 394px; /* 固定高度确保所有卡片大小一致 */
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  cursor: pointer;
  border: 1px solid #f0f0f0;
  position: relative;
}

/* 骨架屏样式 */
.skeleton-item {
  width: 100%;
  height: 394px; /* 固定高度与正常卡片保持一致 */
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
}

.skeleton-cover {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.skeleton-item .user-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 0;
}

.skeleton-item .user-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.workflow-item:hover {
  transform: translateY(-8px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
}

/* 工作流封面样式 */
.workflow-cover {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.workflow-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.workflow-item:hover .workflow-cover img {
  transform: scale(1.05);
}

/* 渐变遮罩层 */
.gradient-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50%;
  background: linear-gradient(to top, rgba(0, 0, 0, 1), rgba(0, 0, 0, 0));
  pointer-events: none;
}

/* VIP标签样式 - 右上角 */
.vip-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  z-index: 10;
}

.vip-icon {
  width: 54px;
  height: 26px;
  object-fit: contain;
}

/* 使用次数样式 */
.usage-count {
  position: absolute;
  bottom: 80px;
  right: 12px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 4px 8px;
  border-radius: 8px;
  font-size: 12px;
  font-weight: 500;
  z-index: 5;
}

/* 工作流信息样式 */
.workflow-info {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20px 16px 16px;
  z-index: 5;
}

.workflow-title {
  font-family: Arial, sans-serif;
  font-weight: 500;
  font-size: 16px;
  line-height: 18px;
  letter-spacing: 0px;
  color: #ffffff;
  margin: 0 0 12px 0;
  text-align: left;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 用户信息样式 */
.user-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 0;
  height: 28px;
  min-width: 0;
  overflow: hidden;
}

.user-left {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
  min-width: 0;
}

.user-avatar {
  width: 28px !important;
  height: 28px !important;
  border-radius: 50%;
  object-fit: cover;
  flex-shrink: 0;
  max-width: 28px !important;
  max-height: 28px !important;
}

.user-name {
  font-family: Arial, sans-serif;
  font-weight: 400;
  font-size: 12px;
  line-height: 14px;
  letter-spacing: 0px;
  color: #ffffff;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 80px;
}

.tag-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 68px;
  height: 28px;
  background: #ffffff;
  border: 1px solid rgba(29, 0, 255, 1);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  flex-shrink: 0;
}

.tag-button span {
  font-family: Arial, sans-serif;
  font-size: 12px;
  line-height: 14px;
  letter-spacing: 0px;
  color: rgba(29, 0, 255, 1);
  font-weight: 400;
  text-align: center;
}

.tag-button:hover {
  background: rgba(29, 0, 255, 0.05);
  border-color: rgba(29, 0, 255, 0.8);
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .workflow-list {
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;
  }
  
  .category-tabs {
    gap: 16px;
  }
  
  .category-tab {
    width: 110px;
  }
}

@media (max-width: 1100px) {
  .workflow-list {
    grid-template-columns: repeat(2, 1fr);
    gap: 18px;
  }
  
  .category-tabs {
    gap: 14px;
  }
  
  .category-tab {
    width: 100px;
    height: 44px;
    font-size: 13px;
  }
  
  .workflow-recommend {
    padding: 0 30px 80px 30px;
  }
}

@media (max-width: 768px) {
  .workflow-list {
    grid-template-columns: repeat(1, 1fr);
    gap: 16px;
  }
  
  .category-tabs {
    flex-wrap: wrap;
    gap: 12px;
    justify-content: flex-start;
  }
  
  .category-tab {
    width: 90px;
    height: 40px;
    font-size: 12px;
  }
  
  .workflow-recommend {
    padding: 0 20px 80px 20px;
  }
  
  .workflow-item {
    height: 320px; /* 固定高度确保响应式下卡片大小一致 */
  }
  
  .workflow-title {
    font-size: 14px;
    line-height: 16px;
  }
  
  .user-avatar {
    width: 28px !important;
    height: 28px !important;
    max-width: 28px !important;
    max-height: 28px !important;
  }
  
  .user-name {
    font-size: 11px;
    max-width: 70px;
  }
  
  .tag-button {
    width: 60px;
    height: 28px;
  }
  
  .tag-button span {
    font-size: 11px;
    line-height: 13px;
  }
  
  .section-title {
    margin-top: 0;
  }
  
  .title-text {
    font-size: 20px;
  }
  
  /* 骨架屏响应式调整 */
  .skeleton-item {
    height: 320px; /* 固定高度与响应式卡片保持一致 */
  }
}

/* 错误提示样式 */
.error-message {
  text-align: center;
  padding: 40px 20px;
  color: #666;
}

.error-message p {
  margin: 0 0 20px 0;
  font-size: 16px;
}

.retry-button {
  background: #333;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.3s ease;
}

.retry-button:hover {
  background: #555;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-text {
  font-size: 16px;
  margin: 0;
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 40px;
  padding: 20px 0;
}

.pagination {
  display: flex;
  gap: 8px;
  align-items: center;
}

.page-button {
  min-width: 40px;
  height: 40px;
  border: 1px solid #e0e0e0;
  background: white;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
  font-weight: 500;
  color: #666;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 12px;
}

.page-button:hover:not(.ellipsis):not(:disabled) {
  background: #f5f5f5;
  border-color: #d0d0d0;
}

.page-button.active {
  background: #333;
  color: white;
  border-color: #333;
}

.page-button.ellipsis {
  cursor: default;
  background: white;
  border-color: #e0e0e0;
  color: #999;
}

.page-button:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.next-button {
  font-weight: bold;
}

@media (max-width: 480px) {
  .workflow-recommend {
    padding: 0 15px 80px 15px;
  }
  
  .category-tabs {
    gap: 10px;
  }
  
  .category-tab {
    width: 80px;
    height: 36px;
    font-size: 11px;
  }
  
  .workflow-list {
    grid-template-columns: repeat(1, 1fr);
    gap: 12px;
  }
  
  .workflow-item {
    height: 280px; /* 固定高度确保移动端卡片大小一致 */
  }
  
  .workflow-title {
    font-size: 13px;
    line-height: 15px;
  }
  
  .user-avatar {
    width: 28px !important;
    height: 28px !important;
    max-width: 28px !important;
    max-height: 28px !important;
  }
  
  .user-name {
    font-size: 10px;
    max-width: 60px;
  }
  
  .tag-button {
    width: 52px;
    height: 28px;
  }
  
  .tag-button span {
    font-size: 10px;
    line-height: 12px;
  }
  
  .section-title {
    margin-top: 0;
  }
  
  .title-text {
    font-size: 18px;
  }
  
  /* 骨架屏响应式调整 */
  .skeleton-item {
    height: 280px; /* 固定高度与移动端卡片保持一致 */
  }
}
</style> 