<template>
  <div class="navbar">
    <div class="navbar-left">
      <img class="navbar-logo-img" src="@/assets/logo/logo.png" alt="logo" height="27" width="150px" />
<!--      <span class="navbar-title">浪潮智能信发平台</span>-->
    </div>
    <div class="navbar-center">
      <top-nav id="topmenu-container" class="topmenu-container" />
    </div>
    <div class="navbar-right">
      <div class="right-menu flex align-center">
        <template v-if="appStore.device !== 'mobile'">
          <span v-if="tenantShow && tenantEnabled && companyName" class="navbar-tenant-name" @click="openTenantDialog"
            style="cursor: pointer; display: inline-block; margin-right: 12px; color: #fff">
            <svg-icon icon-class="company" style="margin-right: 4px; vertical-align: middle" />
            <span style="vertical-align: middle">{{
              tenantList.find((t) => String(t.tenantId) === String(companyName))?.companyName || companyName
              }}</span>
          </span>
          <el-dialog v-model="showTenantDialog" :title="$t('navbar.selectTenant')" width="800px" append-to-body>
            <el-table :data="tenantList" style="width: 100%; margin-bottom: 12px" height="320"
              @row-click="handleRadioSelect"
              :row-class-name="({ row }) => (String(row.tenantId) === String(selectedTenantId) ? 'is-selected' : '')"
              v-loading="tenantLoading" element-loading-text="加载租户列表中...">
              <el-table-column label="租户编号" width="120" align="center">
                <template #default="scope">
                  <span style="display: flex; align-items: center; gap: 6px">
                    <el-radio :model-value="selectedTenantId" :label="String(scope.row.tenantId)"
                      style="margin-left: 4px" :disabled="false" />
                    <!-- {{ scope.row.tenantId }} -->
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="companyName" label="企业名称" min-width="200" />
              <el-table-column prop="licenseNumber" label="社会信用代码" min-width="180" />
              <el-table-column prop="contactUserName" label="联系人" min-width="100" />
              <el-table-column prop="contactPhone" label="联系电话" min-width="120" />
            </el-table>
            <div style="text-align: right">
              <el-button @click="showTenantDialog = false">取消</el-button>
              <el-button type="primary" :disabled="!selectedTenantId || selectedTenantId === companyName"
                @click="confirmSelectTenant">确定</el-button>
            </div>
          </el-dialog>

          <!-- <header-search id="header-search" class="right-menu-item" /> -->
          <search-menu ref="searchMenuRef" />
          <!-- <el-tooltip content="搜索" effect="dark" placement="bottom">
          <div class="right-menu-item hover-effect" @click="openSearchMenu">
            <svg-icon class-name="search-icon" icon-class="search" />
          </div>
        </el-tooltip> -->
          <!-- 消息 -->
          <!-- <el-tooltip :content="$t('navbar.message')" effect="dark" placement="bottom">
          <div>
            <el-popover placement="bottom" trigger="click" transition="el-zoom-in-top" :width="300" :persistent="false">
              <template #reference>
                <el-badge :value="newNotice > 0 ? newNotice : ''" :max="99">
                  <svg-icon icon-class="message" />
                </el-badge>
              </template>
<template #default>
                <notice></notice>
              </template>
</el-popover>
</div>
</el-tooltip> -->
          <!--        <el-tooltip content="Github" effect="dark" placement="bottom">
          <ruo-yi-git id="ruoyi-git" class="right-menu-item hover-effect" />
        </el-tooltip>

        <el-tooltip :content="$t('navbar.document')" effect="dark" placement="bottom">
          <ruo-yi-doc id="ruoyi-doc" class="right-menu-item hover-effect" />
        </el-tooltip>-->

          <!-- <el-tooltip :content="$t('navbar.full')" effect="dark" placement="bottom">
          <screenfull id="screenfull" class="right-menu-item hover-effect" />
        </el-tooltip> -->

          <!--        <el-tooltip :content="$t('navbar.language')" effect="dark" placement="bottom">
          <lang-select id="lang-select" class="right-menu-item hover-effect" />
        </el-tooltip>-->

          <!--        <el-tooltip :content="$t('navbar.layoutSize')" effect="dark" placement="bottom">
          <size-select id="size-select" class="right-menu-item hover-effect" />
        </el-tooltip>-->
        </template>
        <div class="avatar-container">
          <el-dropdown class="right-menu-item hover-effect" trigger="click" @command="handleCommand">
            <div class="avatar-wrapper" style="margin-top: 0%">
              <span class="menu-title" style="
                  max-width: 120px;
                  display: inline-block;
                  vertical-align: middle;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                  color: #fff;
                  margin-left: 1rem;
                ">{{ userStore.nickname }}</span>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <router-link v-if="!dynamic" to="/user/profile">
                  <el-dropdown-item>{{ $t('navbar.personalCenter') }}</el-dropdown-item>
                </router-link>
                <el-dropdown-item v-if="settingsStore.showSettings" command="setLayout">
                  <span>{{ $t('navbar.layoutSetting') }}</span>
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  <span>{{ $t('navbar.logout') }}</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import SearchMenu from './TopBar/search.vue';
import useAppStore from '@/store/modules/app';
import useUserStore from '@/store/modules/user';
import useSettingsStore from '@/store/modules/settings';
import useNoticeStore from '@/store/modules/notice';
import { getTenantList } from '@/api/login';
import { dynamicClear, dynamicTenant } from '@/api/system/tenant';
import { TenantVO } from '@/api/types';

