/**
 * 项目相关业务逻辑
 */
import { ref } from 'vue'
import { projectApi } from '@/api'
import type { Project, ProjectCreate } from '@/types'
import { ElMessage } from 'element-plus'

export function useProjects() {
  const loading = ref(false)
  const projects = ref<Project[]>([])

  /**
   * 获取项目列表
   */
  const fetchProjects = async () => {
    loading.value = true
    try {
      const res = await projectApi.list()
      // 处理两种响应格式
      if (Array.isArray(res)) {
        projects.value = res
      } else if (res?.data && Array.isArray(res.data)) {
        projects.value = res.data
      } else if (res?.results && Array.isArray(res.results)) {
        projects.value = res.results
      } else {
        projects.value = []
      }
    } catch (error: any) {
      console.error('获取项目列表失败:', error)
      ElMessage.error('获取项目列表失败')
      projects.value = []
    } finally {
      loading.value = false
    }
  }

  /**
   * 创建项目
   */
  const createProject = async (data: ProjectCreate): Promise<Project | null> => {
    try {
      const res = await projectApi.create(data)
      ElMessage.success('创建成功')
      await fetchProjects()
      return res
    } catch (error: any) {
      console.error('创建项目失败:', error)
      ElMessage.error(error?.message || '创建项目失败')
      return null
    }
  }

  /**
   * 删除项目
   */
  const deleteProject = async (id: number): Promise<boolean> => {
    try {
      await projectApi.delete(id)
      ElMessage.success('删除成功')
      await fetchProjects()
      return true
    } catch (error: any) {
      console.error('删除项目失败:', error)
      ElMessage.error(error?.message || '删除项目失败')
      return false
    }
  }

  /**
   * 获取项目详情
   */
  const fetchProject = async (id: number): Promise<Project | null> => {
    try {
      const res = await projectApi.get(id)
      if (res && typeof res === 'object' && 'id' in res) {
        return res as Project
      } else if (res?.data) {
        return res.data as Project
      }
      return null
    } catch (error: any) {
      console.error('获取项目详情失败:', error)
      ElMessage.error('获取项目详情失败')
      return null
    }
  }

  return {
    loading,
    projects,
    fetchProjects,
    createProject,
    deleteProject,
    fetchProject
  }
}
