useRoleCityList.ts 1.21 KB
import { computed, ref } from 'vue'
import { storeToRefs } from 'pinia'
import { cityApi } from '@/api'
import { useAuthStore } from '@/stores/auth'

export type CityOption = {
  id: number
  name: string
  [key: string]: any
}

export function useRoleCityList() {
  const auth = useAuthStore()
  const { isAdmin, user } = storeToRefs(auth)
  const cityList = ref<CityOption[]>([])
  const managedCityId = computed<number | undefined>(() => user.value?.cityId)
  const managedCityName = computed(() => user.value?.cityName || '')

  function buildManagedCityList() {
    return managedCityId.value
      ? [{ id: managedCityId.value, name: managedCityName.value || `租户#${managedCityId.value}` }]
      : []
  }

  async function loadCities() {
    if (!isAdmin.value) {
      cityList.value = buildManagedCityList()
      return
    }
    const res: any = await cityApi.openList()
    cityList.value = Array.isArray(res?.data) ? res.data : []
  }

  function getCityName(cityId?: number) {
    const city = cityList.value.find(item => item.id === cityId)
    return city?.name || (cityId ? `租户#${cityId}` : '-')
  }

  return {
    isAdmin,
    managedCityId,
    managedCityName,
    cityList,
    loadCities,
    getCityName,
  }
}