const appStore = useAppStore();
const userStore = useUserStore();
const settingsStore = useSettingsStore();
const noticeStore = storeToRefs(useNoticeStore());
const newNotice = ref(<number>0);

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const tenantShow = ref(false);
const userId = ref(userStore.userId);
const permissions = ref(userStore.permissions);
import { listTenant } from '@/api/system/tenant';

const companyName = ref('');
const tenantList = ref<TenantVO[]>([]);
const showTenantDialog = ref(false);
const selectedTenantId = ref('');
const tenantLoading = ref(false);

async function openTenantDialog() {
  tenantLoading.value = true;
  showTenantDialog.value = true;
  try {
    // 尝试用undefined作为参数
    const resp = await listTenant(undefined);
    console.log('listTenant full response:', resp);
    tenantList.value = (resp.rows || []).map((item) => ({
      ...item,
      tenantId: String(item.tenantId)
    }));
  } catch (e) {
    console.error('listTenant failed', e);
    tenantList.value = [];
  } finally {
    tenantLoading.value = false;
  }
}

watch(companyName, (val) => {
  console.log('companyName changed:', val);
});
watch(tenantList, (val) => {
  console.log('tenantList changed:', val);
  console.log('tenantList full:', JSON.stringify(val, null, 2));
  if (!companyName.value && val.length > 0) {
    // 优先根据用户的tenantId决定
    const userTenantId = String(userStore.tenantId);
    const match = val.find((t) => String(t.tenantId) === userTenantId);
    if (match) {
      companyName.value = userTenantId;
      console.log('companyName set by userStore.tenantId:', companyName.value);
    } else {
      companyName.value = String(val[0].tenantId);
      console.log('companyName fallback to first:', companyName.value);
    }
  }
  // 每次租户列表变化时，默认高亮当前companyName
  selectedTenantId.value = String(companyName.value);
});

onMounted(() => {
  console.log('onMounted companyName:', companyName.value);
  console.log('onMounted tenantList:', tenantList.value);
  console.log('onMounted tenantList full:', JSON.stringify(tenantList.value, null, 2));
});

function handleRadioSelect(row: any) {
  if (row) {
    selectedTenantId.value = String(row.tenantId);
    console.log('selectedTenantId changed:', selectedTenantId.value);
  }
}

function confirmSelectTenant() {
  if (selectedTenantId.value && companyName.value !== selectedTenantId.value) {
    dynamicTenantEvent(selectedTenantId.value);
  }
  showTenantDialog.value = false;
}

console.log('navbar render', companyName.value, tenantList.value);
// 是否切换了租户
const dynamic = ref(false);
// 租户开关
const tenantEnabled = ref(true);
// 搜索菜单
const searchMenuRef = ref<InstanceType<typeof SearchMenu>>();

const openSearchMenu = () => {
  searchMenuRef.value?.openSearch();
};

// 动态切换
const dynamicTenantEvent = async (tenantId: string) => {
  if (companyName.value != null && companyName.value !== '') {
    await dynamicTenant(tenantId);
    companyName.value = tenantId; // 立即同步UI
    dynamic.value = true;
    proxy?.$tab.closeAllPage();
    proxy?.$router.push('/');
    proxy?.$tab.refreshPage();
  }
};

const dynamicClearEvent = async () => {
  await dynamicClear();
  dynamic.value = false;
  proxy?.$tab.closeAllPage();
  proxy?.$router.push('/');
  proxy?.$tab.refreshPage();
};

