<template>
  <div>
    <div class="layout-header">
      <!--顶部菜单-->
      <div
        class="layout-header-left"
        v-if="navMode === 'horizontal' || (navMode === 'horizontal-mix' && mixMenu)"
      >
        <div class="logo" v-if="navMode === 'horizontal'">
          <img :src="websiteConfig.logo" alt="" />
          <h2 v-show="!collapsed" class="title">{{ '内容管理' }}</h2>
        </div>
        <!-- v-model:collapsed="collapsed" -->
        <AsideMenu v-model:location="getMenuLocation" :inverted="getInverted" mode="horizontal" />
      </div>
      <!--左侧菜单-->
      <div class="layout-header-left" v-else>
        <!-- 菜单收起 -->
        <!-- <div
          class="ml-1 layout-header-trigger layout-header-trigger-min"
          @click="() => $emit('update:collapsed', !collapsed)"
        >
          <n-icon size="18" v-if="collapsed">
            <MenuUnfoldOutlined />
          </n-icon>
          <n-icon size="18" v-else>
            <MenuFoldOutlined />
          </n-icon>
        </div> -->
        <!-- 刷新 -->
        <div
          class="mr-1 layout-header-trigger layout-header-trigger-min"
          v-if="headerSetting.isReload"
          @click="reloadPage"
        >
          <n-icon size="18">
            <ReloadOutlined />
          </n-icon>
        </div>
        <!-- 面包屑 -->
        <n-breadcrumb v-if="crumbsSetting.show">
          <template v-for="routeItem in breadcrumbList" :key="routeItem.name">
            <n-breadcrumb-item v-if="routeItem.meta.title" :clickable="false">
              <!-- <n-dropdown
                v-if="routeItem.children.length"
                :options="routeItem.children"
                @select="dropdownSelect"
              >
                <span class="link-text">
                  <component
                    v-if="crumbsSetting.showIcon && routeItem.meta.icon"
                    :is="routeItem.meta.icon"
                  />
                  {{ routeItem.meta.title }}
                </span>
              </n-dropdown> -->
              <span class="link-text">
                <component
                  v-if="crumbsSetting.showIcon && routeItem.meta.icon"
                  :is="routeItem.meta.icon"
                />
                {{ routeItem.meta.title }}
              </span>
            </n-breadcrumb-item>
          </template>
        </n-breadcrumb>
      </div>
      <div class="layout-header-right">
        <div
          class="layout-header-trigger layout-header-trigger-min"
          v-for="item in iconList"
          :key="item.icon.name"
        >
          <n-tooltip placement="bottom">
            <template #trigger>
              <n-icon size="18">
                <component :is="item.icon" v-on="item.eventObject || {}" />
              </n-icon>
            </template>
            <span>{{ item.tips }}</span>
          </n-tooltip>
        </div>
        <!--切换全屏-->
        <!-- <div class="layout-header-trigger layout-header-trigger-min">
          <n-tooltip placement="bottom">
            <template #trigger>
              <n-icon size="24">
                <component :is="fullscreenIcon" @click="toggleFullScreen" />
              </n-icon>
            </template>
            <span>全屏</span>
          </n-tooltip>
        </div> -->
        <!-- 消息聊天 -->
        <!-- <div class="layout-header-trigger layout-header-trigger-min" @click="openMessage">
          <n-tooltip placement="bottom">
            <template #trigger>
              <n-badge :value="noReadNum" :dot="noReadNum > 0">
                <n-icon size="24" color="#333">
                  <MessageOutlined />
                </n-icon>
              </n-badge>
            </template>
            <span>点击打开聊天</span>
          </n-tooltip>
        </div> -->
        <!-- 个人中心 -->
        <div class="layout-header-trigger layout-header-trigger-min">
          <n-dropdown trigger="hover" @select="avatarSelect" :options="avatarOptions">
            <div class="avatar">
              <n-avatar round :src="avatar">
                <!-- {{ username }}
                <template #icon>
                  <UserOutlined />
                </template> -->
              </n-avatar>
            </div>
          </n-dropdown>
        </div>
        <!--设置-->
        <!-- <div class="layout-header-trigger layout-header-trigger-min" @click="openSetting">
          <n-tooltip placement="bottom-end">
            <template #trigger>
              <n-icon size="18" style="font-weight: bold">
                <SettingOutlined />
              </n-icon>
            </template>
            <span>项目配置</span>
          </n-tooltip>
        </div> -->
      </div>
    </div>

    <!--项目配置-->
    <!-- <ProjectSetting ref="drawerSetting" /> -->

    <UserSetting ref="userSettingRef" @updateInfo="updateInfo" />

    <UpdatePassword ref="updatePasswordRef" />
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  reactive,
  toRefs,
  ref,
  computed,
  unref,
  onMounted,
  onBeforeMount
} from 'vue'
import { useRouter, useRoute } from 'vue-router'
import components from './components'
import { NDialogProvider, useDialog, useMessage, NModal } from 'naive-ui'
import { TABS_ROUTES } from '@/store/mutation-types'
import { useUserStore } from '@/store/modules/user'
import { useTabsViewStore } from '@/store/modules/tabsView'
// import ProjectSetting from './ProjectSetting.vue'
import { AsideMenu } from '@/layout/components/Menu'
import { useProjectSetting } from '@/hooks/setting/useProjectSetting'
import { websiteConfig } from '@/config/website.config'
import UserSetting from './UserSetting.vue'
import UpdatePassword from './UpdatePassword.vue'

