<template>
  <div class="app-process sa-flex sa-row-between">
    <v-contextmenu ref="cm">
      <v-contextmenu-item :disabled="taskbar.list.length < 2" @click="onClose(selectedCM)">
        <el-icon>
          <Close />
        </el-icon>
        {{ t('taskbar.close') }}
      </v-contextmenu-item>
      <v-contextmenu-item :disabled="taskbar.list.length < 2" @click="closeOther(selectedCM)">
        {{ t('taskbar.closeOthers') }}
      </v-contextmenu-item>
      <v-contextmenu-divider />
      <v-contextmenu-item>
        <el-icon>
          <SwitchButton />
        </el-icon>
        {{ t('common.cancel') }}
      </v-contextmenu-item>
    </v-contextmenu>
    <!-- TODO: 页面需要开多个路由栈(传值) -->
    <div class="app-process__scroller sa-flex">
      <div v-for="(item, index) in taskbar.list" :key="index" class="app-process__item sa-flex"
        :class="{ active: item.name == taskbar.history[0] }" :data-index="index" @click="onMenu(item)" v-contextmenu:cm
        @contextmenu.prevent.stop="onCM(e, item)">
        <div class="wrap sa-flex">
          <sa-icon v-if="item.icon" class="sa-m-r-8" :icon="item.icon" size="14" />
          <span class="text">{{ getTaskbarTitle(item) }}</span>
          <div v-if="taskbar.list.length > 1" class="item-close sa-flex sa-row-center">
            <el-icon @click.stop="onClose(item.name)">
              <Close class="close" />
            </el-icon>
          </div>
        </div>
      </div>
    </div>

    <!-- 语言切换器 -->
    <div class="app-process__language">
      <el-dropdown @command="handleLanguageChange" class="language-switcher">
        <div class="language-trigger">
          <span class="language-icon">🌐</span>
          <span class="language-text">{{ currentLanguageLabel }}</span>
          <el-icon class="dropdown-icon">
            <ArrowDown />
          </el-icon>
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="zh-CN" :class="{ active: locale === 'zh-CN' }">
              🇨🇳 中文
            </el-dropdown-item>
            <el-dropdown-item command="en-US" :class="{ active: locale === 'en-US' }">
              🇺🇸 English
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <!-- 用户头像下拉菜单 -->
    <div class="app-process__user">
      <el-dropdown @command="handleCommand" trigger="click">
        <div class="user-info sa-flex sa-row-center">
          <el-avatar :size="32" :src="userInfo.avatar" class="user-avatar">
            {{ (userInfo.name || t('common.noInfo')).charAt(0).toUpperCase() }}
          </el-avatar>
          <span class="user-name mx-8px">{{ userInfo.name || t('common.noInfo') }}</span>
          <el-tag type="info" plain size="small" class="mr-10px">{{
            userInfo.roleName || t('common.noInfo')
          }}</el-tag>
          <el-icon class="dropdown-icon">
            <ArrowDown />
          </el-icon>
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="profile">
              <el-icon>
                <User />
              </el-icon>
              {{ t('taskbar.profile') }}
            </el-dropdown-item>
            <el-dropdown-item command="changePassword">
              <el-icon>
                <Lock />
              </el-icon>
              {{ t('taskbar.changePassword') }}
            </el-dropdown-item>
            <el-dropdown-item command="logout" divided>
              <el-icon>
                <SwitchButton />
              </el-icon>
              {{ t('taskbar.logout') }}
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>
</template>

<script>
import { directive } from 'v-contextmenu';

export default {
  name: 'taskbar',
  directives: {
    contextmenu: directive,
  },
};
</script>
<script setup>
import { computed, ref } from 'vue';
import sheep from '@/sheep';
import { useRouter } from 'vue-router';
import { closeTaskbar, closeOtherTaskbar } from '@/sheep/hooks/useTaskbar';
import { useModal } from '@/sheep/hooks';
import { ElMessageBox, ElMessage } from 'element-plus';
import { ArrowDown, User, SwitchButton, Lock } from '@element-plus/icons-vue';
import PasswordEdit from '@/app/admin/views/auth/admin/password.vue';
import { useTranslation } from '@/sheep/utils/i18n';
import { useI18n } from 'vue-i18n';
import { navigationMap } from '@/locales/navigation';

