import React from 'react'
import { useLocation } from 'react-router-dom'

import { Spin } from 'antd'

import { useLogin2p } from './Login2pContext'

const Login2pWechatLanding: React.FC = () => {
  const code = new URLSearchParams(useLocation().search).get('code')
  const next = new URLSearchParams(useLocation().search).get('next')
  console.log(next)
  const login2p = useLogin2p()
  React.useEffect(() => {
    // 创建 BroadcastChannel 实例

    const channel = new BroadcastChannel('myChannel')

    if (code) {
      if (login2p.isWechat) {
        login2p.loginWechat(code, decodeURIComponent(next ? next : '/')).then(r => console.log(r))
      } else {
        // 向广播通道发送消息
        channel.postMessage({ code, next })
        // 关闭频道
        channel.close()
        window.close()
      }

      // login2p.loginWechat(code, decodeURIComponent(next ? next : '/')).then(r => console.log(r))
    }
  }, [])

  return <Spin size="large" />
}

export default Login2pWechatLanding
