<template>
  <div class="admin-workflow-videos admin-theme">
    <AdminSidebar active="workflowVideos" />

    <!-- 主内容区域 -->
    <main class="main-content">
      <AdminHeader :title="$t('nav.workflowVideos')" />

      <!-- 视频管理内容 -->
      <section class="video-content">
        <div class="content-header">
          <h2>{{ t('workflowVideo.management') }}</h2>
          <a-button type="primary" size="small" @click="openCreateDialog">
            <PlusOutlined /> {{ t('workflowVideo.addVideo') }}
          </a-button>
        </div>

        <div class="table-container">
          <table class="data-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>{{ t('workflowVideo.thumbnail') }}</th>
                <th>{{ t('workflowVideo.videoTitle') }}</th>
                <th>{{ t('workflowVideo.tags') }}</th>
                <th>{{ t('workflowVideo.sortOrder') }}</th>
                <th>{{ t('workflowVideo.status') }}</th>
                <th>{{ t('workflowVideo.createdAt') }}</th>
                <th>{{ t('workflowVideo.operation') }}</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="video in videoList" :key="video.id" class="table-row">
                <td>{{ video.id }}</td>
                <td>
                  <img
                    v-if="video.thumbnailUrl"
                    :src="video.thumbnailUrl"
                    class="thumb-preview"
                    @click="previewVideo(video)"
                  />
                  <span v-else class="no-thumb">-</span>
                </td>
                <td>{{ video.title }}</td>
                <td>
                  <span class="tag" v-for="tag in parseTags(video.tags)" :key="tag">{{ tag }}</span>
                </td>
                <td>{{ video.sortOrder }}</td>
                <td>
                  <span class="status-tag" :class="video.isActive ? 'active' : 'inactive'">
                    {{ video.isActive ? t('workflowVideo.enabled') : t('workflowVideo.disabled') }}
                  </span>
                </td>
                <td>{{ formatDate(video.createdAt) }}</td>
                <td>
                  <a class="action-link" @click="editVideo(video)">{{ t('common.edit') }}</a>
                  <a class="action-link" @click="toggleActive(video)">
                    {{ video.isActive ? t('workflowVideo.disable') : t('workflowVideo.enable') }}
                  </a>
                  <a class="action-link danger" @click="handleDelete(video)">{{ t('common.delete') }}</a>
                </td>
              </tr>
              <tr v-if="videoList.length === 0">
                <td colspan="8" class="empty-cell">{{ t('workflowVideo.noVideos') }}</td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页 -->
        <div class="pagination-container" v-if="totalPages > 1">
          <div class="pagination">
            <span class="page-arrow" @click="prevPage" :class="{ disabled: currentPage === 0 }"><LeftOutlined /></span>
            <button
              v-for="page in visiblePageNumbers"
              :key="page"
              class="page-btn"
              :class="{ active: page === currentPage }"
              @click="goToPage(page)"
            >
              {{ page + 1 }}
            </button>
            <span class="page-arrow" @click="nextPage" :class="{ disabled: currentPage >= totalPages - 1 }"><RightOutlined /></span>
          </div>
        </div>
      </section>
    </main>

    <!-- 新增/编辑弹窗 -->
    <a-modal
      v-model:open="dialogVisible"
      :title="isEditing ? t('workflowVideo.editVideo') : t('workflowVideo.addVideo')"
      width="600px"
      @cancel="dialogVisible = false"
    >
      <a-form :model="form" layout="vertical">
        <a-form-item :label="t('workflowVideo.videoTitle')" required>
          <a-input v-model:value="form.title" :placeholder="t('workflowVideo.titlePlaceholder')" />
        </a-form-item>
        <a-form-item :label="t('workflowVideo.description')">
          <a-textarea v-model:value="form.description" :rows="3" :placeholder="t('workflowVideo.descriptionPlaceholder')" />
        </a-form-item>
        <a-form-item :label="t('workflowVideo.tags')">
          <a-input v-model:value="form.tags" :placeholder="t('workflowVideo.tagsPlaceholder')" />
        </a-form-item>
        <a-form-item :label="t('workflowVideo.sortOrder')">
          <a-input-number v-model:value="form.sortOrder" :min="0" :max="9999" />
        </a-form-item>
        <a-form-item :label="t('workflowVideo.enableStatus')">
          <a-switch v-model:checked="form.isActive" />
        </a-form-item>

        <!-- 上传视频 -->
        <a-form-item :label="t('workflowVideo.videoFile')">
          <div class="upload-area">
            <input type="file" accept="video/*" @change="handleVideoUpload" ref="videoInputRef" class="file-input" />
            <a-button :loading="uploadingVideo" @click="$refs.videoInputRef.click()">
              <UploadOutlined /> {{ t('workflowVideo.uploadVideo') }}
            </a-button>
            <span v-if="form.videoUrl" class="upload-status success">✓ {{ t('workflowVideo.uploaded') }}</span>
          </div>
          <div v-if="form.videoUrl" class="preview-url">{{ form.videoUrl }}</div>
        </a-form-item>

        <!-- 上传缩略图 -->
        <a-form-item :label="t('workflowVideo.thumbnailFile')">
          <div class="upload-area">
            <input type="file" accept="image/*" @change="handleThumbnailUpload" ref="thumbInputRef" class="file-input" />
            <a-button :loading="uploadingThumb" @click="$refs.thumbInputRef.click()">
              <UploadOutlined /> {{ t('workflowVideo.uploadThumbnail') }}
            </a-button>
            <span v-if="form.thumbnailUrl" class="upload-status success">✓ {{ t('workflowVideo.uploaded') }}</span>
          </div>
          <img v-if="form.thumbnailUrl" :src="form.thumbnailUrl" class="thumb-form-preview" />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button @click="dialogVisible = false">{{ t('common.cancel') }}</a-button>
        <a-button type="primary" @click="saveVideo" :loading="saving">{{ t('common.save') }}</a-button>
      </template>
    </a-modal>

    <!-- 视频预览弹窗 -->
    <a-modal
      v-model:open="previewVisible"
      :title="previewItem?.title"
      width="70%"
      :footer="null"
      :destroy-on-close="true"
    >
      <video
        v-if="previewItem"
        :src="previewItem.videoUrl"
        :poster="previewItem.thumbnailUrl"
        controls
        autoplay
        style="width: 100%; max-height: 70vh;"
      ></video>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { message, Modal } from 'ant-design-vue'
