<template>
  <div class="plaza-home">
    <!-- 顶部筛选 Tab -->
    <div class="tabs">
      <button :class="{ active: sortBy === 'latest' }" @click="changeSort('latest')">最新</button>
      <button :class="{ active: sortBy === 'hot' }" @click="changeSort('hot')">最热</button>
    </div>

    <!-- 瀑布流组件 -->
    <WaterfallGrid
      :items="works"
      :loading="loading"
      :has-more="hasMore"
      :carousel-data="bannerList"
      :show-carousel="bannerList.length > 0"
      :is-logged-in="isLoggedIn"
      @load-more="loadMore"
      @view-detail="handleViewDetail"
      @make-same="handleMakeSame"
      @like-click="toggleLike"
      @carousel-click="handleBannerClick"
      @download="handleDownload"
      @share="handleShare"
      @share-wechat="handleShareWechat"
      @share-xiaohongshu="handleShareXiaohongshu"
      @share-link="handleShareLink"
      @more="handleMore"
      @copy-prompt="handleCopyPrompt"
      @report="handleReport"
      @need-login="handleNeedLogin"
    />
    </div>

  <!-- 登录弹窗 -->
  <LoginModal
    v-if="showLoginModal"
    :visible="showLoginModal"
    mode="login"
    @login="handleLoginSuccess"
    @close="handleCloseLogin"
  />
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { getPlazaWorks, likeWork, unlikeWork, getWorkDetail } from '../../api'
import { submitReport } from '../../api/plaza'
import { getBannerList } from '@/api/banner'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user'
import WaterfallGrid from '@/components/WaterfallGrid.vue'
import LoginModal from '@/components/LoginModal.vue'

const router = useRouter()
const userStore = useUserStore()
const isLoggedIn = computed(() => userStore.getIsLoggedIn)

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

const works = ref([])
const bannerList = ref([])
const page = ref(1)
const size = ref(20)
const total = ref(0)
const loading = ref(false)
const sortBy = ref('latest')
const isLoadingMore = ref(false)

const hasMore = computed(() => works.value.length < total.value)

const fetchData = async (reset = false) => {
  if (loading.value) return
  loading.value = true
  try {
    const res = await getPlazaWorks({ page: page.value, size: size.value, sortBy: sortBy.value })
    if (res?.code === 200) {
      total.value = res.data?.total || 0
      const list = res.data?.list || []
      works.value = reset ? list : works.value.concat(list)
    }
  } finally {
    loading.value = false
  }
}

const handleNeedLogin = () => {
  showLoginModal.value = true
}

const handleLoginSuccess = () => {
  showLoginModal.value = false
  ElMessage.success('登录成功')
  // 刷新数据
  page.value = 1
  works.value = []
  fetchData(true)
}

