app.js 6.6 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: ''
}
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 } = util.getLocalStorage('dj_scrm_corpId')
      ssoApi
        .login({
          code,
          corpId
        })
        .then(({ code, data }) => {
          let url = `${redirectUrl.split('#')[0]}#/`
          let route = state.lastPath == 'home' ? '' : state.lastPath
          state.showWindow = true
          console.log(data)
          if (code == '0') {
            if (data.loginList.length) {
              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.replace(`${url}${route}`)
              }
            } else {
              /**没有账号 */
              window.location.href = `${url}common/nothing`
            }
          } else {
            window.location.href = `${url}common/nothing`
          }
        })
    } else {
      util.showLoading()
      let appid = getParams('corpId') //从链接获取
      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
        } else {
          if (IS_PROD) {
            Notify({
              message: '缺少corpId!',
              duration: 15000
            })
            return
          } else appid = 'ww7ee69c648ae1b7e6'
        }
      }
      util.setLocalStorage('dj_scrm_corpId', { corpId: appid })
      const wxUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize'
      window.location.href = `${wxUrl}?appid=${appid}&redirect_uri=${encodeURIComponent(redirectUrl)}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`
    }
  },
  navigation ({ dispatch }, to) {
    let { redirect_uri, corpId } = getParams()
    let userInfo = util.getLocalStorage('dj_scrm_userInfo')
    let loginList = util.getLocalStorage('dj_scrm_accountList')
    if (corpId) util.setLocalStorage('dj_scrm_corpId', { corpId })
    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
}