const { t } = useI18n();

const router = useRouter();
const selectedCM = ref(0);

// 任务栏列表
const taskbar = computed(() => sheep.$store('app').taskbar);

// 用户信息
const accountStore = sheep.$store('account');
const userInfo = computed(() => accountStore.info);

// 语言切换相关
const { locale, changeLanguage, getCurrentLanguageLabel } = useTranslation();
const currentLanguageLabel = computed(() => getCurrentLanguageLabel());

// 获取任务栏标题的国际化版本
function getTaskbarTitle(item) {
  // 根据路由名称构建 composingKey
  const composingKey = item.name;

  // 查找对应的翻译键
  const translationKey = navigationMap[composingKey];

  if (translationKey) {
    // 使用翻译，如果翻译不存在则使用原标题
    const translatedText = t(translationKey);
    if (translatedText !== translationKey) {
      return translatedText;
    }
  }

  // 如果没有找到翻译键，返回原标题
  return item.title;
}

// 监听语言变化，确保taskbar标题能够响应式更新
// 由于使用了 t() 函数，Vue的响应式系统会自动处理语言切换时的更新

// 点击菜单
function onMenu(item) {
  router.push({
    path: item.path,
    query: item.query,
  });
}

// 右键选项卡
function onCM(_, item) {
  selectedCM.value = item.name;
}

// 关闭
function onClose(name) {
  closeTaskbar(name);
}

// 关闭其他
function closeOther(name) {
  closeOtherTaskbar(name);
}

// 处理下拉菜单命令
function handleCommand(command) {
  switch (command) {
    case 'profile':
      router.push('/admin/profile');
      break;
    case 'changePassword':
      changePassword();
      break;
    case 'logout':
      logout();
      break;
  }
}

// 处理语言切换
function handleLanguageChange(command) {
  changeLanguage(command);
}

// 修改密码
function changePassword() {
  // 检查用户ID是否为1
  if (userInfo.value.id == 1) {
    ElMessage.warning(t('taskbar.superAdminCannotChangePassword'));
    return;
  }

  useModal(
    PasswordEdit,
    {
      title: t('taskbar.changePassword'),
      type: 'password',
      id: userInfo.value.id,
      name: userInfo.value.name,
    },
    {
      confirm: () => {
        // 密码修改成功后，调用注销方法退出登录
        ElMessage.success('密码修改成功，请重新登录');
        setTimeout(() => {
          accountStore.logout();
        }, 500); // 延迟1.5秒后退出登录，让用户看到成功提示
      },
    },
  );
}

// 退出登录
function logout() {
  ElMessageBox.confirm(t('taskbar.confirmLogout'), t('taskbar.logout'), {
    confirmButtonText: t('common.confirm'),
    cancelButtonText: t('common.cancel'),
    type: 'warning',
  })
    .then(() => {
      accountStore.logout();
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: t('common.cancelled'),
      });
    });
}
</script>

