import { RouterProvider } from 'react-router-dom'
import { useEffect } from 'react'
import router from '@/router'
import { cacheClear, cacheSet } from '@/utils/cacheUtil'
import { getAgentBaseInfo, getUserInfoById } from '@/api/common'

function App() {
  const queryString = window.location.search
  const searchParams = new URLSearchParams(queryString)
  const tenantId = searchParams.get('tenantId') || ''
  const token = searchParams.get('token') || ''

  cacheSet('tenantId', tenantId)
  cacheSet('token', token)
  useEffect(() => {
    const agentId = searchParams.get('agentId') || ''
    
    if (agentId) {
      getAgentBaseInfo({ id: agentId }).then(res => {
        cacheSet('appKey', res.data.appKey)
      })
    }
  }, [])

  useEffect(() => {
    if (tenantId && token) {
      getUserInfoById().then(response => {
        if (response.code === 200 && response.data) {
          cacheSet('userInfo', JSON.stringify(response.data))
        }
      })
    }
    return () => {
      cacheClear('userInfo')
    }
  }, [])
  return (
    <>
      <RouterProvider router={router} />
    </>
  )
}

export default App
