<template>
  <div id="layout-header">
    <!-- left -->
    <div class="header-left">
      <div class="header-logo">
        <img class="logo-icon" src="@/assets/image/logo.png" alt="" />
        <img
          class="logo-text"
          src="@/assets/image/appsketch_works.png"
          alt=""
        />
      </div>
      <div
        v-if="isGoBackWorkspace"
        class="workspace-dropdown"
        @click="gotoWorkspace"
      >
        <div class="workspace-dropdown-button">
          <i class="asw-icon icon-a-backtoworkspace"></i>
          {{ t('overall.goBackWorkspace') }}
        </div>
      </div>

      <el-dropdown
        v-else-if="currentRoute.name != 'environment_start'"
        class="workspace-dropdown"
        placement="bottom-start"
      >
        <div class="workspace-dropdown-button">
          {{ workspace.name }}
          <el-icon class="el-icon--right"><arrow-down /></el-icon>
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item
              v-for="item in permissions"
              :key="item.workspace.id"
              :class="{ 'primary-color': workspace.id == item.workspace.id }"
              @click="workspaceChange(item.workspace.id)"
            >
              <span>{{ item.workspace.name }}</span>
            </el-dropdown-item>
            <div v-has="'workspace_add'">
              <el-dropdown-item>
                <el-icon class="primary-color" :size="16">
                  <CirclePlus />
                </el-icon>
                <span>{{ t('overall.add_workspace') }}</span>
              </el-dropdown-item>
            </div>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <!-- right -->
    <div class="header-right">
      <el-button
        v-if="currentRoute.name == 'environment_start'"
        type="danger"
        size="large"
        @click="desktopEnd"
      >
        <i class="asw-icon icon-End" style="margin-right: 6px"></i>
        <span>{{ t('environment.end') }}</span>
      </el-button>
      <template v-else>
        <el-switch
          class="theme-switch"
          :width="56"
          size="large"
          v-model="isLight"
          inline-prompt
          :active-icon="Sunny"
          :inactive-icon="Moon"
          @change="themeChange"
        >
        </el-switch>
        <el-dropdown
          class="avatar-dropdown"
          placement="bottom-end"
          popper-class="avatar-popper"
        >
          <div class="avatar-dropdown-personal">
            <i class="asw-icon icon-Personal"></i>
            <el-icon class="el-icon--right"><arrow-down /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="gotoProfileManage" >
                <div>
                  <p class="profile-text">{{ t('overall.profile') }}</p>
                  <p class="profile-info">{{ userInfo.name }}</p>
                </div>
              </el-dropdown-item>
              <el-dropdown-item @click="logout">
                <i class="asw-icon icon-sign-out"></i>
                <span class="profile-text">{{ t('overall.sign_out') }}</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <el-dropdown
          class="headerMore-dropdown"
          trigger="click"
          placement="bottom-end"
          popper-class="headerMore-popper"
        >
          <button class="headerMore-dropdown-button">
            <i class="asw-icon icon-More"></i>
          </button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>
                <div class="headerMore-list">
                  <li
                    class="headerMore-item"
                    :class="{ active: currentRoute.name == 'users' }"
                    @click="gotoUserManage"
                    v-if="userInfo.accessLevel === administrator"
                  >
                    <i class="asw-icon icon-Users"></i>
                    <span>{{ t('overall.users') }}</span>
                  </li>
                  <li class="headerMore-item">
                    <el-icon><Setting /></el-icon>
                    <span>{{ t('overall.about') }}</span>
                  </li>
                </div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
    </div>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router';
import { Sunny, Moon } from '@element-plus/icons-vue';
import { toRefs, ref, onBeforeMount, computed, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useSystemStore } from '@/store/index';
import { useTheme } from '@/hooks/useTheme';
import { logoutApi } from '@/axios/api';
import { logoutClear, isAdministrator } from '@/utils/index';
import { ElMessage } from 'element-plus';
import { setWorkspace } from '@/router/permissions';
import { goHome } from '@/utils/index';
import { administrator, userMenuType, profileMenuType, normalMenuType } from '@/utils/constants';
import mitter from '@/utils/mitter';

const router = useRouter();

const emit = defineEmits([
  'refreshStart',
  'refreshEnd',
  'goBackWorkspace',
  'gotoUserManage',
  'gotoProfileManage']);

const { t } = useI18n();
const systemStore = useSystemStore();

const currentRoute = computed(() => {
  return router.currentRoute.value;
});

// 当前workspace
const workspace = computed(() => {
  return systemStore.workspace;
});
// 所有权限
const permissions = computed(() => {
  return systemStore.permissions;
});

const desktopEnd = () => {
  mitter.emit('desktopEnd');
};

// 切换workspace
const workspaceChange = async (id) => {
  if (id != workspace.value.id) {
    const data = permissions.value.find((item) => item.workspace.id == id);
    setWorkspace(data);

    emit('refreshStart');
    // 切换workspace跳转到首页
    await goHome();
    // 刷新页面 否则v-has自定义指令不更新
    emit('refreshEnd');
  }
};

// 主题
const { themeSet } = useTheme();
const isLight = ref(systemStore.theme === 'light');
const themeChange = (val) => {
  themeSet(val ? 'light' : 'dark');
};

