<!-- 切换租户 -->
<template>
  <div class="switchTenantLable-wrapper">
    <el-tree-select
      :model-value="currentTenant"
      :data="options"
      size="small"
      check-strictly
      show-all-levels
      default-expand-all
      placeholder="请选择租户"
      @change="handleChange"
    />
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue';
  import { queryListTenant } from '@/api/tenant';
  import { useTargetTenantIdSetting } from '@/utils/useTargetTenantIdSetting';
  import { replaceParams } from '@/utils/helper/treeHelper';
  import router from '@/router';
  import { useRoute } from 'vue-router';
  import { msgConfirm } from '@/utils/element-plus/messageBox';

  interface TenantOption {
    label: string;
    value: string;
    children?: TenantOption[];
  }

  const { setValue, getValue } = useTargetTenantIdSetting();

  const currentTenant = ref();
  const options = ref<TenantOption[]>([]);

  const route = useRoute();

  onMounted(() => {
    const routeTenantId = route.query.targetTenantId as string;
    if (routeTenantId && routeTenantId !== 'undefined') {
      const nextTenantId = Number(routeTenantId);
      currentTenant.value = nextTenantId;
      setValue(routeTenantId);
    } else {
      currentTenant.value = Number(getValue());
    }
    queryListTenant().then((res) => {
      if (!res) return;
      options.value = replaceParams(res || [], 'tenantName', 'id');
      /** 如果当前租户没选中的话，默认选中第一个 */
      if (currentTenant.value === undefined && res.length > 1) {
        currentTenant.value = res[0].id;
      }
    });
  });

  /* 选择租户添加二次确认弹窗 */
  const handleChange = (targetTenantId: string) => {
    msgConfirm('是否切换租户？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      setValue(targetTenantId);
      currentTenant.value = Number(targetTenantId);
      // 统一返回首页
      await router.push('/');
      window.location.reload();
    });
  };
</script>
<style lang="scss" scoped>
  .switchTenantLable {
    margin-right: 15px;
    display: inline-block;
    width: 100px;
  }

  .switchTenantWrapper {
    margin-right: 20px;
  }

  .switchTenantLable-wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 80px;
    margin-left: 10px;
  }
</style>
