import { createNamespacedHelpers } from 'vuex'
import cloneDeep from 'lodash.clonedeep'
import store from '@/common/store'
import qs from 'qs'
import { state } from './store-common'

const { mapState } = createNamespacedHelpers('sd/common')

function getRunAs() {
  const query = qs.parse(window.location?.search?.replace('?', ''))
  return query?.srcTrustId?.toString() || 'default'
}

const userInfo = (state) => {
  return state.userInfo[getRunAs()]
}
const userPerms = (state) => state.userPerms[getRunAs()]

const storeMixin = {
  computed: {
    // store-common下的值，除了userInfo和userPerms都自动映射
    ...mapState(Object.keys(state).filter((key) => key !== 'userInfo' && key !== 'userPerms')),
    // 手工映射userInfo和userPerms
    ...mapState({
      userInfo,
      userPerms,
    }),
  },
}

function getStoreCommon() {
  // @ts-ignore
  return store.state.sd.common
}

/**
 * 从Vuex获取用户信息
 */
export function getUserInfo() {
  return cloneDeep(userInfo(getStoreCommon()))
}

/**
 * 从Vuex获取用户权限
 */
export function getUserPerms() {
  return cloneDeep(userPerms(getStoreCommon()))
}

/**
 * 用户信息写入到Vuex
 */
export function setUserInfo(info, runAs = getRunAs()) {
  store.commit('sd/common/setUserInfo', { [runAs]: info })
}

/**
 * 用户权限写入到Vuex
 */
export function setUserPerms(perms, runAs = getRunAs()) {
  store.commit('sd/common/setUserPerms', { [runAs]: perms })
}
export default storeMixin