const handleCloseLogin = () => {
  showLoginModal.value = false
}
// 获取Banner列表
const fetchBannerList = async () => {
  try {
    const res = await getBannerList()
    if (res?.data) {
      bannerList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (error) {
    console.error('获取Banner列表失败:', error)
    bannerList.value = []
  }
}

const loadMore = () => {
  if (!hasMore.value || isLoadingMore.value) return
  isLoadingMore.value = true
  page.value += 1
  fetchData().finally(() => {
    isLoadingMore.value = false
  })
}

// 切换点赞
const toggleLike = async (work) => {
  const w = works.value.find(i => i.workNo === work.workNo)
  if (!w) return

  const originalLiked = w.isLiked
  const originalCount = w.likeCount || 0

  try {
    // 乐观更新
    w.isLiked = !originalLiked
    w.likeCount = originalCount + (w.isLiked ? 1 : -1)

    // 调用API
    if (w.isLiked) {
      await likeWork(work.workNo)
    } else {
      await unlikeWork(work.workNo)
    }
  } catch (error) {
    // 如果失败，恢复原状态
    w.isLiked = originalLiked
    w.likeCount = originalCount
    ElMessage.error(error.response?.data?.message || '操作失败')
  }
}

// 做同款 - 先获取详情数据，再跳转
const handleMakeSame = async (work) => {
  console.log('做同款:', work)

  try {
    // 显示加载提示
    const loadingMsg = ElMessage.info('正在准备数据...')

    // 获取完整的作品详情
    const res = await getWorkDetail(work.workNo)
    if (res?.code !== 200 || !res.data) {
      ElMessage.error('获取作品详情失败')
      return
    }

    const detailWork = res.data
    console.log('获取到的详情数据:', detailWork)

    // 关闭加载提示
    loadingMsg.close()

    // 根据任务类型跳转到对应的创作页面
    const taskType = detailWork.taskType
    let routePath = ''
    let query = {}

    // 根据任务类型判断跳转路由和参数
    switch (taskType) {
      case 'text_to_video':
        // 文生视频 - 跳转到 Create.vue，模式为 text
        routePath = '/ai-application/create'
        query.mode = 'text'
        if (detailWork.prompt) {
          query.prompt = detailWork.prompt
        }
        if (detailWork.aspectRatio) {
          query.aspectRatio = detailWork.aspectRatio
        }
        if (detailWork.modelName) {
          query.modelName = detailWork.modelName
        }
        break

      case 'image_to_video':
        // 图生视频 - 跳转到 Create.vue，模式为 image
        routePath = '/ai-application/create'
        query.mode = 'image'
        if (detailWork.prompt) {
          query.prompt = detailWork.prompt
        }
        if (detailWork.imageUrl) {
          query.imageUrl = detailWork.imageUrl
        }
        if (detailWork.aspectRatio) {
          query.aspectRatio = detailWork.aspectRatio
        }
        if (detailWork.modelName) {
          query.modelName = detailWork.modelName
        }
        break

      case 'text_to_image':
        // 文生图 - 跳转到 ImageCreate.vue
        routePath = '/ai-application/image-create'
        if (detailWork.prompt) {
          query.prompt = detailWork.prompt
        }
        if (detailWork.imageUrl) {
          query.imageUrl = detailWork.imageUrl
        }
        if (detailWork.aspectRatio) {
          query.aspectRatio = detailWork.aspectRatio
        }
        break

      case 'storyboard_video':
      case 'storyboard_to_video':
        // 分镜视频 - 跳转到 Create.vue，模式为 storyboard
        routePath = '/ai-application/create'
        query.mode = 'storyboard'
        if (detailWork.prompt) {
          query.prompt = detailWork.prompt
        }
        if (detailWork.imageUrl) {
          query.imageUrl = detailWork.imageUrl
        }
        if (detailWork.aspectRatio) {
          query.aspectRatio = detailWork.aspectRatio
        }
        break

      default:
        // 默认跳转到创作页面
        routePath = '/ai-application/create'
        query.mode = 'text'
        if (detailWork.prompt) {
          query.prompt = detailWork.prompt
        }
        if (detailWork.aspectRatio) {
          query.aspectRatio = detailWork.aspectRatio
        }
    }

    console.log('跳转参数:', { path: routePath, query })

    // 跳转到创作页面
    router.push({
      path: routePath,
      query: query
    })

    ElMessage.success('正在为您跳转到创作页面...')
  } catch (error) {
    console.error('做同款失败:', error)
    ElMessage.error(error.response?.data?.message || '操作失败，请重试')
  }
}

// 查看详情
const handleViewDetail = (work) => {
  if (!work || !work.workNo) {
    ElMessage.error('作品信息无效')
    return
  }
  router.push({
    name: 'AIApplicationWorkDetail',
    params: { id: work.workNo }
  })
}


// Banner点击跳转处理
const handleBannerClick = (item, event) => {
  if (event) {
  event.stopPropagation()
  }

  if (!item.link) return

  if (item.linkType === 'external') {
    window.open(item.link, '_blank', 'noopener,noreferrer')
    return
  }

  // 内部链接处理
  const courseMatch = item.link.match(/^\/course\/(\d+)$/)
  const workflowMatch = item.link.match(/^\/workflow\/(\d+)$/)

  if (courseMatch || workflowMatch) {
    router.push(item.link)
    return
  }

  // 尝试修复链接格式
  const idMatch = item.link.match(/\/(\d+)$/)
  if (idMatch) {
    if (item.contentType === 'course') {
      router.push(`/course/${idMatch[1]}`)
    } else if (item.contentType === 'workflow') {
      router.push(`/workflow/${idMatch[1]}`)
    } else {
      router.push(item.link)
    }
  } else {
    router.push(item.link)
  }
}

const changeSort = (newSortBy) => {
  if (sortBy.value === newSortBy) return // 避免重复点击相同按钮

  sortBy.value = newSortBy
  page.value = 1
  works.value = [] // 清空现有数据，显示加载效果
  fetchData(true)
}

// 下载
const handleDownload = (work) => {
  if (!work || !work.resultUrl) {
    ElMessage.warning('暂无下载资源')
    return
  }
  // 创建下载链接
  const link = document.createElement('a')
  link.href = work.resultUrl
  link.download = work.title || '作品'
  link.target = '_blank'
  document.body.appendChild(link)
  link.click()
  link.remove()
  ElMessage.success('开始下载')
}

const copyShareLink = (url, successMessage) => {
  navigator.clipboard.writeText(url).then(() => {
    ElMessage.success(successMessage)
  }).catch(() => {
    ElMessage.error('复制失败，请手动复制')
  })
}

const buildShareUrl = (work) => `${globalThis.location.origin}/ai-application/work/${work.workNo}`

// 分享
const handleShare = (work) => {
  if (!work || !work.workNo) {
    ElMessage.warning('作品信息无效')
    return
  }
  copyShareLink(buildShareUrl(work), '链接已复制到剪贴板')
}

// 分享到微信
const handleShareWechat = (work) => {
  if (!work || !work.workNo) {
    ElMessage.warning('作品信息无效')
    return
  }
  const url = `${buildShareUrl(work)}?source-scene=shared&source-media=shared_wechat`
  copyShareLink(url, '微信分享链接已复制')
}

// 分享到小红书
const handleShareXiaohongshu = (work) => {
  if (!work || !work.workNo) {
    ElMessage.warning('作品信息无效')
    return
  }
  const url = `${buildShareUrl(work)}?source-media=shared_xiaohongshu`
  copyShareLink(url, '小红书分享链接已复制')
}

// 分享链接
const handleShareLink = (work) => {
  handleShare(work)
}

// 举报原因映射到英文类型
const getReportType = (reason) => {
  const typeMap = {
    '政治敏感': 'political',
    '色情低俗': 'pornographic',
    '暴力血腥': 'violent',
    '危险行为': 'dangerous',
    '引人不适': 'disturbing',
    '其他': 'other'
  }
  return typeMap[reason] || 'other'
}

// 举报提交
const handleReport = async ({ item, reason, extra }) => {
  if (!item || !item.workNo) {
    ElMessage.warning('作品信息无效')
    return
  }

  try {
    const reportType = getReportType(reason)
    const reportReason = extra ? `${reason}：${extra}` : reason

    const response = await submitReport({
      workNo: item.workNo,
      reportType: reportType,
      reportReason: reportReason
    })

    if (response?.code === 200 || response?.code === 0) {
      ElMessage.success('举报信息已提交，感谢您的反馈')
    } else {
      ElMessage.error(response?.message || '举报提交失败，请稍后重试')
    }
  } catch (error) {
    console.error('举报提交失败:', error)
    ElMessage.error(error?.message || '举报提交失败，请稍后重试')
  }
}

// 更多操作
const handleMore = (work) => {
  if (!work || !work.workNo) {
    ElMessage.warning('作品信息无效')
  }
  // 这里可以显示更多操作菜单，比如收藏、举报等
}

// 复制提示词
const handleCopyPrompt = (work, prompt) => {
  if (!prompt) {
    ElMessage.warning('暂无提示词')
    return
  }
  navigator.clipboard.writeText(prompt).then(() => {
    ElMessage.success('提示词已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败，请手动复制')
  })
}

onMounted(() => {
  fetchBannerList()
  fetchData(true)
})
</script>

<style scoped>
.plaza-home {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  background: #151515;
  min-height: 100vh;
}

/* 顶部 tabs */
.tabs {
  display: flex;
  gap: 12px;
  margin-bottom: 24px;
  background: #1e293b;
  padding: 6px;
  border-radius: 12px;
  border: 1px solid #334155;
  width: fit-content;
}

.tabs button {
  background: transparent;
  color: #94a3b8;
  border: none;
  padding: 10px 24px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-size: 14px;
  font-weight: 600;
  position: relative;
  min-width: 80px;
}

.tabs button::before {
  content: '';
  position: absolute;
  inset: 0;
  border-radius: 8px;
  opacity: 0;
  transition: opacity 0.3s ease;
  z-index: -1;
}

.tabs button.active {
  color: #fff;
  text-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
}

.tabs button.active::before {
  opacity: 1;
}

.tabs button:hover:not(.active) {
  background: #334155;
  color: #e2e8f0;
  transform: translateY(-1px);
}

.tabs button:active {
  transform: translateY(0);
}

@media (max-width: 768px) {
  .plaza-home {
    padding: 16px;
  }
}
</style>