export default defineComponent({
  name: 'PageHeader',
  components: {
    ...components,
    NDialogProvider,
    // ProjectSetting,
    AsideMenu,
    NModal,
    UserSetting,
    UpdatePassword
    // ImChat
  },
  props: {
    collapsed: {
      type: Boolean
    },
    inverted: {
      type: Boolean
    }
  },
  setup(props) {
    document.title = websiteConfig.title
    const userStore = useUserStore()
    const tabsViewStore = useTabsViewStore()
    const message = useMessage()
    const showImChat = ref(false)

    const dialog = useDialog()
    const { getNavMode, getNavTheme, getHeaderSetting, getMenuSetting, getCrumbsSetting } =
      useProjectSetting()

    const { nickname, avatar, imToken } = userStore?.info || {}

    // const drawerSetting = ref()

    const state = reactive({
      username: nickname || '',
      avatar: avatar || ('' as any),
      fullscreenIcon: 'FullscreenOutlined',
      navMode: getNavMode,
      navTheme: getNavTheme,
      headerSetting: getHeaderSetting,
      crumbsSetting: getCrumbsSetting,
      visiableUserSetting: false
    })

    const getInverted = computed(() => {
      const navTheme = unref(getNavTheme)
      return ['light', 'header-dark'].includes(navTheme) ? props.inverted : !props.inverted
    })

    const mixMenu = computed(() => {
      return unref(getMenuSetting).mixMenu
    })

    const getChangeStyle = computed(() => {
      const { collapsed } = props
      const { minMenuWidth, menuWidth }: any = unref(getMenuSetting)
      return {
        left: collapsed ? `${minMenuWidth}px` : `${menuWidth}px`,
        width: `calc(100% - ${collapsed ? `${minMenuWidth}px` : `${menuWidth}px`})`
      }
    })

    const getMenuLocation = computed(() => {
      return 'header'
    })

    const router = useRouter()
    const route = useRoute()

    const generator: any = (routerMap: any) => {
      return routerMap.map((item: any) => {
        const currentMenu = {
          ...item,
          label: item.meta.title,
          key: item.name,
          disabled: item.path === '/'
        }
        // 是否有子菜单，并递归处理
        if (item.children && item.children.length > 0) {
          // Recursion
          currentMenu.children = generator(item.children, currentMenu)
        }
        return currentMenu
      })
    }

    const breadcrumbList = computed(() => {
      return generator(route.matched)
    })

    const dropdownSelect = (key: any) => {
      router.push({ name: key })
    }

    // 刷新页面
    const reloadPage = () => {
      router.push({
        path: '/redirect' + unref(route).path,
        query: unref(route).query
      })
    }

    // 退出登录
    const doLogout = () => {
      dialog.info({
        title: '提示',
        content: '您确定要退出登录吗',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
          userStore.logout().then(() => {
            message.success('成功退出登录')
            // 移除标签页
            localStorage.removeItem(TABS_ROUTES)
            tabsViewStore.closeAllTabs()
            router
              .replace({
                name: 'Login'
              })
              .finally(() => location.reload())
          })
        },
        onNegativeClick: () => {}
      })
    }

    // 切换全屏图标
    const toggleFullscreenIcon = () =>
      (state.fullscreenIcon =
        document.fullscreenElement !== null ? 'FullscreenExitOutlined' : 'FullscreenOutlined')

    // 监听全屏切换事件
    document.addEventListener('fullscreenchange', toggleFullscreenIcon)

    // 全屏切换
    const toggleFullScreen = () => {
      if (!document.fullscreenElement) {
        document.documentElement.requestFullscreen()
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen()
        }
      }
    }

    // 图标列表
    const iconList = [] as any
    const avatarOptions = [
      {
        label: '个人设置',
        key: 1
      },
      {
        label: '修改密码',
        key: 3
      },
      {
        label: '退出登录',
        key: 2
      }
    ]

    //头像下拉菜单
    const avatarSelect = (key: any) => {
      switch (key) {
        case 1:
          openUserSetting()
          break
        case 2:
          doLogout()
          break
        case 3:
          openUpdatePassword()
          break
      }
    }

    // function openSetting() {
    //   const { openDrawer } = drawerSetting.value
    //   openDrawer()
    // }
    const userSettingRef = ref()

    const openUserSetting = () => {
      const { openModal } = userSettingRef.value
      openModal()
    }
    const updateInfo = () => {
      const { avatar } = userStore?.info || {}
      state.avatar = avatar
    }

    const updatePasswordRef = ref()
    const openUpdatePassword = () => {
      const { openModal } = updatePasswordRef.value
      openModal()
    }

    return {
      ...toRefs(state),
      iconList,
      showImChat,
      toggleFullScreen,
      doLogout,
      route,
      dropdownSelect,
      avatarOptions,
      getChangeStyle,
      avatarSelect,
      breadcrumbList,
      reloadPage,
      // drawerSetting,
      // openSetting,
      getInverted,
      getMenuLocation,
      mixMenu,
      websiteConfig,
      userSettingRef,
      updateInfo,
      updatePasswordRef
    }
  }
})
</script>

