import { Result, Spin, Flex, Typography } from 'antd'
import React, { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'

import { useAuthContext } from '@/stores/AuthContext'

const { Title } = Typography

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

function DingdingQRCode() {

  const navigate = useNavigate()
  const { loginUser } = useAuthContext()
  const [loginStatus, setLoginStatus] = useState(0)

  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
          console.log(loginResult)
          setLoginStatus(200)

          fetch(`https://p9axztuwd7x8a7.mycht.cn/dingtalk/dingtalkwork/WhatsAppAuth?authCode=${authCode}`)
            .then(response => response.json())
            .then(json => {
              // {"errcode":0,"errmsg":"ok","result":{"nick":"廖一军","unionId":"j7cuUCplZe1ZiiqjQNUUmFwiEiE","avatarUrl":"https://static-legacy.dingtalk.com/media/lALPBDDrhXr716HNAoDNAoA_640_640.png","openId":"iioljiPmZ4RPoOYpkFiSn7IKAiEiE","mobile":"18777396951","stateCode":"86","email":"lyj@hainatravel.com","opisn":"383"}}
              if (json.errcode === 0) {
                loginUser.userId = json.result.opisn
                loginUser.accountName = json.result.opisn
                loginUser.username = json.result.nick
                loginUser.avatarUrl = json.result.avatarUrl
                loginUser.stateCode = json.result.stateCode
                loginUser.mobile = json.result.mobile
                loginUser.email = json.result.email
                loginUser.openId = json.result.openId
                navigate('/account/profile')
              } else {
                setLoginStatus(403)
              }
            })
        },
        (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 === 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 DingdingQRCode