import React, { useCallback, useEffect } from 'react'
import styles from './index.module.scss'
import TopCom from '@/components/TopCom'
import { Button } from 'antd'
import { setTokenInfo } from '@/utils/storage'
import { MessageFu } from '@/utils/message'
import { useParams } from 'react-router-dom'
import { API_login } from '@/store/action/all'
import { baseUrlTemp } from '@/utils/http'
import { domShowFu } from '@/utils/domShow'
function Z1login() {
  // 获取地址栏参数 1：课程 2：展馆
  const urlObjTemp: any = useParams()

  // 获取用户openID(微信授权)
  const getUserCode = useCallback(() => {
    //此处的ID是在文档的开发-基本配置里面
    let appid = 'wxcf0db4440f05e3a5'
    let url = `${baseUrlTemp}/web/#/login/${urlObjTemp.key}`
    window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(
      url
    )}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
  }, [urlObjTemp.key])

  // 获取地址栏参数的方法
  const getQueryCode = useCallback((name: string) => {
    // 未传参，返回空
    if (!name) return null
    // 查询参数：先通过search取值，如果取不到就通过hash来取
    let after = window.location.search
    after = after.substr(1) || window.location.hash.split('?')[1]
    // 地址栏URL没有查询参数，返回空
    if (!after) return null
    // 如果查询参数中没有"name"，返回空
    if (after.indexOf(name) === -1) return null

    let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
    // 当地址栏参数存在中文时，需要解码，不然会乱码
    let r = decodeURI(after).match(reg)
    // 如果url中"name"没有值，返回空
    if (!r) return null

    return r[2]
  }, [])

  const API_loginFu = useCallback(async (code: string) => {
    const res = await API_login(code)
    if (res.code === 0) {
      // console.log(123, res)
      // // 跳到首页
      setTokenInfo(res.data)
      MessageFu.success('登录成功!')
      domShowFu('#AsyncSpinLoding', true)

      setTimeout(() => {
        domShowFu('#AsyncSpinLoding', false)
        window.location.href = `${baseUrlTemp}/web/home.html`
      }, 400)

      // history.replace(window.location.href.includes('/login/1') ? '/' : '/exhi')
    }
  }, [])

  useEffect(() => {
    let code = getQueryCode('code')
    // console.log('-----------', code)
    if (code) API_loginFu(code)
  }, [API_loginFu, getQueryCode])

  return (
    <div className={styles.Z1login}>
      <TopCom txt='登录' />
      <div className='Z1main'>
        <Button size='large' type='primary' onClick={getUserCode}>
          授权微信登录
        </Button>
      </div>
    </div>
  )
}

const MemoZ1login = React.memo(Z1login)

export default MemoZ1login
