
/**
 * @description 单点登录
 * @param redirect_uri 需要后端添加(该项目的访问地址，不然就是跳回来就是白板) 关键!!!!!!!!!!!!!!!!!!!!!!!
 */

import { request } from '@umijs/max';
import { Base64 } from 'js-base64';
import { setCookie, getCookie, removeAllCookies } from '@/utils/cookie'

import { INDEX_ROUTE, CLIENT_ID, CLIENT_SECRET, LOGIN_SERVE } from '@/utils/loginUtil/config';


const IS_PROD = process.env.NODE_ENV === 'production'

// 接口前缀
const apiPrefix = IS_PROD ? '/cd-comprehensive/apis' : `/apis`;


// 获取单点登录的地址
export const getSSOUrl = (): string => {
  const oauthPath = "/oauth2/authorize";

  const redirect_uri = window.location.origin + INDEX_ROUTE // 重定向地址
  const client_id = CLIENT_ID; //客户端 ID
  const scope = 'server';
  const response_type = 'code'; // 授权码

  return `${LOGIN_SERVE}${oauthPath}?scope=${scope}&response_type=${response_type}&client_id=${client_id}&redirect_uri=${redirect_uri}`;;
}

// 单点退出登录
export const handleLogout = (): void => {

  const redirect_url = window.location.href // 完整的url

  const logoutUrl = `${LOGIN_SERVE}/logout?redirect_url=${redirect_url}`

  try {
    // 这儿的接口不管请求成功还是失败都会去到登录
    request(`${apiPrefix}/auth/token/logout`, { method: 'delete' }).then(() => {
      removeAllCookies();
      window.location.replace(logoutUrl);
    })
  } catch (error) {
    console.log('退出登录失败错误信息', error)
    removeAllCookies();
    window.location.replace(logoutUrl);
  }
}



export const getUrlParams = () => {
  let url = location.search; //获取url中"?"符后的字串
  let theRequest: any = new Object();
  if (url.indexOf('?') !== -1) {
    let str = url.substring(1);
    let strs = str.split('&');
    for (let i = 0; i < strs.length; i++) {
      theRequest[strs[i].split('=')[0]] = decodeURIComponent(strs[i].split('=')[1]);
    }
  }
  return theRequest;
};

// 处理单点登录code, 获取token
export const getTokenByUrlCode = (code: string) => {
  return new Promise<{ access_token: string }>((resolve, reject) => {
    try {
      if (!code) {
        reject('没有获取到code')
        return;
      }
      const params: any = {
        grant_type: 'authorization_code',
        scope: 'server',
        redirect_uri: window.location.origin + INDEX_ROUTE,
        code
      }
      const formData = new FormData()
      for (let key in params) {
        if (params.hasOwnProperty(key)) {
          formData.append(key, params[key]);
        }
      }
      // 获取token
      request<any>(`${apiPrefix}/auth/oauth2/token`, {
        method: 'post',
        data: formData,
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          Authorization: 'Basic ' + Base64.encode(`${CLIENT_ID}:${CLIENT_SECRET}`)
        }
      }).then(response => {
        if (response.code === 200) {
          resolve(response.data)
        } else {
          reject('code换取token失败')
        }
      }).catch(error => {
        console.log('code换取token失败', error)
        reject(error)
      })
    } catch (error) {
      console.log('code换取token失败', error)
      reject(error)
    }
  })
}

// 登录前置校验
export const checkBeforeLogin = async (cb: () => void, isRedirect: boolean = true): Promise<void> => {
  const token = getCookie('token');
  let Request: any = new Object();
  Request = getUrlParams();
  const code = Request['code']
  // 如果没有token 和 code 就去登录
  if (!token && !code) {
    sessionStorage.clear();
    window.location.replace(getSSOUrl())
    return
  }
  // 如果有code就去换token
  if(!token && code) {
    const authToken = await getTokenByUrlCode(code)
    setCookie('token', authToken.access_token)
    if(isRedirect) {
      location.href = window.location.origin + INDEX_ROUTE;
    }
  }
  cb()
}