import {
  LeftOutlined,
  RightOutlined,
  PlusOutlined,
  UploadOutlined
} from '@ant-design/icons-vue'
import AdminSidebar from '@/components/AdminSidebar.vue'
import AdminHeader from '@/components/AdminHeader.vue'
import {
  getAdminWorkflowVideos,
  createWorkflowVideo,
  updateWorkflowVideo,
  deleteWorkflowVideo,
  uploadWorkflowVideoFile,
  uploadWorkflowThumbnail
} from '@/api/workflowVideo'

const { t } = useI18n()

// 列表数据
const videoList = ref([])
const currentPage = ref(0)
const pageSize = ref(20)
const totalElements = ref(0)

const totalPages = computed(() => Math.ceil(totalElements.value / pageSize.value))
const visiblePageNumbers = computed(() => {
  const pages = []
  const total = totalPages.value
  for (let i = 0; i < total && i < 10; i++) {
    pages.push(i)
  }
  return pages
})

// 弹窗状态
const dialogVisible = ref(false)
const isEditing = ref(false)
const editingId = ref(null)
const saving = ref(false)

const form = ref({
  title: '',
  description: '',
  tags: '',
  sortOrder: 0,
  isActive: true,
  videoUrl: '',
  thumbnailUrl: ''
})

// 上传状态
const uploadingVideo = ref(false)
const uploadingThumb = ref(false)
const videoInputRef = ref(null)
const thumbInputRef = ref(null)

// 预览
const previewVisible = ref(false)
const previewItem = ref(null)

