import React, { useCallback, useEffect, useRef, useState } from 'react'
import dd from 'gdt-jsapi'
import styles from './index.module.scss'
import { MessageFu } from '@/utils/message'
import { API_ddLogin } from '@/store/action/layout'
import { Button } from 'antd'
import { setTokenInfo } from '@/utils/storage'
import history from '@/utils/history'
function DingLogin() {
  const DDloginFu = useCallback(() => {
    dd.ready(function () {
      dd.getAuthCode({
        corpId: ''
      })
        .then(async res1 => {
          const code = res1.auth_code
          const res = await API_ddLogin(code!)
          if (res.code === 0) {
            MessageFu.success('登录成功')
            // 用户信息存到本地
            setTokenInfo(res.data)
            const urlAll = window.location.href
            if (urlAll.includes('?back=')) {
              const url = urlAll.split('?back=')[1]
              if (url) history.push(`/${url}`)
              else history.push('/')
            } else history.push('/')
          }
        })
        .catch(err => {
          MessageFu.error(err)
        })
    })
  }, [])

  const [num, setNum] = useState(10)
  const numRef = useRef(10)

  useEffect(() => {
    numRef.current = num
    if (num <= 0) {
      clearInterval(time.current)
      DDloginFu()
    }
  }, [DDloginFu, num])

  const time = useRef(-1)

  useEffect(() => {
    time.current = window.setInterval(() => {
      setNum(numRef.current - 1)
    }, 1000)

    return () => {
      clearInterval(time.current)
    }
  }, [])

  return (
    <div className={styles.DingLogin}>
      <div className='DingLoginBox'>
        <Button type='primary' size='large' onClick={() => setNum(0)}>
          钉钉授权登录
        </Button>
        <h3 style={{ opacity: num <= 0 ? '0' : '1' }}>
          <span>{num}</span>秒之后自动登录
        </h3>
      </div>
    </div>
  )
}

const MemoDingLogin = React.memo(DingLogin)

export default MemoDingLogin
