<template>
  <div class="space-y-6">
    <!-- 上传卡片 -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
      <div class="border-b border-gray-200 pb-4 mb-6">
        <h2 class="text-xl font-semibold text-gray-800 flex items-center gap-2">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-blue-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
          </svg>
          视频上传
        </h2>
      </div>

      <!-- 上传表单 -->
      <el-form ref="uploadFormRef" :model="uploadForm" :rules="uploadRules" label-width="120px">
        <el-form-item label="广告账户ID" prop="accountId">
          <el-input v-model.number="uploadForm.accountId" placeholder="请输入广告账户ID" />
        </el-form-item>

        <el-form-item label="视频文件" prop="file">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :limit="1"
            :on-change="handleFileChange"
            :on-exceed="handleExceed"
            :before-remove="handleBeforeRemove"
            accept=".mp4,.mov,.avi">
            <template #trigger>
              <el-button type="primary">选择视频文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                支持MP4、MOV、AVI格式，文件大小不超过100MB
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="是否添加水印">
          <el-switch v-model="uploadForm.hasWatermark" @change="handleWatermarkChange" />
        </el-form-item>

        <el-form-item v-if="uploadForm.hasWatermark" label="选择短剧" prop="dramaId">
          <el-select
            v-model="uploadForm.dramaId"
            filterable
            placeholder="请选择短剧"
            style="width: 100%"
            :loading="dramaLoading">
            <el-option
              v-for="item in dramaList"
              :key="item.id"
              :label="item.marketingAssetName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="uploadForm.hasWatermark" label="水印时长(秒)">
          <el-input-number
            v-model="uploadForm.watermarkDuration"
            :min="1"
            :max="3600"
            placeholder="不填则全程显示" />
          <span style="margin-left: 10px; color: #909399; font-size: 12px;">
            不填则水印全程显示
          </span>
        </el-form-item>

        <el-form-item label="视频描述">
          <el-input
            v-model="uploadForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入视频描述（可选）"
            maxlength="500"
            show-word-limit />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="uploading" @click="handleUpload">
            {{ uploading ? '上传中...' : '开始上传' }}
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 上传进度 -->
      <div v-if="uploading" class="mt-6">
        <div class="mb-2 text-sm text-gray-600">上传进度</div>
        <el-progress
          :percentage="uploadProgress"
          :status="uploadStatus"
          :show-text="true" />
      </div>
    </div>

    <!-- 视频列表 -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
      <div class="flex items-center justify-between mb-6 pb-4 border-b border-gray-200">
        <h2 class="text-xl font-semibold text-gray-800 flex items-center gap-2">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-green-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z" />
          </svg>
          视频列表
        </h2>
        <el-button type="primary" size="small" @click="loadVideoList">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
          </svg>
          刷新
        </el-button>
      </div>

      <!-- 筛选条件 -->
      <el-form :inline="true" style="margin-bottom: 20px;">
        <el-form-item label="账户ID">
          <el-input v-model.number="queryForm.accountId" placeholder="请输入账户ID" clearable />
        </el-form-item>
        <el-form-item label="上传状态">
          <el-select v-model="queryForm.uploadStatus" placeholder="请选择状态" clearable>
            <el-option label="成功" value="SUCCESS" />
            <el-option label="失败" value="FAILED" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table :data="videoList" border style="width: 100%" v-loading="tableLoading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="accountId" label="账户ID" width="120" />
        <el-table-column prop="originalFilename" label="文件名" width="200" show-overflow-tooltip />
        <el-table-column prop="videoId" label="视频ID" width="150" />
        <el-table-column prop="coverImageId" label="封面图片ID" width="150" />
        <el-table-column prop="videoDuration" label="时长(秒)" width="100" />
        <el-table-column label="是否水印" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.hasWatermark ? 'success' : 'info'" size="small">
              {{ scope.row.hasWatermark ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="watermarkText" label="水印文字" width="150" show-overflow-tooltip />
        <el-table-column prop="watermarkDuration" label="水印时长(秒)" width="120">
          <template #default="scope">
            {{ scope.row.watermarkDuration || '全程' }}
          </template>
        </el-table-column>
        <el-table-column label="上传状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.uploadStatus === 'SUCCESS' ? 'success' : 'danger'" size="small">
              {{ scope.row.uploadStatus === 'SUCCESS' ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="errorMessage" label="错误信息" min-width="200" show-overflow-tooltip />
        <el-table-column prop="createdTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="scope">
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-6 flex justify-end">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
</template>

<script setup>
defineOptions({
  name: 'Video'
})

import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { uploadVideo, getVideoList, deleteVideo } from '@/api/video'
import { getDramaList } from '@/api/drama'

// 上传表单
const uploadFormRef = ref(null)
const uploadRef = ref(null)
const uploadForm = reactive({
  accountId: null,
  file: null,
  hasWatermark: false,
  dramaId: null,
  watermarkDuration: null,
  description: ''
})

// 表单验证规则
const uploadRules = {
  accountId: [
    { required: true, message: '请输入广告账户ID', trigger: 'blur' },
    { type: 'number', message: '账户ID必须为数字', trigger: 'blur' }
  ],
  file: [
    { required: true, message: '请选择视频文件', trigger: 'change' }
  ],
  dramaId: [
    { required: true, message: '请选择短剧', trigger: 'change' }
  ]
}

// 上传状态
const uploading = ref(false)
const uploadProgress = ref(0)
const uploadStatus = ref('')

// 短剧列表
const dramaList = ref([])
const dramaLoading = ref(false)

// 查询表单
const queryForm = reactive({
  accountId: null,
  uploadStatus: null
})

// 视频列表
const videoList = ref([])
const tableLoading = ref(false)

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

// 加载短剧列表
const loadDramaList = async () => {
  dramaLoading.value = true
  try {
    const res = await getDramaList(1, 1000)
    if (res.success && res.data) {
      dramaList.value = res.data || []
    }
  } catch (error) {
    console.error('加载短剧列表失败', error)
  } finally {
    dramaLoading.value = false
  }
}

// 水印开关变化
const handleWatermarkChange = (value) => {
  if (value && dramaList.value.length === 0) {
    loadDramaList()
  }
  if (!value) {
    uploadForm.dramaId = null
    uploadForm.watermarkDuration = null
  }
}

// 文件选择
const handleFileChange = (file) => {
  uploadForm.file = file.raw
}

// 文件超出限制
const handleExceed = () => {
  ElMessage.warning('最多只能选择1个视频文件')
}

// 移除文件前
const handleBeforeRemove = () => {
  uploadForm.file = null
  return true
}

// 开始上传
// 100MB 文件大小限制
const MAX_FILE_SIZE = 100 * 1024 * 1024
const handleUpload = async () => {
  if (!uploadFormRef.value) return

  await uploadFormRef.value.validate(async (valid) => {
    if (!valid) return

    if (!uploadForm.file) {
      ElMessage.warning('请选择视频文件')
      return
    }
    
    if (uploadForm.file.size > MAX_FILE_SIZE) {
      ElMessage.warning('视频文件大小不能超过100MB')
      return
    }

    // 校验水印
    if (uploadForm.hasWatermark && !uploadForm.dramaId) {
      ElMessage.warning('添加水印时必须选择短剧')
      return
    }

    uploading.value = true
    uploadProgress.value = 0
    uploadStatus.value = ''

    try {
      // 构建FormData
      const formData = new FormData()
      formData.append('file', uploadForm.file)
      formData.append('accountId', uploadForm.accountId)
      formData.append('hasWatermark', uploadForm.hasWatermark)
      if (uploadForm.dramaId) {
        formData.append('dramaId', uploadForm.dramaId)
      }
      if (uploadForm.watermarkDuration) {
        formData.append('watermarkDuration', uploadForm.watermarkDuration)
      }
      if (uploadForm.description) {
        formData.append('description', uploadForm.description)
      }

      // 模拟进度
      const progressInterval = setInterval(() => {
        if (uploadProgress.value < 90) {
          uploadProgress.value += 10
        }
      }, 500)

      const res = await uploadVideo(formData)

      clearInterval(progressInterval)
      uploadProgress.value = 100
      uploadStatus.value = 'success'

      if (res.success) {
        ElMessage.success('视频上传成功')
        resetForm()
        loadVideoList()
      } else {
        ElMessage.error(res.message || '视频上传失败')
        uploadStatus.value = 'exception'
      }
    } catch (error) {
      console.error('上传失败', error)
      ElMessage.error('视频上传失败：' + (error.message || '未知错误'))
      uploadStatus.value = 'exception'
    } finally {
      uploading.value = false
      setTimeout(() => {
        uploadProgress.value = 0
        uploadStatus.value = ''
      }, 2000)
    }
  })
}

// 重置表单
const resetForm = () => {
  uploadFormRef.value?.resetFields()
  uploadRef.value?.clearFiles()
  uploadForm.file = null
  uploadForm.hasWatermark = false
  uploadForm.dramaId = null
  uploadForm.watermarkDuration = null
  uploadForm.description = ''
}

// 加载视频列表
const loadVideoList = async () => {
  tableLoading.value = true
  try {
    const res = await getVideoList(
      pagination.page,
      pagination.size,
      queryForm.accountId,
      queryForm.uploadStatus
    )
    if (res.success && res.data) {
      videoList.value = res.data.records || []
      pagination.total = res.data.total || 0
    }
  } catch (error) {
    console.error('加载视频列表失败', error)
    ElMessage.error('加载视频列表失败')
  } finally {
    tableLoading.value = false
  }
}

// 查询
const handleQuery = () => {
  pagination.page = 1
  loadVideoList()
}

// 重置查询
const handleResetQuery = () => {
  queryForm.accountId = null
  queryForm.uploadStatus = null
  handleQuery()
}

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.size = val
  loadVideoList()
}

// 页码变化
const handleCurrentChange = (val) => {
  pagination.page = val
  loadVideoList()
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除这条视频记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await deleteVideo(row.id)
    if (res.success) {
      ElMessage.success('删除成功')
      loadVideoList()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  })
}

// 页面加载时获取数据
onMounted(() => {
  loadVideoList()
})
</script>

<style scoped>
/* 使用Tailwind CSS类替代自定义样式 */
</style>
