import { useEffect, useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { getUser, getMapList, getMyList, getMyField, getProcessProgress } 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
}

// 读取excel文件
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: [] }
    },
  })
  const fields =
    query.data?.map((item) => {
      return { ...item, label: item.name, value: item.english_name }
    }) || []

  const getFieldName = (value: string) => {
    return fields.find((item) => item.value === value)?.label || value
  }

  const getFieldNames = (values: string[]) => {
    return values.map((value) => getFieldName(value))
  }

  return { ...query, fields, fieldOptions: fields, getFieldName, getFieldNames }
}

// 进度查询
export function useProcessProgressQuery(params: { function_name: string }) {
  const queryClient = useQueryClient()
  const [enabled, setEnabled] = useState(false)

  const query = useQuery({
    queryKey: ['processProgress', params],
    queryFn: () => {
      return getProcessProgress(params)
    },
    select: (res) => res.data,
    enabled,
    refetchInterval: enabled ? 500 : false,
    staleTime: 0,
    gcTime: 0,
    placeholderData: (): any => {
      return { data: { progress: -1, message: {} } }
    },
  })

  const remove = () => {
    queryClient.removeQueries({ queryKey: ['processProgress', params] })
  }

  // 开始轮询的方法
  const start = () => {
    setEnabled(true)
  }

  // 结束轮询的方法
  const stop = () => {
    setEnabled(false)
  }
  // 组件卸载时清理
  useEffect(() => {
    if (query.data?.result === 'SUCCESS' || query.data?.result === 'FAIL') {
      stop()
    }
    return () => {
      stop()
    }
  }, [query.data, enabled])

  return { ...query, start, stop, remove }
}
