﻿<template>
  <el-dialog
    v-model="visible"
    title="批量移动"
    width="500px"
    :close-on-click-modal="false"
  >
    <div class="form-item">
      <span class="label">目标目录</span>
      <el-tree-select
        v-model="targetFolderId"
        :data="folderTreeData"
        :props="treeProps"
        placeholder="请选择目标目录"
        clearable
        check-strictly
        :render-after-expand="false"
        style="flex: 1"
        node-key="id"
      />
    </div>
    <template #footer>
      <el-button @click="visible = false">
        <el-icon><Close /></el-icon>
        <span style="margin-left: 4px">取消</span>
      </el-button>
      <el-button type="primary" @click="handleConfirm">
        <el-icon><FolderOpened /></el-icon>
        <span style="margin-left: 4px">移动</span>
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { Close, FolderOpened } from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  folders: { type: Array, default: () => [] },
  canGoParent: { type: Boolean, default: false },
  parentFolderName: { type: String, default: '返回上一级' }
})

const emit = defineEmits(['update:modelValue', 'confirm'])

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const targetFolderId = ref(0)

// 树形配置
const treeProps = {
  label: 'name',
  children: 'children',
  value: 'id'
}

// 转换目录数据为树形结构
const folderTreeData = computed(() => {
  // 根节点
  const rootNodes = [
    {
      id: 0,
      name: '根目录',
      children: []
    }
  ]
  
  // 递归转换后端返回的树形数据
  const convertFolderTree = (folders) => {
    if (!folders || folders.length === 0) return []
    
    return folders.map(folder => ({
      id: folder.id,
      name: folder.name,
      children: folder.children && folder.children.length > 0 
        ? convertFolderTree(folder.children) 
        : undefined
    }))
  }
  
  // 将后端返回的目录树挂载到根目录下
  rootNodes[0].children = convertFolderTree(props.folders)
  
  return rootNodes
})

const handleConfirm = () => {
  // targetFolderId = 0 表示根目录，null 表示未选择
  emit('confirm', targetFolderId.value)
  visible.value = false
  targetFolderId.value = 0
}

const open = () => {
  targetFolderId.value = 0
  visible.value = true
}

// 重置选中状态
watch(visible, (val) => {
  if (!val) {
    targetFolderId.value = 0
  }
})

defineExpose({ open })
</script>

<style scoped>
.form-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.label {
  flex-shrink: 0;
  width: 80px;
  font-size: 14px;
  color: #606266;
}
</style>
