import { useEffect } from 'react'
import { useQuery } from '@tanstack/react-query'
import { getUser, getMapList, getMyList, getMyField } from '@/api/base'
import { useUserStore } from '@/stores/user'
import { useMapStore } from '@/stores/map'
import axios from 'axios'
import { read, utils } from 'xlsx'

export function useUserQuery() {
  const { setUser } = useUserStore()

  const query = useQuery({ queryKey: ['user'], queryFn: getUser, select: (res) => res.data })

  useEffect(() => {
    if (query.data) {
      setUser(query.data)
    }
  }, [query.data, setUser])

  return query
}

export function useMapQuery() {
  const { setMap } = useMapStore()

  const query = useQuery({ queryKey: ['dictionary'], queryFn: getMapList, select: (res) => res.data })

  useEffect(() => {
    if (query.data) {
      setMap(query.data)
    }
  }, [query.data, setMap])

  return query
}

// 我的数据集
export function useDataQuery() {
  const query = useQuery({
    queryKey: ['data'],
    queryFn: () => {
      return getMyList({ page: 1, 'per-page': 1000 })
    },
    select: (res) => res.data,
    placeholderData: (): any => {
      return { data: { total: 0, list: [], title: [] } }
    },
  })
  const file = query.data.info?.source || {}

  useExcelQuery(file.url)

  return query
}

export function useExcelQuery(url: string) {
  const query = useQuery({
    queryKey: ['excel', url],
    queryFn: () => {
      return axios(url, { responseType: 'arraybuffer' })
    },
    select: (res) => res.data,
    enabled: !!url,
  })

  useEffect(() => {
    if (query.data) {
      const workbook = read(query.data)
      const sheetName = workbook.SheetNames[0]
      const worksheet = workbook.Sheets[sheetName]
      const jsonData = utils.sheet_to_json(worksheet, { defval: '' })
      localStorage.setItem('dataset', JSON.stringify(jsonData))
    }
  }, [query.data])
}

interface DataField {
  name: string
  english_name: string
  type: string
}

export function useDataFieldQuery() {
  const query = useQuery({
    queryKey: ['dataFiled'],
    queryFn: getMyField,
    select: (res): DataField[] => res.data,
    placeholderData: (): any => {
      return { data: [] }
    },
  })

  return query
}
