import useAuthStore from '@/stores/AuthStore'
import { Flex, Result, Spin, Typography } from 'antd'
import { useEffect } from 'react'
import { useNavigate } from 'react-router-dom'

const { Title } = Typography

// 钉钉扫码开发文档：https://open.dingtalk.com/document/orgapp/tutorial-obtaining-user-personal-information#title-qpi-0qv-anm

function QRCode() {

  const navigate = useNavigate()
  
  const { loginStatus, loginUser, login, setLoginStatus } = useAuthStore()

  useEffect(() => {
    if (loginUser.userId > 0) {
      navigate('/')
    }
	}, [])

  useEffect(() => {
    import('https://g.alicdn.com/dingding/h5-dingtalk-login/0.21.0/ddlogin.js').then(() => {
      window.DTFrameLogin(
        {
          id: 'qrCodeContainer',
          width: 300,
          height: 300,
        },
        {
          redirect_uri: encodeURIComponent('https://sales.mycht.cn/p/dingding/callback'),
          client_id: 'dingwgdx6emlxr3fcrg8',
          scope: 'openid',
          response_type: 'code',
          state: 'global-sales',
          prompt: 'consent',
        },
        (loginResult) => {
          const { authCode } = loginResult
          login(authCode)
        },
        (errorMsg) => {
          setLoginStatus(403)
          console.error(`Login Error: ${errorMsg}`)
        },
      )
    })
  }, [])

  if (loginStatus === 200) {
    return (
      <Flex justify='center' align='center' gap='middle' vertical>
        <Result
          status='success'
          title='扫码成功'
          subTitle='正在获取你的权限'
          extra={[
            <Spin size='small' />
          ]}
        />
      </Flex>
    )
  } else if (loginStatus === 302) {
    navigate('/')
  } else if (loginStatus === 403) {
    return (
      <Flex justify='center' align='center' gap='middle' vertical>
        <Result
          status='403'
          title='403'
          subTitle='你没有绑定钉钉账号，无法登陆。'
        />
      </Flex>
    )
  } else {
    return (
      <Flex justify='center' align='center' gap='middle' vertical>
        <Title level={4}>使用钉钉扫码</Title>
        <div id='qrCodeContainer' style={{ border: '12px solid rgba(5, 5, 5, 0.06)', borderRadius: '8px' }}></div>
      </Flex>
    )
  }
}

export default QRCode