import React, { useCallback, useEffect, useState } from 'react'
import styles from './index.module.scss'
import { Button } from 'antd'
import { API_login, isTokenFlagAPI } from '@/store/action/A1List'
import { MessageFu } from '@/utils/message'
import { setTokenInfo } from '@/utils/storage'
import history from '@/utils/history'
import { isLocal } from '@/utils/http'
function Login() {
  const loginFu = useCallback(() => {
    window.location.href = `https://dev.itfinspread.com:8003/#/sso?redirectUrl=${backUrl}`
  }, [])

  const [code, setCode] = useState('')

  const getUserInfo = useCallback(async (code: string) => {
    setCode(code)
    try {
      const res = await API_login({ code, redirectUrl: backUrl })
      if (res.code === 0) {
        if (res.data.token) {
          MessageFu.success('登录成功')
          // 用户信息存到本地
          setTokenInfo(res.data)
          window.location.href = `${isLocal ? '' : '/backstage'}/#/list`
        } else {
          MessageFu.warning('token为空')
          setCode('')
        }
      } else setCode('')
    } catch (error) {
      setCode('')
    }
  }, [])

  const checkTokenFu = useCallback(async () => {
    // 检查token有效直接跳list页面
    const res = await isTokenFlagAPI()
    if (res.code === 0) {
      if (res.data) {
        history.replace('/list')
      }
    }
  }, [])

  useEffect(() => {
    // 创建 URLSearchParams 对象解析查询字符串
    const searchParams = new URLSearchParams(window.location.search)
    const code = searchParams.get('code') // 获取 code 参数
    if (code) {
      getUserInfo(code)
    } else {
      checkTokenFu()
    }
  }, [checkTokenFu, getUserInfo])

  return (
    <div className={styles.Login}>
      <div className='LoginBtn'>
        <Button type='primary' size='large' onClick={loginFu} hidden={!!code}>
          孪生数字底座平台授权登录
        </Button>
      </div>

      {/* 获取用户信息加载中 */}
      <div className='codeLoding' hidden={!code}>
        授权中，请稍后...
      </div>
    </div>
  )
}

const MemoLogin = React.memo(Login)

export default MemoLogin