<style lang="less" scoped>
.layout-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
  height: @header-height;
  box-shadow: 0 1px 4px rgb(0 21 41 / 8%);
  transition: all 0.2s ease-in-out;
  width: 100%;
  z-index: 11;

  &-left {
    display: flex;
    align-items: center;

    .logo {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 64px;
      line-height: 64px;
      overflow: hidden;
      white-space: nowrap;
      padding-left: 10px;

      img {
        width: auto;
        height: 32px;
        margin-right: 10px;
      }

      .title {
        margin-bottom: 0;
      }
    }

    ::v-deep(.ant-breadcrumb span:last-child .link-text) {
      color: #515a6e;
    }

    .n-breadcrumb {
      display: inline-block;
    }

    &-menu {
      color: var(--text-color);
    }
  }

  &-right {
    display: flex;
    align-items: center;
    margin-right: 20px;

    .avatar {
      display: flex;
      align-items: center;
      height: 64px;
    }

    > * {
      cursor: pointer;
    }
  }

  &-trigger {
    display: inline-block;
    width: 64px;
    height: 64px;
    text-align: center;
    cursor: pointer;
    transition: all 0.2s ease-in-out;

    .n-icon {
      display: flex;
      align-items: center;
      height: 64px;
      line-height: 64px;
    }

    &:hover {
      background: hsla(0, 0%, 100%, 0.08);
    }

    .anticon {
      font-size: 16px;
      color: #515a6e;
    }
  }

  &-trigger-min {
    width: auto;
    padding: 0 12px;
  }

  ::v-deep(.n-badge.n-badge--dot .n-badge-sup) {
    top: 18px !important;
  }

  ::v-deep(.n-badge .n-badge-sup) {
    bottom: 100% !important;
  }
}

.layout-header-light {
  background: #fff;
  color: #515a6e;

  .n-icon {
    color: #515a6e;
  }

  .layout-header-left {
    ::v-deep(.n-breadcrumb .n-breadcrumb-item:last-child .n-breadcrumb-item__link) {
      color: #515a6e;
    }
  }

  .layout-header-trigger {
    &:hover {
      background: #f8f8f9;
    }
  }
}

.layout-header-fix {
  position: fixed;
  top: 0;
  right: 0;
  left: 200px;
  z-index: 11;
}

.imGroupContainer,
.container {
  background-color: #fff;
  width: 968px;
  height: 640px;
  border-radius: 15px;
}

.hideModal {
  visibility: hidden;
}
</style>
