<template>
  <div class="video-tab">
    <h2>视频拼接</h2>
    
    <div class="form-group">
      <label>选择文件夹：</label>
      <div class="input-group">
        <input 
          type="text" 
          v-model="folderPath" 
          placeholder="请选择包含视频文件夹的目录"
          readonly
        />
        <button @click="selectFolder">选择文件夹</button>
      </div>
    </div>

    <div class="form-group" v-if="folderInfos.length > 0">
      <label>文件夹列表：</label>
      <div class="folder-list">
        <div v-for="(folder, index) in folderInfos" :key="index" class="folder-item">
          <span>{{ folder.name }}</span>
          <span class="video-count">{{ folder.videoCount }} 个视频</span>
        </div>
      </div>
    </div>

    <div class="form-group">
      <label>拼接模式：</label>
      <div class="radio-group">
        <label>
          <input type="radio" v-model="joinType" :value="1" />
          组合拼接（从每个文件夹随机选择）
        </label>
        <label>
          <input type="radio" v-model="joinType" :value="2" />
          顺序拼接（按索引顺序）
        </label>
      </div>
    </div>

    <div class="form-group">
      <label>生成数量：</label>
      <input 
        type="number" 
        v-model.number="num" 
        :min="1" 
        :max="maxNum"
        :disabled="isProcessing"
      />
      <span class="hint">最大可生成：{{ maxNum }} 个</span>
    </div>

    <div class="form-group">
      <label>审核图片（可选）：</label>
      <div class="input-group">
        <input 
          type="text" 
          v-model="auditImagePath" 
          placeholder="选择审核图片"
          readonly
        />
        <button @click="selectAuditImage">选择图片</button>
      </div>
    </div>

    <div class="form-group">
      <button 
        class="btn-primary" 
        @click="startConcat"
        :disabled="!canStart || isProcessing"
      >
        {{ isProcessing ? '处理中...' : '开始拼接' }}
      </button>
    </div>

    <div v-if="concatResults.length > 0" class="results">
      <h3>拼接结果</h3>
      <table>
        <thead>
          <tr>
            <th>序号</th>
            <th>文件名</th>
            <th>大小</th>
            <th>时长</th>
            <th>状态</th>
            <th>进度</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="result in concatResults" :key="result.index">
            <td>{{ result.index }}</td>
            <td>{{ result.fileName }}</td>
            <td>{{ result.size }}</td>
            <td>{{ result.seconds }}秒</td>
            <td :class="result.status === '拼接成功' ? 'success' : 'error'">
              {{ result.status }}
            </td>
            <td>
              <div class="progress-bar">
                <div 
                  class="progress-fill" 
                  :style="{ width: result.progress }"
                ></div>
                <span class="progress-text">{{ result.progress }}</span>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { VideoService, FileService } from '../../bindings/videoconcat/services/index.js'

const folderPath = ref('')
const folderInfos = ref([])
const joinType = ref(1)
const num = ref(1)
const maxNum = ref(0)
const auditImagePath = ref('')
const isProcessing = ref(false)
const concatResults = ref([])

const canStart = computed(() => {
  return folderPath.value && num.value > 0 && num.value <= maxNum.value && !isProcessing.value
})

const selectFolder = async () => {
  try {
    // 调用后端选择文件夹对话框
    const selectedPath = await FileService.SelectFolder()
    if (selectedPath && selectedPath.trim()) {
      folderPath.value = selectedPath.trim()
      
      // 调用后端列出文件夹
      try {
        folderInfos.value = await VideoService.ListFolders(folderPath.value)
        updateMaxNum()
      } catch (error) {
        alert('列出文件夹失败: ' + error.message)
      }
    }
  } catch (error) {
    console.error('选择文件夹失败:', error)
    alert('选择文件夹失败: ' + (error.message || '未知错误'))
  }
}

const selectAuditImage = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  input.onchange = (e) => {
    const file = e.target.files[0]
    if (file) {
      auditImagePath.value = file.name
    }
  }
  input.click()
}

const updateMaxNum = () => {
  if (joinType.value === 1) {
    // 组合拼接：所有文件夹视频数量的乘积
    maxNum.value = folderInfos.value.reduce((acc, folder) => acc * folder.videoCount, 1)
  } else {
    // 顺序拼接：第一个文件夹的视频数量
    maxNum.value = folderInfos.value.length > 0 ? folderInfos.value[0].videoCount : 0
  }
}

const startConcat = async () => {
  if (!canStart.value) return

  isProcessing.value = true
  concatResults.value = []

  try {
    const request = {
      folderPath: folderPath.value,
      num: num.value,
      joinType: joinType.value,
      auditImagePath: auditImagePath.value,
      folderInfos: folderInfos.value
    }

    // 调用后端拼接视频
    try {
      const results = await VideoService.JoinVideos(request)
      if (results) {
        concatResults.value = results
      }
    } catch (error) {
      alert('拼接视频失败: ' + error.message)
    }
  } catch (error) {
    alert('拼接失败: ' + error.message)
  } finally {
    isProcessing.value = false
  }
}
</script>

<style scoped>
.video-tab {
  max-width: 900px;
  margin: 0 auto;
}

h2 {
  margin-bottom: 20px;
  color: #333;
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #555;
}

.input-group {
  display: flex;
  gap: 10px;
}

.input-group input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.input-group button {
  padding: 8px 16px;
  background: #7163ba;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.input-group button:hover {
  background: #5a5080;
}

.radio-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.radio-group label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: normal;
}

input[type="number"] {
  width: 100px;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.hint {
  margin-left: 10px;
  color: #888;
  font-size: 14px;
}

.btn-primary {
  padding: 12px 24px;
  background: #7163ba;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.btn-primary:hover:not(:disabled) {
  background: #5a5080;
}

.btn-primary:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.folder-list {
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 10px;
  max-height: 200px;
  overflow-y: auto;
}

.folder-item {
  display: flex;
  justify-content: space-between;
  padding: 8px;
  border-bottom: 1px solid #eee;
}

.folder-item:last-child {
  border-bottom: none;
}

.video-count {
  color: #888;
  font-size: 14px;
}

.results {
  margin-top: 30px;
}

.results h3 {
  margin-bottom: 15px;
}

table {
  width: 100%;
  border-collapse: collapse;
  background: white;
  border-radius: 4px;
  overflow: hidden;
}

thead {
  background: #7163ba;
  color: white;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.success {
  color: #28a745;
}

.error {
  color: #dc3545;
}

.progress-bar {
  position: relative;
  width: 100px;
  height: 20px;
  background: #eee;
  border-radius: 10px;
  overflow: hidden;
}

.progress-fill {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  background: #28a745;
  transition: width 0.3s;
}

.progress-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 12px;
  z-index: 1;
}
</style>

