import { ref } from 'vue'
import type { TreeNodeData } from '@arco-design/web-vue'
import { getDeptTree } from '@/apis/system/dept'

/** 部门模块 */
export function useDept(options?: { onSuccess?: () => void }) {
  const loading = ref(false)
  const deptList = ref<TreeNodeData[]>([])

  const getDeptList = async (deptName?: string) => {
    try {
      loading.value = true
      const res = await getDeptTree({ deptName })
      
      // 处理部门树数据，确保有title字段用于显示
      const processDeptData = (data: any[]): TreeNodeData[] => {
        if (!data || !data.length) return []
        
        return data.map(item => ({
          key: item.deptId,
          title: item.deptName || '未命名部门',  // 将deptName映射为title
          children: item.children ? processDeptData(item.children) : []
        }))
      }
      
      deptList.value = processDeptData(res.data || [])
      options?.onSuccess && options.onSuccess()
    } finally {
      loading.value = false
    }
  }
  return { deptList, getDeptList, loading }
}
