import parser from 'ua-parser-js'
import { useUserStore } from '@/stores/user'
import { getPageKey, setMetaInfo } from '@/api/log'

const userStore = useUserStore()

export function useLog(options?: { hasKey?: boolean }) {
  let key = ''
  // UA
  const userAgent = window.navigator.userAgent
  // 解析后的UA
  const parsedUserAgent = parser(userAgent)
  // 调用时间，一般是页面加载时间
  const startTime = Math.floor(Date.now() / 1000)

  // 获取Key
  const getKey = async () => {
    const res = await getPageKey()
    key = res.data.key
    return key
  }

  // 上送日志
  const upload = async (data: { event: string; action: string; data: Record<string, any> }) => {
    if (options?.hasKey && !key) {
      await getKey()
    }
    const OSName = parsedUserAgent.os.name || ''
    const defaultData = {
      key,
      sso_id: userStore.user?.id,
      open_browser_time: startTime,
      close_browser_time: Math.floor(Date.now() / 1000),
      device: ['iOS', 'Android'].includes(OSName) ? OSName : 'PC'
    }
    return setMetaInfo(Object.assign({}, data, { data: JSON.stringify(Object.assign(defaultData, data.data)) }))
  }

  return { userAgent, parsedUserAgent, key, upload, getKey }
}