/** 租户列表 */
const initTenantList = async () => {
  const { data } = await getTenantList();
  tenantEnabled.value = data.tenantEnabled === undefined ? true : data.tenantEnabled;
  if (tenantEnabled.value) {
    tenantList.value = data.voList;
  }
  if (userId.value === 1 || permissions.value?.includes('*:*:*')) {
    tenantShow.value = true;
  }
};

defineExpose({
  initTenantList
});

const toggleSideBar = () => {
  appStore.toggleSideBar(false);
};

const logout = async () => {
  await ElMessageBox.confirm('确定注销并退出系统吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  });
  await userStore.logout();
  location.href = import.meta.env.VITE_APP_CONTEXT_PATH + 'index';
};

const emits = defineEmits(['setLayout']);
const setLayout = () => {
  emits('setLayout');
};
// 定义Command方法对象 通过key直接调用方法
const commandMap: { [key: string]: any } = {
  setLayout,
  logout
};
const handleCommand = (command: string) => {
  // 判断是否存在该方法
  if (commandMap[command]) {
    commandMap[command]();
  }
};
//用深度监听 消息
watch(
  () => noticeStore.state.value.notices,
  (newVal) => {
    newNotice.value = newVal.filter((item: any) => !item.read).length;
  },
  { deep: true }
);
</script>

<style lang="scss" scoped>
:deep(.el-select .el-input__wrapper) {
  height: 30px;
}

:deep(.el-badge__content.is-fixed) {
  top: 12px;
}

.flex {
  display: flex;
}

.align-center {
  align-items: center;
}

.navbar {
  height: 50px;
  overflow: hidden;
  position: relative;
  //background: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);

  .hamburger-container {
    line-height: 46px;
    height: 100%;
    float: left;
    cursor: pointer;
    transition: background 0.3s;
    -webkit-tap-highlight-color: transparent;

    &:hover {
      background: rgba(0, 0, 0, 0.025);
    }
  }

  .breadcrumb-container {
    float: left;
  }

  .topmenu-container {
    position: absolute;
    background-color: transparent;
    left: 50px;
    margin-top: 5px;
  }

  .errLog-container {
    display: inline-block;
    vertical-align: top;
  }

  .right-menu {
    float: right;
    height: 100%;
    line-height: 50px;
    display: flex;

    &:focus {
      outline: none;
    }

    .right-menu-item {
      display: inline-block;
      padding: 0 8px;
      height: 100%;
      font-size: 18px;
      color: #5a5e66;
      vertical-align: text-bottom;

      &.hover-effect {
        cursor: pointer;
        transition: background 0.3s;

        &:hover {
          background: rgba(0, 0, 0, 0.025);
        }
      }
    }

    .avatar-container {
      margin-right: 40px;

      .avatar-wrapper {
        // margin-top: 5px;
        position: relative;

        .user-avatar {
          cursor: pointer;
          width: 40px;
          height: 40px;
          border-radius: 10px;
          // margin-top: 10px;
        }

        i {
          cursor: pointer;
          position: absolute;
          right: -20px;
          top: 4px;
          // font-size: 12px;
        }
      }
    }
  }
}

.navbar {
  display: flex;
  align-items: center;
  height: 60px;
  width: 100%;
  background: #2282ff;
  box-sizing: border-box;
  padding: 0 20px;
}

.navbar-left {
  display: flex;
  align-items: center;
  flex-shrink: 0;
}

.navbar-logo-img {
  margin-right: 10px;
  margin-top: 10px;
}

.navbar-title {
  font-size: 18px;
  font-weight: bold;
  color: #222;
  letter-spacing: 2px;
}

.navbar-center {
  flex: 1;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  min-width: 0;
  position: relative;
  z-index: 1;
  margin-left: -35px;
  /* 适当左移，可根据实际调整 */
}

.topmenu-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: auto;
  max-width: 900px;
  flex: 1;
}

.navbar-right {
  display: flex;
  align-items: center;
  flex-shrink: 0;
  margin-left: 20px;
  min-width: 200px;
  justify-content: flex-end;
}

.navbar-logo-title {
  display: flex;
  align-items: center;
  height: 100%;
  margin-right: 20px;
}

.navbar-logo-img {
  display: block;
  margin-right: 10px;
}

.navbar-title {
  font-size: 18px;
  font-weight: normal;
  color: #ffffff;
  letter-spacing: 2px;
}

.navbar-main {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 0;
}

.topmenu-container {
  flex: 1;
  min-width: 0;
}
</style>