<style lang="scss" scoped>
.app-process {
  display: flex;
  align-items: center;
  height: 48px;
  position: relative;
  border-bottom: 1px solid var(--sa-border);

  &__scroller {
    width: 100%;
    flex: 1;
    overflow: hidden;
    padding: 0 16px;

    &::-webkit-scrollbar {
      display: none;
    }
  }

  &__language {
    flex-shrink: 0;
    padding-right: 12px;

    .language-switcher {
      .language-trigger {
        display: flex;
        align-items: center;
        cursor: pointer;
        padding: 8px 12px;
        border-radius: 6px;
        transition: all 0.3s ease;

        &:hover {
          background-color: var(--el-color-primary-light-9);
          color: var(--el-color-primary);
        }

        .language-icon {
          font-size: 16px;
          margin-right: 6px;
        }

        .language-text {
          font-size: 14px;
          font-weight: 500;
          margin-right: 4px;
        }

        .dropdown-icon {
          font-size: 12px;
          color: var(--el-text-color-regular);
          transition: transform 0.3s ease;
        }

        &:hover .dropdown-icon {
          color: var(--el-color-primary);
        }
      }

      :deep(.el-dropdown-menu__item) {
        &.active {
          color: var(--el-color-primary);
          background-color: var(--el-color-primary-light-9);
        }
      }
    }
  }

  &__user {
    flex-shrink: 0;
    padding-right: 16px;

    .user-info {
      cursor: pointer;
      padding: 8px 12px;
      border-radius: 6px;
      transition: all 0.3s ease;

      &:hover {
        background-color: var(--el-color-primary-light-9);
      }

      .user-avatar {
        margin-right: 8px;
        border: 2px solid var(--el-color-primary-light-7);
        background-color: var(--el-color-primary);
        color: white;
        font-weight: 600;
      }

      .user-name {
        margin-right: 8px;
        font-size: 14px;
        font-weight: 500;
        color: var(--el-text-color-primary);
      }

      .user-role {
        margin-right: 8px;
        background-color: var(--el-color-primary);
        border-color: var(--el-color-primary);
      }

      .dropdown-icon {
        font-size: 12px;
        color: var(--el-text-color-regular);
        transition: transform 0.3s ease;
      }

      &:hover .dropdown-icon {
        color: var(--el-color-primary);
      }
    }
  }

  &__item {
    height: 48px;
    position: relative;
    min-width: 38px;
    transition: all 0.2s;

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 50%;
      margin-left: -12px;
      height: 4px;
      border-radius: 2px;
      background: var(--t-btn-active);
    }

    &::after {
      content: '';
      position: absolute;
      top: 16px;
      left: 0;
      width: 1px;
      height: 16px;
      border-radius: 2px;
      background: var(--sa-border);
    }

    &:first-of-type {
      &::after {
        display: none;
      }
    }

    .wrap {
      min-width: 38px;
      height: 36px;
      padding: 0 12px;
      border-radius: 8px;
      font-size: 12px;
      color: var(--sa-font);
      display: flex;
      align-items: center;
      cursor: pointer;
    }

    .sa-icon {
      flex-shrink: 0;
    }

    .item-close {
      flex-shrink: 0;
      width: 0;
      height: 16px;
      overflow: hidden;
      transition: all 0.3s;

      .el-icon {
        font-size: 12px;
      }

      &:hover {
        width: 16px;
        height: 16px;
        border-radius: 50%;
        background: var(--t-bg-active);

        .close {
          color: var(--el-color-primary);
        }
      }
    }

    &:not(:hover),
    &:not(.active) {
      .text {
        min-width: 0;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
        height: 23px;
        line-height: 23px;
      }
    }

    &:hover {
      flex-shrink: 0;
      min-width: unset;

      .wrap {
        color: var(--el-color-primary);
        background: var(--t-bg-hover);
      }

      &::before {
        width: 24px;
      }

      .item-close {
        width: 16px;
        margin-left: 8px;
      }

      &:after {
        display: none;
      }

      &+.app-process__item {
        &:after {
          display: none;
        }
      }
    }

    &.active {
      flex-shrink: 0;
      min-width: unset;

      .wrap {
        color: var(--el-color-primary);
        background: var(--t-bg-hover);
      }

      &::before {
        width: 24px;
        background-color: var(--el-color-primary);
      }

      .item-close {
        width: 16px;
        margin-left: 8px;
      }

      &:after {
        display: none;
      }

      &+.app-process__item {
        &:after {
          display: none;
        }
      }
    }
  }

  @media only screen and (max-width: 768px) {
    display: none;
  }
}
</style>
