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

  // 获取用户openID(微信授权)
  const getUserCode = useCallback(() => {
    console.log(123, urlObjTemp.key)

    // window.location.href = 'http://192.168.20.55:3001/#/login?code=xxxx'
    //此处的ID是在文档的开发-基本配置里面
    // let appid = 'wx3d4f2e0cfc3b8e54'
    // let url = `https://sit-hqbooking.4dage.com/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=SCOPE&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]
  }, [])

  useEffect(() => {
    let code = getQueryCode('code')
    console.log('-----------', code)
    if (code) {
      // 发请求，拿token
      // 用户信息存到本地
      setTokenInfo({
        token:
          'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJvakpPdDZBc1MyTUhKSUFLMWtqSV9FTllyRnIwIiwibG9naW5UeXBlIjoid3giLCJpZCI6MSwidXNlck5hbWUiOiJvakpPdDZBc1MyTUhKSUFLMWtqSV9FTllyRnIwIiwiZXhwIjoxNzM0NjU3NjgyLCJyb2xlS2V5cyI6WyJ3ZWJfdXNlciJdLCJpYXQiOjE3MzQ1NzEyODIsImp0aSI6IjBkOTNlZTBkLTI0NjAtNDliZi1iM2Y2LTdjY2ZjNzMwNjVlMSJ9.01BrenscrgsUxvM6z6GFap0d78qnnmAVQuW1VTA_3mI'
      })
      // 跳到首页
      MessageFu.success('登录成功!')
      history.replace(urlObjTemp.key === '1' ? '/' : '/exhi')
    }
  }, [getQueryCode, urlObjTemp.key])

  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
