"use client"

import { useAppLayoutStore } from "@/components/layout/store"
// import { useLoginStore } from "../login/store"
import { usePathname, useSearchParams } from "next/navigation"
import { useEffect, useMemo } from "react"
import { MenuItem } from "./common"
interface ComponentProps {
  menu: MenuItem[] | undefined
}

export function PathnameRecorder({ menu }: ComponentProps) {
  const pathname = usePathname()

  //   const { setFingerprint } = useLoginStore()

  //   useEffect(() => {
  //     if (pathname.startsWith("/login")) {
  //       return
  //     }
  //     setFingerprint("")
  //   }, [pathname, setFingerprint])

  const searchParams = useSearchParams() // 查询参数

  const queryParams = Array.from(searchParams.entries()).reduce(
    (acc, [key, value]) => {
      acc[key] = value // 或者 acc[key] = value.split(',') 如果值是数组
      return acc
    },
    {} as Record<string, string>
  )

  // 将查询参数对象转换为查询字符串
  const queryString = new URLSearchParams(queryParams).toString()

  const sideNavMenu = useMemo(() => {
    return menu?.find((item) => pathname.startsWith(`/${item.url}`))
  }, [menu, pathname])

  const { updateMenuDefaultRouter } = useAppLayoutStore()
  useEffect(() => {
    pathname.startsWith(`/${sideNavMenu?.url}`) &&
      sideNavMenu?.url &&
      `/${sideNavMenu?.url}` !== pathname &&
      updateMenuDefaultRouter(
        `/${sideNavMenu?.url}`,
        queryString
          ? `${process.env.NEXT_PUBLIC_BASE_PATH}${pathname}?${queryString}`
          : `${process.env.NEXT_PUBLIC_BASE_PATH}${pathname}`
      )
  }, [queryString, pathname, sideNavMenu?.url, updateMenuDefaultRouter])
  return <></>
}
