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 { domShowFu } from '@/utils/domShow'
import { API_ddLogin } from '@/store/action/layout'
import { setTokenInfo } from '@/utils/storage'
import history from '@/utils/history'
function DingLogin() {
  const [txt, setTxt] = useState('正在授权登录中...')

  let time = useRef(-1)
  const succFu = useCallback((val: string, code?: string) => {
    clearTimeout(time.current)
    time.current = window.setTimeout(async () => {
      domShowFu('#AsyncSpinLoding', false)
      if (val === '成功') {
        const res = await API_ddLogin(code!)
        if (res.code === 0) {
          MessageFu.success('登录成功')
          // 用户信息存到本地
          setTokenInfo(res.data)
          history.push('/')
        }
      }
    }, 500)
  }, [])

  useEffect(() => {
    domShowFu('#AsyncSpinLoding', true)
    dd.ready(function () {
      dd.getAuthCode({
        corpId: ''
      })
        .then(res => {
          succFu('成功', res.auth_code)
        })
        .catch(err => {
          succFu('失败')
          setTxt(err)
          MessageFu.error(err)
        })
    })
  }, [succFu])

  return (
    <div className={styles.DingLogin}>
      <div className='DingLoginBox'>
        <h2>{txt}</h2>
      </div>
    </div>
  )
}

const MemoDingLogin = React.memo(DingLogin)

export default MemoDingLogin
