import { fetchGetThirdUserInfo, fetchLogin, fetchLoginByUid } from '@/api/user'
import { EnumStorageKey } from '@/enum'
import { getQueryVariable } from '@/utils/location'
import { setLocal, setSession } from '@/utils/storage'

export function useAuth() {
  /** 授权 */
  function oauth2Verify() {
    // 当前企业的 corp_id
    // eslint-disable-next-line node/prefer-global/process
    const origin = process.env.VITE_APP_BASE_API?.replace('/sdream-api', '')
    // eslint-disable-next-line node/prefer-global/process
    const corpId = process.env.VITE_APP_WECHAT_APP_ID
    // 重定向 URL
    const source = `${origin}${window.location.pathname}${window.location.search}`
    // const source = 'https://jianyan-sit.guominpension.com'
    const url = encodeURIComponent(source)
    // 授权链接 URL
    // snsapi_base
    const loginUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${corpId}&redirect_uri=${url}&response_type=code&scope=snsapi_base&state=#wechat_redirect`
    console.log(loginUrl, 'loginUrl')
    // 跳转授权链接e
    window.location.href = loginUrl
  }
  /** 用code去换用户信息 */
  async function codeExchangeToken() {
    const res = await fetchGetThirdUserInfo(getQueryVariable('code') as string)
    if (res.data) {
      const loginRes = await fetchLogin(res.data.loginCode)
      if (loginRes.data) {
        setLocal(EnumStorageKey.token, loginRes.data.token)
        setLocal(EnumStorageKey['user-info'], loginRes.data)
        setLocal('userName', loginRes.data.userName)
        setSession(EnumStorageKey.temporary, true)
        setLocal('grantFlag', loginRes.data.grantFlag)
        window.location.reload()
        return true
      }
      else {
        return false
      }
    }
    else {
      return false
    }
  }
  /**
   * 用 uid换token
   */
  async function utdExchangeToken() {
    const loginRes = await fetchLoginByUid(getQueryVariable('utd') as string)
    if (loginRes.data) {
      setLocal(EnumStorageKey.token, loginRes.data.token)
      setLocal(EnumStorageKey['user-info'], loginRes.data)
      setLocal('userName', loginRes.data.userName)
      setSession(EnumStorageKey.temporary, true)
      window.location.reload()
      return true
    }
    else {
      return false
    }
  }
  return {
    oauth2Verify,
    codeExchangeToken,
    utdExchangeToken,
  }
}
