<template>
  <div class="manage-work">
    <div class="page-header">
      <h1 class="page-title">作品管理</h1>
      <p class="page-description">管理您已发布的作品</p>
    </div>
    
    <div class="manage-content">
      <div class="toolbar">
        <div class="search-filter-row">
          <input
            v-model="filters.keyword"
            class="search-input"
            type="text"
            placeholder="搜索关键词（标题/描述）"
            @input="handleInstantSearch"
            @keyup.enter="handleSearch"
          />
          <select v-model="filters.type" class="select" @change="handleInstantSearch">
            <option value="course">课程</option>
            <option value="workflow">工作流</option>
          </select>
          <select v-model="filters.auditStatus" class="select" @change="handleInstantSearch">
            <option :value="undefined">全部状态</option>
            <option :value="0">待审核</option>
            <option :value="1">已通过</option>
            <option :value="2">未通过</option>
          </select>
        </div>
      </div>

      <div class="works-list">
        <div class="works-table-container">
          <div v-if="loading" class="empty">加载中...</div>
          <div v-else-if="!worksList.length" class="empty">暂无数据</div>
          <table v-else class="works-table">
            <thead>
              <tr>
                <th class="name-col">作品名称</th>
                <th class="category-col">作品分类</th>
                <th class="status-col">状态</th>
                <th class="action-col">操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="item in worksList" :key="getId(item)" class="work-row">
                <td class="name-col">
                  <div class="work-name-cell">
                    <div class="work-thumbnail" v-if="item.coverUrl">
                      <img :src="item.coverUrl" alt="cover" />
                    </div>
                    <div class="work-thumbnail placeholder" v-else>
                      <span>无图</span>
                    </div>
                    <div class="work-info">
                      <div class="work-title">{{ item.title || '未命名作品' }}</div>
                      
                    </div>
                  </div>
                </td>
                <td class="category-col">
                  <el-tag size="small" class="category-tag" effect="plain">
                    {{ getCategoryDisplay(item) }}
                  </el-tag>
                </td>
                <td class="status-col">
                  <div class="status-item" :class="'status-' + item.auditStatus">
                    <span v-if="item.auditStatus === 0 || item.auditStatus === '0'" class="status-dot warning"></span>
                    <span v-if="item.auditStatus === 1 || item.auditStatus === '1'" class="status-dot success"></span>
                    <span v-if="item.auditStatus === 2 || item.auditStatus === '2'" class="status-dot danger"></span>
                    <span class="status-text">{{ formatAuditStatus(item.auditStatus) }}</span>
                  </div>
                </td>
                <td class="action-col">
                  <div class="work-actions">
                    <button class="action-btn view-btn" @click="onView(item)">查看</button>
                    <span class="action-divider">|</span>
                    <button class="action-btn delete-btn" @click="onDelete(item)">删除</button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <div class="pagination" v-if="pagination.total > 0">
          <button :disabled="pagination.page === 1 || loading" @click="toPrev">上一页</button>
          <span class="page-info">第 {{ pagination.page }} / {{ totalPages }} 页，共 {{ pagination.total }} 条</span>
          <button :disabled="pagination.page >= totalPages || loading" @click="toNext">下一页</button>
        </div>
      </div>
    </div>

    <!-- 课程详情弹窗组件 -->
    <CourseDetailModal
      v-if="filters.type === 'course'"
      v-model="showDetailModal"
      :work-id="currentWorkId"
      :list-item="currentListItem"
      @refresh="fetchWorks"
    />
    
    <!-- 工作流详情弹窗组件 -->
    <WorkflowDetailModal
      v-if="filters.type === 'workflow'"
      v-model="showDetailModal"
      :workflow-id="currentWorkId"
      :list-item="currentListItem"
      :json-data="currentListItem?.data || currentListItem?.jsonData || ''"
      :data-file-url="currentListItem?.dataFileUrl || currentListItem?.dataFile || ''"
      @refresh="fetchWorks"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { getUserContents, deleteUserContent } from '@/api/index.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import CourseDetailModal from './CourseDetailModal.vue'
import WorkflowDetailModal from './WorkflowDetailModal.vue'

// 基础数据
const worksList = ref([])
const loading = ref(false)

// 详情相关状态
const showDetailModal = ref(false)
const currentWorkId = ref('')
const currentListItem = ref(null)

// 即时搜索防抖计时器
let searchTimeout = null

const filters = reactive({
  keyword: '',
  auditStatus: undefined,
  type: 'workflow'
})

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

const totalPages = computed(() => {
  if (!pagination.size) return 1
  return Math.max(1, Math.ceil(pagination.total / pagination.size))
})

const getAuditStatusType = (val) => {
  if (val === 0 || val === '0') return 'info'
  if (val === 1 || val === '1') return 'success'
  if (val === 2 || val === '2') return 'danger'
  return 'info'
}

