import Taro, { useRouter } from '@tarojs/taro'
import { useRef } from 'react'
import qs from 'qs'
import useUserInfo from './useUserInfo'
// eslint-disable-next-line import/first
import { BASE_URL, WX_APPID } from '@/common/constant'

// 开这个hook 主要是为了让useHttp 能够调用

interface Param { success: boolean; data: any; msg: string; code: null | number; loading: boolean }
let loginStatus = false // 登录状态，true登录中
export default () => {
  const initData = {
    success: false,
    data: null,
    msg: '',
    code: null,
    loading: false,
  }
  const loginData = useRef<Param>(initData)
  const { setToken, setSessionKey } = useUserInfo()
  const router = useRouter()
  // 微信登录请求v2
  const fetchDataLogin = async(login_code) => {
    const q = {
      url: `${BASE_URL}/v2/mp/login`,
      header: {
        Platform: 3,
        Appid: WX_APPID,
        // Authorization: token || stateRef.current.token,
      },
      method: 'post',
      data: { js_code: login_code },
    }
    try {
      const result = await Taro.request(q as any)
      const { code, data, msg } = result.data
      if (result.statusCode === 200) {
        loginData.current.success = code === 0
        loginData.current.code = code
        loginData.current.msg = msg
        loginData.current.data = data
      }
      else {
        Taro.showToast({
          title: '错误：登录失败',
          icon: 'none',
        })
        console.log('登录错误：', result.errMsg)
      }
    }
    catch (e) {
      Taro.showToast({
        title: '错误：登录失败',
        icon: 'none',
      })
      console.log('登录错误：', e.errMsg)
    }
    return loginData.current
  }

  // 微信登录
  const login = () => {
    return new Promise((resolve, reject) => {
      // eslint-disable-next-line prefer-promise-reject-errors
      if (loginStatus) { return reject(false) }
      loginStatus = true
      Taro.login({
        success: async(res) => {
          if (res.code) {
            const { data, success, msg } = await fetchDataLogin(res.code)
            if (success) {
              setToken(data.token)
              setSessionKey(data.session_key)
              resolve(data)
              const params = router.params
              delete params.$taroTimestamp
              if (router.path === '/pages/index/index' || router.path === '/pages/user/index') {
                Taro.reLaunch({
                  url: `${router.path}?${qs.stringify(params)}`,
                })
              }
              else {
                Taro.redirectTo({
                  url: `${router.path}?${qs.stringify(params)}`,
                })
              }
            }
            else {
              Taro.showToast({
                title: '登录失败',
                icon: 'none',
              })
              reject(msg)
            }
          }
          else {
            console.log(`登录失败！${res.errMsg}`)
            reject(res.errMsg)
          }
          loginStatus = false
        },
        fail(e) {
          console.log('登录失败！::', e)
          reject(e)
          loginStatus = false
        },
      })
    })
  }

  return {
    login,
  }
}
