app.js 6.65 KB
/*
 * @Descripttion:
 * @version:
 * @Author: limin
 * @Date: 2021-06-07 14:12:32
 * @LastEditors: limin
 * @LastEditTime: 2021-07-06 12:02:21
 */
import { ssoApi } from '@/api'
import { store, util } from 'utils'
import { Http } from 'glsx-common'
import { Notify } from 'vant'
const state = {
  pageMeta: '',
  keepAlives: [],
  lastPath: '',
  showWindow: false
}
import router from '@/router'

// 检测是否为移动端
function isMobileDevice () {
  return /(phone|pad|pod|iphone|ipod|ios|ipad|android|mobile)/i.test(navigator.userAgent);
}
// 综合环境判断
function detectEnvironment () {
  const ua = navigator.userAgent.toLowerCase();
  const isWxWork = ua.includes('wxwork');
  const isWechat = ua.includes('micromessenger');
  const isMobile = isMobileDevice();

  if (isWxWork) {
    return 1
  } else {
    return isMobile ? 2 : 3
  }
}
const mutations = {
  SET_PAGE_META (state, meta) {
    state.pageMeta = meta
  },
  PUSH_KEEP (state, name) {
    if (!state.keepAlives.includes(name)) {
      state.keepAlives.push(name)
    }
  },
  REMOVE_KEEP (state, names) {
    state.keepAlives = state.keepAlives.reduce((arr, name) => {
      if (!names.includes(name)) {
        return arr.push(name)
      }
      return arr
    }, [])
  },
  SET_LAST_PATH (state, path) {
    state.lastPath = path
  }
}
const actions = {
  setPageMeta ({ commit }, meta) {
    document.title = meta.title || '登录中...'
    commit('SET_PAGE_META', meta)
  },
  // 设置name
  setUserInfo ({ commit }, user) {
    commit('SET_USER_INFO', user)
    store.set(store.consts.USER_KEY, user)
  },
  login ({ dispatch }) {
    try {
      let [redirectUrl] = window.location.href.split('?'),
        { defaultCorpId, defaultAgentId } = window.$fetchConfig
      const wwcode = getParams('code')
      if (wwcode) {
        const { corpId, agentId } = util.getLocalStorage('ww_storage_info')
        let redirect_uri = util.getLocalStorage('ww_redirect_uri'),
          url = `${redirectUrl.split('#')[0]}#/`,
          backLoginCode = util.getLocalStorage('ww_back_login_code')
        if (backLoginCode) {
          if (redirect_uri) {
            let [URL, query] = decodeURIComponent(redirect_uri).split('?')
            URL = `${URL}?code=${wwcode}`
            if (query) URL = `${URL}&${query}`
            window.location.href = URL
          } else {
            window.location.href = url
            throw '请设置回调地址'
          }
          return
        }
        ssoApi.login({
          code: wwcode,
          corpId,
          agentId
        }).then(res => {
          if (res.errCode == 0 && res.userId) {
            util.setLocalStorage('ww_userInfo', {
              userId: res.userId,
              entmicroId: corpId
            })
            if (redirect_uri) {
              let [URL, query] = decodeURIComponent(redirect_uri).split('?')
              URL = `${URL}?userId=${res.userId}`
              if (query) URL = `${URL}&${query}`
              window.location.href = URL
            }
            else window.location.href = url
          } else throw res.errMsg
        })
      } else {
        util.showLoading()
        let appid = getParams('corpId') //从链接获取
        let agentid = getParams('agentId') //从链接获取
        let logintype = getParams('loginType') //从链接登录类型
        let backLoginCode = getParams('backLoginCode') // 返回登录CODE
        let storage_info = util.getLocalStorage('ww_storage_info')
        let scope = getParams('scope') || 'snsapi_privateinfo' //应用授权作用域。 oauth2登录时可选snsapi_base:静默授权,snsapi_privateinfo:手动授权, 默认手动
        const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV)
        if (logintype) util.setLocalStorage('ww_login_type', logintype)
        if (backLoginCode) util.setLocalStorage('ww_back_login_code', backLoginCode)
        util.setLocalStorage('ww_scope', scope)
        if (!appid) {
          if (storage_info) {
            appid = storage_info.corpId
            agentid = storage_info.agentId
          } else {
            if (IS_PROD) throw '缺少corpId!'
            else {
              appid = defaultCorpId // 默认参数
              agentid = defaultAgentId //默认参数
            }
          }
        }
        let ww_storage_info = { corpId: appid },
          env = detectEnvironment()
        if (agentid && agentid != 'undefined') ww_storage_info.agentId = agentid
        util.setLocalStorage('ww_storage_info', ww_storage_info)
        if (env == 1) {
          let wxUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize'
          wxUrl = `${wxUrl}?appid=${appid}&redirect_uri=${encodeURIComponent(redirectUrl)}&response_type=code`
          if (agentid && agentid != 'undefined') {
            wxUrl = `${wxUrl}&scope=${scope}&agentid=${agentid}`
            ww_storage_info.agentId = agentid
          }
          else wxUrl = `${wxUrl}&scope=${scope}`

          window.location.href = `${wxUrl}&state=STATE#wechat_redirect`
        } else if (env == 2) {
          Notify({
            message: '请使用企业微信打开',
            duration: 999999999
          })
        } else {
          //扫码
          router.replace({ name: 'common.wwLoginPanel' })
        }

      }
    } catch (error) {
      if (error) Notify(typeof error === 'string' ? error : error.toString())
    }
  },
  navigation ({ dispatch }, to) {
    let { redirect_uri, corpId, agentId } = getParams()
    let userInfo = util.getLocalStorage('ww_userInfo')
    if (corpId) {
      let ww_storage_info = {}
      ww_storage_info.corpId = corpId
      if (agentId && agentId != 'undefined') ww_storage_info.agentId = agentId
      util.setLocalStorage('ww_storage_info', ww_storage_info)
    }
    if (redirect_uri) util.setLocalStorage('ww_redirect_uri', redirect_uri)
    let storage_info = util.getLocalStorage('ww_storage_info')
    if (storage_info && userInfo) {
      if (storage_info.corpId != userInfo.entmicroId) {
        util.showLoading()
        removeStoreage()
      }
    }
    login({
      dispatch,
      to
    })
  },
}

const login = ({ dispatch }) => {
  let userInfo = util.getLocalStorage('ww_userInfo')
  if (!userInfo) {
    state.showWindow = false
    util.showLoading()
    dispatch('login')
    return
  }
  state.showWindow = true

}
const getParams = name => {
  let [url, paramsList] = window.location.href.split('?')
  if (!paramsList) return name ? null : {}
  let param = paramsList.split('&')
  let obj = {}
  param.map(e => {
    let [key, value] = e.split('=')
    obj[key] = value
  })
  return name ? obj[name] : obj
}
const removeStoreage = () => {
  util.removeLocalStorage('ww_userInfo')
}
export default {
  state,
  mutations,
  actions
}