const formatAuditStatus = (val) => {
  if (val === 0 || val === '0') return '待审核'
  if (val === 1 || val === '1') return '已通过'
  if (val === 2 || val === '2') return '未通过'
  return '未知'
}

const getId = (item) => item?.id ?? item?.videoId ?? item?.courseId ?? item?._id ?? ''

const formatDuration = (seconds) => {
  if (!seconds || seconds <= 0) return '未知'
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const remainingSeconds = seconds % 60
  
  if (hours > 0) {
    return `${hours}:${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
  } else {
    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
  }
}

// 获取分类显示
const getCategoryDisplay = (item) => {
  if (filters.type === 'course') {
    return item.category || '课程'
  } else {
    return item.category || 'AIGC工作流'
  }
}

const extractListAndTotal = (res) => {
  let list = []
  let total = 0
  if (Array.isArray(res)) {
    list = res
    total = res.length
  } else if (res?.data) {
    const d = res.data
    if (Array.isArray(d?.records)) {
      list = d.records
      total = d.total ?? d.records.length
    } else if (Array.isArray(d?.list)) {
      list = d.list
      total = d.total ?? d.list.length
    } else if (Array.isArray(d?.items)) {
      list = d.items
      total = d.total ?? d.items.length
    }
  } else if (Array.isArray(res?.records)) {
    list = res.records
    total = res.total ?? res.records.length
  } else if (Array.isArray(res?.list)) {
    list = res.list
    total = res.total ?? res.list.length
  }
  
  // 适配数据结构差异：工作流使用 name，课程使用 title
  list = list.map(item => ({
    ...item,
    title: item.title || item.name, // 统一使用 title 字段
    name: item.name || item.title   // 保留原有字段
  }))
  
  return { list, total }
}

const fetchWorks = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      auditStatus: filters.auditStatus,
      keyword: filters.keyword?.trim() || undefined
    }
    const res = await getUserContents(filters.type, params)
    const { list, total } = extractListAndTotal(res)
    worksList.value = list || []
    pagination.total = Number(total) || (list ? list.length : 0)
  } catch (e) {
    console.error('获取作品列表失败', e)
    ElMessage.error('获取作品列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  fetchWorks()
}

// 即时搜索函数（带防抖）
const handleInstantSearch = () => {
  // 清除之前的定时器
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }
  
  // 设置新的定时器，300ms 后执行搜索
  searchTimeout = setTimeout(() => {
    pagination.page = 1
    fetchWorks()
  }, 300)
}

const toPrev = () => {
  if (pagination.page > 1) {
    pagination.page -= 1
    fetchWorks()
  }
}

const toNext = () => {
  if (pagination.page < totalPages.value) {
    pagination.page += 1
    fetchWorks()
  }
}

const onView = (item) => {
  const id = getId(item)
  if (!id) {
    ElMessage.error('无法获取作品ID')
    return
  }
  
  currentWorkId.value = id
  currentListItem.value = item || null
  showDetailModal.value = true
}





const onDelete = async (item) => {
  const id = getId(item)
  if (!id) {
    ElMessage.error('无法获取作品ID')
    return
  }
  
  try {
    await ElMessageBox.confirm('确认删除该作品？此操作不可恢复', '删除确认', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    loading.value = true
    await deleteUserContent(filters.type, id)
    ElMessage.success('删除成功')
    
    // 如果当前页删除后没有数据且不是第一页，自动回退一页
    if (worksList.value.length === 1 && pagination.page > 1) {
      pagination.page -= 1
    }
    fetchWorks()
  } catch (e) {
    if (e === 'cancel') {
      return // 用户取消操作
    }
    console.error('删除失败', e)
    ElMessage.error('删除失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchWorks()
})
</script>

<style scoped>
.manage-work {
  padding: 0px;
}

.page-header {
  margin-bottom: 30px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.page-description {
  color: #666;
  font-size: 14px;
}

.works-list {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
}

.toolbar {
  margin-bottom: 16px;
}

.search-filter-row {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.search-input {
  flex: 2;
  min-width: 200px;
  padding: 8px 12px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  font-size: 14px;
  font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  color: #333333;
  background: #ffffff;
  outline: none;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  box-sizing: border-box;
}

.search-input::placeholder {
  color: #999999 !important;
  opacity: 1;
}

.search-input:focus {
  border-color: #1e80ff;
}

.select {
  padding: 8px 12px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  background: #ffffff;
  color: #333333;
  font-size: 14px;
  font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  min-width: 120px;
  outline: none;
  cursor: pointer;
  box-sizing: border-box;
}

.select option {
  background: #ffffff;
  color: #333333;
  padding: 8px 12px;
  font-family: inherit;
}

/* 表格样式 */
.works-table-container {
  margin-top: 20px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
}

.works-table {
  width: 100%;
  border-collapse: collapse;
  background: white;
}

.works-table thead {
  background: #f8f9fa;
}

.works-table th {
  padding: 16px 12px;
  text-align: center;
  font-weight: 600;
  font-size: 14px;
  color: #333;
  border-bottom: 1px solid #e0e0e0;
}

.works-table td {
  padding: 16px 12px;
  border-bottom: 1px solid #f0f0f0;
  vertical-align: middle;
}

.works-table .name-col {
  text-align: left;
}

.works-table .category-col {
  text-align: center;
}

.works-table .status-col {
  text-align: center;
}

.works-table .action-col {
  text-align: center;
}

.works-table tbody tr:hover {
  background-color: #f8f9fa;
}

.works-table tbody tr:last-child td {
  border-bottom: none;
}

/* 列宽度 */
.name-col {
  width: 45%;
  min-width: 300px;
}

.category-col {
  width: 20%;
  min-width: 120px;
}

.status-col {
  width: 15%;
  min-width: 100px;
}

.action-col {
  width: 20%;
  min-width: 150px;
}

/* 作品名称单元格 */
.work-name-cell {
  display: flex;
  align-items: center;
  gap: 12px;
}

.work-thumbnail {
  width: 60px;
  height: 45px;
  border-radius: 6px;
  overflow: hidden;
  flex-shrink: 0;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.work-thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.work-thumbnail.placeholder {
  color: #999;
  font-size: 12px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.work-info {
  flex: 1;
  min-width: 0;
}

.work-title {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: left;
}

.work-desc {
  font-size: 12px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 分类标签 */
.category-tag {
  font-size: 14px;
  font-weight: 500;
  border-color: #722ED1;
  height: 24px;
  color:#722ED1;
}

/* 状态样式 */
.status-item {
  display: flex;
  align-items: center;
  gap: 6px;
  justify-content: center;
}

.status-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  flex-shrink: 0;
}

.status-dot.warning {
  background-color: #faad14;
}

.status-dot.success {
  background-color: #52c41a;
}

.status-dot.danger {
  background-color: #ff4d4f;
}

.status-text {
  font-size: 14px;
  font-weight: 400;
  color: #333;
}

/* 操作按钮 */
.work-actions {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

/* 操作按钮样式 - 黑白ins风格 */
.action-btn {
  padding: 6px 8px;
  border: 1.5px solid #000000;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #000000;
  background: transparent;
}

.action-divider {
  color: #cccccc;
  font-size: 14px;
  font-weight: 300;
  margin: 0 4px;
  user-select: none;
}

.view-btn {
  color: #000000;
  border-color: #000000;
}

.view-btn:hover {
  background-color: #000000;
  color: #ffffff;
  border-color: #000000;
}

.delete-btn {
  color: #2d2d2d;
  border-color: #2d2d2d;
}

.delete-btn:hover {
  background-color: #2d2d2d;
  color: #ffffff;
  border-color: #2d2d2d;
}

.empty {
  text-align: center;
  color: #888;
  padding: 40px;
  font-size: 14px;
}

.pagination {
  display: flex;
  gap: 12px;
  align-items: center;
  justify-content: center;
  margin-top: 16px;
}

.page-info {
  color: #666;
}

/* 分页按钮样式 - 黑白ins风格 */
.pagination button {
  padding: 8px 16px;
  border: 1.5px solid #000000;
  background: white;
  color: #000000;
  border-radius: 6px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.pagination button:hover:not(:disabled) {
  background-color: #000000;
  border-color: #000000;
  color: #ffffff;
}

.pagination button:disabled {
  background-color: #f5f5f5;
  border-color: #d9d9d9;
  color: #b3b3b3;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-filter-row {
    flex-direction: column;
    gap: 8px;
    align-items: stretch;
  }
  
  .search-input {
    flex: none;
    min-width: 150px;
    width: 100%;
  }
  
  .select {
    min-width: 100px;
    flex: 1;
  }
  
  .works-table-container {
    overflow-x: auto;
  }
  
  .works-table {
    min-width: 600px;
  }
  
  .work-name-cell {
    gap: 8px;
  }
  
  .work-thumbnail {
    width: 40px;
    height: 30px;
  }
  
  .work-actions {
    flex-direction: column;
    gap: 4px;
  }
  
  .action-divider {
    display: none;
  }
  
  .action-btn {
    width: 100%;
    text-align: center;
  }
  
  .pagination {
    flex-direction: column;
    gap: 8px;
  }
  
  .pagination button {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .name-col {
    min-width: 250px;
  }
  
  .work-title {
    font-size: 13px;
  }
  
  .work-desc {
    font-size: 11px;
  }
}
</style> 