// 加载数据
const loadVideos = async () => {
  try {
    const response = await getAdminWorkflowVideos(currentPage.value, pageSize.value)
    if (response?.data?.success) {
      videoList.value = response.data.data || []
      totalElements.value = response.data.totalElements || 0
    }
  } catch (error) {
    console.error('加载视频列表失败:', error)
    message.error(t('workflowVideo.loadFailed'))
  }
}

// 打开新增弹窗
const openCreateDialog = () => {
  isEditing.value = false
  editingId.value = null
  form.value = {
    title: '',
    description: '',
    tags: '',
    sortOrder: 0,
    isActive: true,
    videoUrl: '',
    thumbnailUrl: ''
  }
  dialogVisible.value = true
}

// 编辑
const editVideo = (video) => {
  isEditing.value = true
  editingId.value = video.id
  form.value = {
    title: video.title || '',
    description: video.description || '',
    tags: video.tags || '',
    sortOrder: video.sortOrder || 0,
    isActive: video.isActive !== false,
    videoUrl: video.videoUrl || '',
    thumbnailUrl: video.thumbnailUrl || ''
  }
  dialogVisible.value = true
}

// 保存
const saveVideo = async () => {
  if (!form.value.title?.trim()) {
    message.warning(t('workflowVideo.titleRequired'))
    return
  }
  if (!form.value.videoUrl) {
    message.warning(t('workflowVideo.videoRequired'))
    return
  }

  saving.value = true
  try {
    const data = { ...form.value }
    let response
    if (isEditing.value) {
      response = await updateWorkflowVideo(editingId.value, data)
    } else {
      response = await createWorkflowVideo(data)
    }

    if (response?.data?.success) {
      message.success(response.data.message || t('common.success'))
      dialogVisible.value = false
      await loadVideos()
    } else {
      message.error(response?.data?.message || t('common.error'))
    }
  } catch (error) {
    console.error('保存失败:', error)
    message.error(t('common.saveFailed'))
  } finally {
    saving.value = false
  }
}

// 切换启用状态
const toggleActive = async (video) => {
  try {
    const response = await updateWorkflowVideo(video.id, { isActive: !video.isActive })
    if (response?.data?.success) {
      message.success(t('common.success'))
      await loadVideos()
    }
  } catch (error) {
    message.error(t('common.updateFailed'))
  }
}

// 删除
const handleDelete = (video) => {
  Modal.confirm({
    title: t('common.confirmDeleteTitle'),
    content: `${t('workflowVideo.confirmDelete')} "${video.title}"?`,
    okText: t('common.delete'),
    cancelText: t('common.cancel'),
    okType: 'danger',
    onOk: async () => {
      try {
        const response = await deleteWorkflowVideo(video.id)
        if (response?.data?.success) {
          message.success(t('common.deleteSuccess'))
          await loadVideos()
        } else {
          message.error(response?.data?.message || t('common.deleteFailed'))
        }
      } catch (error) {
        message.error(t('common.deleteFailed'))
      }
    }
  })
}

// 上传视频
const handleVideoUpload = async (e) => {
  const file = e.target.files[0]
  if (!file) return
  uploadingVideo.value = true
  try {
    const response = await uploadWorkflowVideoFile(file)
    if (response?.data?.success) {
      form.value.videoUrl = response.data.url
      message.success(t('workflowVideo.uploadSuccess'))
    } else {
      message.error(response?.data?.message || t('workflowVideo.uploadFailed'))
    }
  } catch (error) {
    message.error(t('workflowVideo.uploadFailed'))
  } finally {
    uploadingVideo.value = false
    e.target.value = '' // 重置 input
  }
}

// 上传缩略图
const handleThumbnailUpload = async (e) => {
  const file = e.target.files[0]
  if (!file) return
  uploadingThumb.value = true
  try {
    const response = await uploadWorkflowThumbnail(file)
    if (response?.data?.success) {
      form.value.thumbnailUrl = response.data.url
      message.success(t('workflowVideo.uploadSuccess'))
    } else {
      message.error(response?.data?.message || t('workflowVideo.uploadFailed'))
    }
  } catch (error) {
    message.error(t('workflowVideo.uploadFailed'))
  } finally {
    uploadingThumb.value = false
    e.target.value = ''
  }
}

