import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { createChartComponent, updateChartComponent, deleteChartComponent, getChartComponent } from '@/api/data'
import { message } from 'antd'

// 创建
export function useCreateChart() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (data: { name: string; type: string; content: string }) => createChartComponent(data),
    onSuccess: () => {
      message.success('创建成功')
      queryClient.invalidateQueries({ queryKey: ['chartComponentList'] })
    },
  })
}

// 编辑
export function useUpdateChart() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (data: { id: string; name: string; type: string; content: string }) => updateChartComponent(data),
    onSuccess: () => {
      message.success('编辑成功')
      queryClient.invalidateQueries({ queryKey: ['chartComponentList'] })
    },
  })
}

// 删除
export function useDeleteChart() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (data: { id: string }) => deleteChartComponent(data),
    onSuccess: () => {
      message.success('删除成功')
      queryClient.invalidateQueries({ queryKey: ['chartComponentList'] })
    },
  })
}

// 查看
export function useViewChartQuery(id: string) {
  return useQuery({
    queryKey: ['chartComponent', id],
    queryFn: () => {
      return getChartComponent({ id })
    },
    select: (res) => res.data,
    enabled: !!id,
    staleTime: 0,
  })
}
