<template>
  <el-dropdown trigger="click" @command="handleTenantChange">
    <div class="tenant-select" :class="{ 'hover': showHover }"
         @mouseenter="showHover = true" @mouseleave="showHover = false">
      <span class="tenant-name">{{ currentTenantName }}</span>
      <i class="el-icon-arrow-down" />
    </div>

    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item
            v-for="tenant in tenants"
            :key="tenant.apiLoginTenantInfoResponse.tenantBizId"
            :command="tenant"
            :class="{ 'current': isCurrentTenant(tenant) }"
        >
          <div class="tenant-item">
            <span>{{ tenant.apiLoginTenantInfoResponse.tenantName }}</span>
            <el-icon v-if="isCurrentTenant(tenant)" class="check-icon">
              <Check />
            </el-icon>
          </div>
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script setup>
import { computed, ref } from 'vue'
import { Check } from '@element-plus/icons-vue'
import useUserStore  from '@/store/modules/user'
import usePermissionStore from '@/store/modules/permission'
import { resetRouter } from '@/router'
import { useRouter } from 'vue-router'

const userStore = useUserStore()
const permissionStore = usePermissionStore()
const router = useRouter()
const showHover = ref(false)

// 计算属性
const tenants = computed(() => userStore.tenants)
const currentTenant = computed(() => userStore.currentTenant)
const currentTenantName = computed(() =>
    currentTenant.value?.apiLoginTenantInfoResponse?.tenantName || '选择租户'
)

// 判断是否是当前租户
const isCurrentTenant = (tenant) => {
  return tenant.apiLoginTenantInfoResponse.tenantBizId ===
      currentTenant.value?.apiLoginTenantInfoResponse?.tenantBizId
}

// 切换租户
const handleTenantChange = async (tenant) => {
  if (!isCurrentTenant(tenant)) {
    // 切换租户
    await userStore.switchTenant(tenant)

    // // 重新生成路由
    // const routes = await permissionStore.generateRoutes()
    //
    // // 重置路由
    // resetRouter()
    //
    // // 添加新路由
    // routes.forEach(route => {
    //   if (!isHttp(route.path)) {
    //     router.addRoute(route)
    //   }
    // })
    //
    // // 刷新页面以更新菜单
    // router.replace('/').then(() => {
    //   location.reload()
    // })

  }
}
</script>

<style scoped>
.tenant-select {
  display: flex;
  align-items: center;
  padding: 0 12px;
  height: 48px;
  cursor: pointer;
  transition: background .3s;
}

.tenant-select.hover {
  background: rgba(0, 0, 0, 0.025);
}

.tenant-name {
  margin-right: 4px;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}


.tenant-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-width: 150px;
}

.check-icon {
  margin-left: 8px;
  color: var(--el-color-primary);
}


.current {
  background-color: #f5f7fa;
}
</style>
