<template>
  <el-dialog
    :model-value="visible"
    title="移动文件"
    width="400px"
    @close="handleClose"
    @update:model-value="handleClose"
  >
    <el-form>
      <el-form-item label="目标分组">
        <el-select
          v-model="targetCate"
          placeholder="请选择分组"
          style="width: 100%"
          @change="handleCateChange"
        >
          <el-option
            v-for="cate in filteredCateList"
            :key="cate.id"
            :label="cate.name"
            :value="cate.id"
            :disabled="cate.id === props.currentCateId"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleMove">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { moveFile } from '@/api/file'

interface Cate {
  id: number
  name: string
}

// Props
const props = defineProps<{
  visible: boolean
  fileId: number | null
  currentCateId?: number | null
  cateList: Cate[]
}>()

// Emits
const emit = defineEmits(['update:visible', 'moved'])

// Data
const targetCate = ref<number | null>(null)
const loading = ref(false)

// 未分类分组
const uncategorizedOption: Cate = {
  id: 0,
  name: '未分类'
}

// 计算属性：添加未分类选项，并标记当前分组为禁用
const filteredCateList = computed(() => {
  const list = [uncategorizedOption, ...(props.cateList || [])]
  return list
})

// 重置
watch(
  () => props.visible,
  (val) => {
    if (val) {
      targetCate.value = null
    }
  }
)

// 关闭对话框
function handleClose() {
  emit('update:visible', false)
  targetCate.value = null
}

// 选择分组
function handleCateChange(value: number) {
  targetCate.value = value
}

// 移动文件
async function handleMove() {
  // 校验文件ID和目标分组ID的有效性
  if (!props.fileId) {
    ElMessage.error('请选择要移动的文件')
    return
  }
  
  // 修复：0 是有效的分组ID（未分类），需要检查 null 或 undefined
  if (targetCate.value === null || targetCate.value === undefined) {
    ElMessage.error('请选择目标分组')
    return
  }

  loading.value = true
  try {
    const res = await moveFile(props.fileId, targetCate.value)
    
    if (res && res.code === 200) {
      ElMessage.success('文件移动成功')
      handleClose() // 先关闭对话框
      emit('moved') // 然后触发移动成功事件，刷新列表
    } else {
      ElMessage.error(res?.msg || '文件移动失败')
    }
  } catch (error: any) {
    console.error('移动文件失败:', error)
    ElMessage.error(error?.message || '文件移动失败，请稍后重试')
  } finally {
    loading.value = false
  }
}
</script>
