<template>
  <el-dialog 
    :title="form.id ? '编辑文件夹' : '新建文件夹'" 
    v-model="visible" 
    :width="500" 
    :close-on-click-modal="false" 
    draggable>
    <el-form 
      ref="dataFormRef" 
      :model="form" 
      :rules="dataRules" 
      label-width="100px" 
      v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="24" class="mb20">
          <el-form-item label="文件夹名称" prop="classification">
            <el-input
              v-model="form.classification"
              placeholder="请输入文件夹名称"
              style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">确 认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="FileManagerFolderDialog">
import { ref, reactive, nextTick } from 'vue'
import { useMessage } from '/@/hooks/message'
import { editFile, getDetail } from '/@/api/stuwork/filemanager'

const emit = defineEmits(['refresh'])

// 定义变量内容
const dataFormRef = ref()
const visible = ref(false)
const loading = ref(false)
const operType = ref('add') // add 或 edit

// 提交表单数据
const form = reactive({
  id: '',
  classification: '',
  parentId: null as string | null
})

// 定义校验规则
const dataRules = {
  classification: [
    { required: true, message: '请输入文件夹名称', trigger: 'blur' }
  ]
}

// 打开弹窗
const openDialog = async (type: string = 'add', row?: any) => {
  visible.value = true
  operType.value = type
  
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields()
    form.id = ''
    form.classification = ''
    form.parentId = row?.parentId ?? null
    
    // 编辑时填充数据
    if (type === 'edit' && row) {
      form.id = row.id
      form.classification = row.classification || ''
      form.parentId = row.parentId || null
      
      // 如果需要获取详情
      if (row.id && !row.classification) {
        loading.value = true
        getDetail(row.id).then((res: any) => {
          if (res.data) {
            form.classification = res.data.classification || ''
            form.parentId = res.data.parentId || form.parentId
          }
        }).finally(() => {
          loading.value = false
        })
      }
    }
  })
}

// 提交表单（新增文件夹需要通过新增文件接口，但只传 classification 和 parentId）
const onSubmit = async () => {
  if (!dataFormRef.value) return
  
  await dataFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    loading.value = true
    try {
      if (operType.value === 'add') {
        // 新增文件夹：使用 addObj，但只传 classification 和 parentId
        const { addObj } = await import('/@/api/stuwork/filemanager')
        await addObj({
          classification: form.classification,
          parentId: form.parentId || '-1',
          level: '0' // 文件夹层级为 0
        })
        useMessage().success('新建成功')
      } else {
        // 编辑文件夹：使用 editFile 接口
        await editFile({
          id: form.id,
          parentId: form.parentId || '-1',
          classification: form.classification
        })
        useMessage().success('编辑成功')
      }
      visible.value = false
      emit('refresh')
    } catch (err: any) {
      if (!err?._messageShown) {
        useMessage().error(err?.msg || (operType.value === 'add' ? '新建失败' : '编辑失败'))
      }
    } finally {
      loading.value = false
    }
  })
}

// 暴露方法
defineExpose({
  openDialog
})
</script>

<style scoped lang="scss">
.mb20 {
  margin-bottom: 20px;
}
</style>
