app.js 7.32 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'
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 = {
  // 设置name
  setUserInfo ({ commit }, user) {
    commit('SET_USER_INFO', user)
    store.set(store.consts.USER_KEY, user)
  },
  setPageMeta ({ commit }, meta) {
    document.title = meta.title || '嘀加企微助手'
    commit('SET_PAGE_META', meta || {})
  },
  setLoginToken ({ commit }, val) {
    commit('SET_LOGIN_TOKEN', val)
  },
  setAccountList ({ commit }, list) {
    commit('SET_ACCOUNT_LIST', list)
  },
  setSessionId ({ commit }, id) {
    commit('SET_SESSION_ID', id)
  },
  pushKeep ({ commit }, name) {
    commit('PUSH_KEEP', name)
  },
  removeKeep ({ commit }, names) {
    commit('REMOVE_KEEP', names)
  },
  registerHttp ({ }, sessionId = '') {
    console.log('sessionId', sessionId)
    window.$HTTP = new Http({ ...window.$fetchConfig, alert: Notify, headers: { token: sessionId } })
  },
  login ({ dispatch }) {
    let [redirectUrl] = window.location.href.split('?')
    const code = getParams('code')
    if (code) {
      const { corpId, agentId } = util.getLocalStorage('dj_scrm_corpId')
      ssoApi
        .login({
          code,
          corpId,
          getUserInfoFlag: agentId ? true : false
        })
        .then(({ code, data }) => {
          let url = `${redirectUrl.split('#')[0]}#/`
          let route = state.lastPath == 'home' ? '' : state.lastPath
          if (code == '0') {
            if (data.loginList.length) {
              state.showWindow = true
              route = route.replace('.', '/')
              if (data.loginList.length > 1) {
                util.setLocalStorage('dj_scrm_loginToken', data.loginToken)
                util.setLocalStorage('dj_scrm_accountList', data.loginList)
                window.location.href = `${url}common/accountList?lastPath=${route}`
              } else {
                let redirect_uri = util.getLocalStorage('dj_scrm_redirect_uri')
                let [userInfo] = data.loginList
                if (userInfo.status != 2) {
                  /**账号过期 */
                  window.location.href = `${url}common/overdue`
                  return
                }
                util.setLocalStorage('dj_scrm_userInfo', userInfo)
                util.setSessionId(userInfo.sessionId)
                dispatch('registerHttp', userInfo.sessionId)
                util.removeLocalStorage('dj_scrm_redirect_uri')
                // 只有一个账号 history.back()
                if (route == 'common/overdue' || route == 'common/nothing') route = ''
                if (redirect_uri) {
                  let [URL, query] = decodeURIComponent(redirect_uri).split('?')
                  URL = `${URL}?sessionId=${userInfo.sessionId}&corpId=${corpId}`
                  if (query) URL = `${URL}&${query}`
                  window.location.href = URL
                }
                else window.location.href = `${url}${route}`
              }
            } else {
              /**没有账号 */
              window.location.href = `${url}common/nothing`
            }
          } else {
            window.location.href = `${url}common/nothing`
          }
        })
    } else {
      util.showLoading()
      let appid = getParams('corpId') //从链接获取
      let agentid = getParams('agentId') //从链接获取
      let dj_scrm = util.getLocalStorage('dj_scrm_corpId')
      const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV)
      if (!appid) {
        if (dj_scrm) {
          appid = dj_scrm.corpId
          agentid = dj_scrm.agentId
        } else {
          if (IS_PROD) {
            Notify({
              message: '缺少corpId!',
              duration: 15000
            })
            return
          } else {
            appid = 'wp-ZewEAAAhictTABWn9t2_N79ybqhCw'
            agentid = 1000002
            // appid = 'wwc1fefc2a3f70bd0b'
            // agentid = 1000002
          }
        }
      }
      let dj_scrm_storage = { corpId: appid }
      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=snsapi_privateinfo&agentid=${agentid}`
        dj_scrm_storage.agentId = agentid
      }
      else wxUrl = `${wxUrl}&scope=snsapi_base`
      util.setLocalStorage('dj_scrm_corpId', dj_scrm_storage)
      window.location.href = `${wxUrl}&state=STATE#wechat_redirect`
    }
  },
  navigation ({ dispatch }, to) {
    let { redirect_uri, corpId, agentId } = getParams()
    let userInfo = util.getLocalStorage('dj_scrm_userInfo')
    let loginList = util.getLocalStorage('dj_scrm_accountList')
    if (corpId) {
      let dj_scrm_storage = {}
      dj_scrm_storage.corpId = corpId
      if (agentId && agentId != 'undefined') dj_scrm_storage.agentId = agentId
      util.setLocalStorage('dj_scrm_corpId', dj_scrm_storage)
    }
    if (redirect_uri) util.setLocalStorage('dj_scrm_redirect_uri', redirect_uri)
    let dj_scrm = util.getLocalStorage('dj_scrm_corpId')
    if (dj_scrm && userInfo) {
      if (dj_scrm.corpId != userInfo.entmicroId) {
        util.showLoading()
        removeStoreage()
      }
    }
    try {
      if (loginList && dj_scrm) {
        loginList.length && loginList.map(e => {
          if (e.entmicroId != dj_scrm.corpId) throw false
        })
      }
    } catch (error) {
      util.showLoading()
      removeStoreage()
    }
    login({
      dispatch,
      to
    })
  },
}

const login = ({ dispatch, to }) => {
  let loginToken = util.getLocalStorage('dj_scrm_loginToken')
  let userInfo = util.getLocalStorage('dj_scrm_userInfo')
  let sessionId = util.getSessionId()
  dispatch('registerHttp', sessionId || '')
  if (!userInfo || !sessionId) {
    if (loginToken) {
      state.showWindow = true
      if (to && to.name != 'common.accountList') router.replace({ name: 'common.accountList' })
      return
    } else {
      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('dj_scrm_userInfo')
  util.removeLocalStorage('dj_scrm_accountList')
  util.removeLocalStorage('dj_scrm_loginToken')
  util.clearSessionId()
}
export default {
  state,
  mutations,
  actions
}