// 预览视频
const previewVideo = (video) => {
  previewItem.value = video
  previewVisible.value = true
}

// 工具函数
const parseTags = (tags) => {
  if (!tags) return []
  return tags.split(',').map(t => t.trim()).filter(t => t)
}

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 分页
const prevPage = () => {
  if (currentPage.value > 0) {
    currentPage.value--
    loadVideos()
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value - 1) {
    currentPage.value++
    loadVideos()
  }
}

const goToPage = (page) => {
  currentPage.value = page
  loadVideos()
}

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

<style scoped>
.admin-workflow-videos {
  display: flex;
  height: 100vh;
  width: 100vw;
  background: #07090F;
  color: #E2E8F0;
  font-family: var(--font-sans);
}

/* Main Content */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* Video Content */
.video-content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.content-header h2 {
  font-size: 18px;
  font-weight: 600;
  color: #E2E8F0;
  margin: 0;
}

/* Table */
.table-container {
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th {
  padding: 12px 16px;
  text-align: left;
  font-size: 12px;
  font-weight: 600;
  color: #94A3B8;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  border-bottom: 1px solid rgba(255,255,255,0.06);
  white-space: nowrap;
}

.data-table td {
  padding: 12px 16px;
  font-size: 13px;
  color: #CBD5E1;
  border-bottom: 1px solid rgba(255,255,255,0.04);
}

.table-row:hover {
  background: rgba(255,255,255,0.03);
}

.thumb-preview {
  width: 60px;
  height: 40px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  transition: transform 0.2s;
}

.thumb-preview:hover {
  transform: scale(1.1);
}

.no-thumb {
  color: #475569;
}

.tag {
  display: inline-block;
  padding: 2px 8px;
  background: rgba(99, 102, 241, 0.15);
  color: #818CF8;
  border-radius: 4px;
  font-size: 11px;
  margin-right: 4px;
  margin-bottom: 2px;
}

.status-tag {
  padding: 2px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-tag.active {
  background: rgba(16, 185, 129, 0.15);
  color: #10B981;
}

.status-tag.inactive {
  background: rgba(239, 68, 68, 0.15);
  color: #EF4444;
}

.action-link {
  color: #818CF8;
  cursor: pointer;
  font-size: 12px;
  margin-right: 12px;
  transition: color 0.2s;
}

.action-link:hover {
  color: #A5B4FC;
}

.action-link.danger {
  color: #EF4444;
}

.action-link.danger:hover {
  color: #F87171;
}

.empty-cell {
  text-align: center;
  color: #475569;
  padding: 40px !important;
}

/* Pagination */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

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

.page-arrow {
  padding: 6px 10px;
  cursor: pointer;
  color: #94A3B8;
  border-radius: 6px;
  transition: all 0.2s;
}

.page-arrow:hover:not(.disabled) {
  background: rgba(255,255,255,0.06);
  color: #E2E8F0;
}

.page-arrow.disabled {
  opacity: 0.3;
  cursor: not-allowed;
}

.page-btn {
  padding: 6px 12px;
  background: transparent;
  border: 1px solid rgba(255,255,255,0.1);
  color: #94A3B8;
  border-radius: 6px;
  cursor: pointer;
  font-size: 13px;
  transition: all 0.2s;
}

.page-btn:hover {
  background: rgba(255,255,255,0.06);
  color: #E2E8F0;
}

.page-btn.active {
  background: rgba(99, 102, 241, 0.2);
  border-color: #818CF8;
  color: #818CF8;
}

/* Form styles */
.upload-area {
  display: flex;
  align-items: center;
  gap: 12px;
}

.file-input {
  display: none;
}

.upload-status.success {
  color: #10B981;
  font-size: 13px;
}

.preview-url {
  margin-top: 6px;
  font-size: 11px;
  color: #64748B;
  word-break: break-all;
}

.thumb-form-preview {
  margin-top: 8px;
  max-width: 200px;
  max-height: 120px;
  object-fit: cover;
  border-radius: 8px;
  border: 1px solid rgba(255,255,255,0.1);
}

</style>
