import { app_config } from '@/config'
import { useUserStore } from '@/stores'
// import { localCache } from '@/utils/storage'

/**
 * 跳转企业微信获取最新code
 * @param fullPath to.fullPath
 */
export function wxLogin(fullPath: string) {
  const wxRedirect = app_config[import.meta.env.MODE]?.wxRedirect
  const userStore = useUserStore()
  userStore.clearAllUserInfo()
  // localCache.removeCache('token')
  const wxUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize'
  const redirect = encodeURIComponent('http://' + wxRedirect + fullPath)
  const wxParams = `?appid=ww42a2d34b42b8d721&redirect_uri=${redirect}&response_type=code&scope=snsapi_base&state=#wechat_redirect`
  window.location.href = wxUrl + wxParams
}

/**
 * 解析地址栏 code   beforeEach的时候 location.href 还是旧的 会一直进入到code 一直重定向循环
 *
 * ?code=ODwKMle878L26YftD85-nJQwDyQmSDyKeEpODM6qMMM&state=
 * @param search
 */
export function parseCode(path: string) {
  const reg = new RegExp('(^|\\\\?|&)' + 'code' + '=([^&]*)(\\\\s|&|$)', 'i')
  if (reg.test(path)) {
    return unescape(RegExp.$2.replace(/\+/g, ' '))
  }
  return ''
}

/**
 * 解析地址栏 isCodeLogin
 *
 * ?isCodeLogin=1
 * @param search
 */
export function parseIsCodeLogin() {
  const reg = new RegExp('(^|\\\\?|&)' + 'isCodeLogin' + '=([^&]*)(\\\\s|&|$)', 'i')
  if (reg.test(window.location.href)) {
    return unescape(RegExp.$2.replace(/\+/g, ' '))
  }
  return ''
}

/**
 * 解析地址栏 cutEmail
 *
 * ?cutEmail=xxx@yswg.com.cn
 * @param search
 */
export function parseIsCutEmail() {
  const reg = new RegExp('(^|\\\\?|&)' + 'cutEmail' + '=([^&]*)(\\\\s|&|$)', 'i')
  if (reg.test(window.location.href)) {
    return unescape(RegExp.$2.replace(/\+/g, ' '))
  }
  return ''
}
