import React, { useEffect } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { clearCurrentConversation, setCurrentConversation } from '@/store/conversationSlice'
import { clearCurrentTacticsConversation, setCurrentTacticsConversation } from '@/store/tacticsSlice'
import { useAppDispatch, useAppSelector } from '@/store/hook'
import { setIsAsking } from '@/store/chatSlice'
import type { RootState } from '@/store'

export function withRouteChangeHandler(WrappedComponent: React.ComponentType) {
  let beforeLocationPathName = ''
  return (props: any) => {
    const isAsking = useAppSelector((state: RootState) => state.chat.isAsking)
    const location = useLocation()
    const dispatch = useAppDispatch()
    const navigate = useNavigate()

    const newPath = location.pathname
    const oldPath = beforeLocationPathName

    useEffect(() => {
      // 处理 /home?from=tactics 重定向到 /tactics
      if (location.pathname === '/home') {
        const searchParams = new URLSearchParams(location.search)
        const from = searchParams.get('from')
         // 获取place参数值
        const place = searchParams.get('place')
        if (from === 'tactics') {
          // 在重定向前缓存查询参数，供 /tactics 页读取（避免 from 被清理导致丢失）
          try {
            if (place) {
const userMeta = {
               cstId: searchParams.get('cstId') ?? undefined,
               userId: searchParams.get('userId') ?? undefined,
               numberType: searchParams.get('numberType') ?? undefined,
               place,
               busiType: '02',
               busiId: searchParams.get('userId') ?? undefined,
             }
              sessionStorage.setItem('userMeta', JSON.stringify(userMeta))
            }
            else {
              const meta = {
                version: searchParams.get('version') || undefined,
                taskId: searchParams.get('taskId') || undefined,
                pinBeginTime: searchParams.get('pinBeginTime') || undefined,
                pinEndTime: searchParams.get('pinEndTime') || undefined,
                partOrAll: searchParams.get('partOrAll') || undefined,
                channel: searchParams.get('channel') || undefined,
                channelName: searchParams.get('channelName') || undefined,
                from,
                busiType: '02',
                busiId: searchParams.get('taskId') || undefined,
              }
              sessionStorage.setItem('tacticsMeta', JSON.stringify(meta))
            }
          }
          catch {
            // ignore
          }
          // 重定向到 /tactics，保留其他查询参数
          const newSearchParams = new URLSearchParams(location.search)
          newSearchParams.delete('from')
          const newSearch = newSearchParams.toString()
          navigate(`/tactics${newSearch ? `?${newSearch}` : ''}`, { replace: true })
          return
        }
      }

      if (isAsking && newPath !== oldPath && oldPath !== '') {
        dispatch(setIsAsking(false))
      }

      if (location.pathname === '/') {
        dispatch(clearCurrentConversation())
      }
      else if (location.pathname.startsWith('/chat/')) {
        const conversationId = location.pathname.split('/')[2]

        const tokenStr = window.localStorage.getItem('__TOKEN__') || '""'
        let token = ''
        try {
          token = JSON.parse(tokenStr)
        }
        catch {
          // 如果解析失败，说明没有有效的 token
          navigate('/')
          return // 提前返回，不执行后续的 dispatch
        }

        if (!token) {
          // 如果没有有效的 token，重定向到首页
          navigate('/')
          return // 提前返回，不执行后续的 dispatch
        }

        dispatch(setCurrentConversation(conversationId))
      }
      // 处理问答功能的聊天路由
      else if (location.pathname.startsWith('/tactics/chat/')) {
        const conversationId = location.pathname.split('/')[3]

        const tokenStr = window.localStorage.getItem('__TOKEN__') || '""'
        let token = ''
        try {
          token = JSON.parse(tokenStr)
        }
        catch {
          navigate('/tactics')
          return
        }

        if (!token) {
          navigate('/tactics')
          return
        }

        dispatch(setCurrentTacticsConversation(conversationId))
      }
      else if (location.pathname === '/tactics') {
        dispatch(clearCurrentTacticsConversation())
      }
      // 这里可以添加其他路由相关的逻辑
      beforeLocationPathName = newPath
    }, [location, dispatch, navigate])

    return <WrappedComponent {...props} />
  }
}