// 退出登录
const logout = async () => {
  const res = await logoutApi();
  logoutClear();
  ElMessage.success(t('message.sign_out_success'));
};

//workspace页面和user页面相互切换控制
const isGoBackWorkspace = ref(false);
const curMenuType = ref(normalMenuType);
const gotoUserManage = () => {
  isGoBackWorkspace.value = true;
  curMenuType.value = userMenuType;
  emit('gotoUserManage');
};

const gotoWorkspace = () => {
  isGoBackWorkspace.value = false;
  curMenuType.value = normalMenuType;
  emit('goBackWorkspace');
};

//workspace页面和Enviroment页面相互切换控制
const gotoProfileManage = () => {
  isGoBackWorkspace.value = true;
  curMenuType.value = profileMenuType;
  emit('gotoProfileManage');
};

// 用户信息
const userInfo = ref({});
onBeforeMount(() => {
  let info = localStorage.getItem('asg-userInfo');
  try {
    userInfo.value = JSON.parse(info);
  } catch (error) {}
});

watch(
  () => router.currentRoute.value,
  (value) => {
    if (
      (isAdministrator && (router.currentRoute.value.path === '/users' || router.currentRoute.value.path.startsWith('/users/'))) ||
      router.currentRoute.value.path === '/profile' ||
      router.currentRoute.value.path.startsWith('/profile/')
    ) {
      isGoBackWorkspace.value = true;
    } else {
      isGoBackWorkspace.value = false;
    }
  },
  { immediate: true }
);
</script>

<style lang="scss" scoped>
#layout-header {
  width: 100%;
  height: 70px;
  background-color: var(--background_secondary);
  padding: 14px 32px;
  box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.25);
  display: flex;
  align-items: center;
  justify-content: space-between;
  .header-left {
    align-items: center;
    display: flex;
    .header-logo {
      display: flex;
      align-items: center;
      gap: 15px;
      .logo-icon {
        width: 45px;
      }
      .logo-text {
        height: 22px;
      }
    }
    .workspace-dropdown {
      margin-left: 20px;
      .workspace-dropdown-button {
        outline: none;
        cursor: pointer;
        display: inline-flex;
        justify-content: center;
        align-items: center;
        gap: 10px;
        background: #e0eaff;
        border: 1px solid var(--primary);
        border-radius: 4px;
        color: var(--primary);
        height: 27px;
        padding: 0 8px;
      }
    }
    #header-search {
      margin-left: 60px;
      .el-input {
        width: 320px;
      }
    }
  }

  .header-right {
    display: flex;
    align-items: center;
    gap: 20px;
    :deep(.theme-switch) {
      .el-icon {
        font-size: 20px !important;
        color: #fac302 !important;
      }
      .el-switch__core {
        border: none;
        background: #636363;
      }
      .el-icon {
        margin-left: 4px;
      }
      &.is-checked {
        .el-switch__core {
          background: #e8e8e8;
        }
        .el-icon {
          margin-left: 0px;
        }
      }
    }
    .avatar-dropdown {
      .avatar-dropdown-personal {
        outline: none;
        cursor: default;
        display: flex;
        align-items: center;
        gap: 0 5px;
        i.icon-Personal {
          width: 36px;
          height: 36px;
          border-radius: 50%;
          background: #e0eaff;
          color: var(--primary);
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
    }
    .headerMore-dropdown {
      .headerMore-dropdown-button {
        background: transparent;
        border: none;
        border-radius: 4px;
        box-shadow: none;
        cursor: pointer;
        outline: none;
        color: var(--text);
        width: 28px;
        height: 28px;
        display: flex;
        justify-content: center;
        align-items: center;
        i {
          font-size: 18px;
        }
        &:hover {
          color: var(--primary);
        }
        &[aria-expanded='true'] {
          background: #f0f0f0;
          color: var(--primary);
        }
      }
    }
  }
}
</style>
<style lang="scss">
.avatar-popper {
  .profile-text {
    font-size: 14px;
    color: var(--text);
  }
  i {
    font-size: 18px;
    color: var(--text);
  }
  .profile-info {
    color: var(--text_secondary);
    font-size: 13px;
  }
  .el-dropdown-menu__item {
    padding: 10px 16px;
    &:last-of-type {
      border-top: 1px solid #ceced2;
    }
  }
}

.headerMore-popper {
  .el-dropdown-menu {
    padding: 0;
    .el-dropdown-menu__item {
      padding: 0;
      &:hover,
      &:focus {
        background-color: unset;
      }
    }
    .headerMore-list {
      padding: 8px;
      display: flex;
      gap: 0 8px;
      justify-content: center;
      max-width: 224px;
      flex-wrap: wrap;
    }
    .headerMore-item {
      width: 64px;
      height: 64px;
      align-items: center;
      border-radius: 4px;
      color: var(--text);
      display: flex;
      flex-direction: column;
      gap: 4px 0;
      justify-content: center;
      transition: all 0.2s ease-in;
      cursor: pointer;
      .el-icon {
        font-size: 20px;
      }
      span {
        font-size: 14px;
      }
      &:hover {
        color: var(--primary);
      }
      &.active {
        background: #f0f0f0;
        color: var(--primary);
      }
    }
  }
}
</style>
