<script setup name="layout">
import { getCurrentInstance, onMounted, ref, nextTick } from 'vue'
import { infoReceived } from '@/http/apis/home'
import store from '@/store'
import { storeToRefs } from 'pinia'
import { useRouter, useRoute, onBeforeRouteUpdate } from 'vue-router'
import Cookie from 'js-cookie'
import { logout } from '@/http/apis/auth'
import moment from 'moment'
const { proxy } = getCurrentInstance(),
  { projectCount, infoList } = storeToRefs(store.countStore) || 0,
  userInfo = storeToRefs(store.userStore).userInfo || {},
  router = useRouter(),
  route = useRoute(),
  { menuArr } = storeToRefs(store.menuStore),
  sidebarMenu = ref([]),
  toRoute = name => {
    sidebarMenu.value = menuArr.value.find(i => i.name === name).children
    if (name === 'cockpits') {
      const url = router.resolve({ path: '/cockpit' })
      window.open(url.href, '_blank')
    } else { router.push({ name }) }
  },
  // 退出登录
  loginOut = async () => {
    await logout()
    Cookie.remove('token')
    localStorage.clear()
    router.push('/login')
    window.location.reload()
  },
  // 申请权限
  apply = () => {
    proxy.$messageBox.alert('请联系管理员申请权限（13588274036）', '申请权限', {
      showConfirmButton: false
    })
  },
  toNewsDetail = async ({ id, type, instanceId, projectId, meetingId }) => {
    if (type === 'PROJECT_REVIEW') {
      await infoReceived({ id })
      await store.countStore.setCountStore()
      router.push({ name: 'handleDuringExamine', query: { instanceId, projectId }})
    } else if (type === 'PROJECT_REVIEW_PASS' || type === 'PROJECT_REVIEW_REJECT') {
      await infoReceived({ id })
      await store.countStore.setCountStore()
      router.push({ name: 'projectStore' })
    } else if (type === 'PROJECT_REVIEW_BACK') {
      await infoReceived({ id })
      await store.countStore.setCountStore()
      router.push({ name: 'handleAfterGiveBack', query: { instanceId, id: projectId }})
    } else if (type === 'EXPERT_REVIEW') {
      router.push({ name: 'expertReview' })
    } else if (type === 'REVIEW_MEETING') {
      router.push({ name: 'meetingDetail', query: { id: meetingId }})
    }
  },
  // 菜单栏判断
  currentMenu = ref(),
  topMenuRef = ref(),
  hidMenuActive = ref(false),
  hidMenus = ref(),
  hidMenuRef = ref(),
  hidMenuHeight = ref(),
  hidNum = ref(),
  widthDifference = ref(0),
  // 判断隐藏菜单
  setHidMenu = async () => {
    currentMenu.value = JSON.parse(JSON.stringify(menuArr.value.filter((i) => !i.meta.hidden && i.meta.menuType === 'MENU')))
    currentMenu.value.forEach((i) => {
      i.meta.hidden = false
    })
    await nextTick()
    widthDifference.value = (currentMenu.value.length * 120) - topMenuRef.value.offsetWidth
    hidNum.value = Math.floor((((currentMenu.value.length * 120) - topMenuRef.value.offsetWidth) / 120) + 2)
    hidMenus.value = currentMenu.value.slice(-hidNum.value)
    for (let i = 1; i <= hidNum.value; i++) {
      currentMenu.value[currentMenu.value.length - i].meta.hidden = true
    }
    await nextTick()
    hidMenuHeight.value = hidMenuRef.value?.offsetHeight
  },
  moreMenuClick = () => {
    hidMenuActive.value = !hidMenuActive.value
  },
  openUrl = (url) => {
    window.open(url, '_blank')
  },
  mode = import.meta.env.MODE
onBeforeRouteUpdate(() => {
  setHidMenu()
})
onMounted(() => {
  setHidMenu()
  window.addEventListener('resize', () => {
    setHidMenu()
  })
  document.addEventListener('click', () => {
    hidMenuActive.value = false
  })
  store.countStore.setCountStore()
})
</script>
<template>
  <el-container class="h-screen overflow-hidden">
    <el-header class="header flex items-center justify-between">
      <div class=" flex items-center flex-1">
        <p class="title text-black flex-shrink-0">湖州市信息化项目管理系统</p>
        <ul ref="topMenuRef" class="flex -mx-20 header-menu flex-1">
          <template
            v-for="item in currentMenu"
            :key="item.name"
          >
            <li
              v-if="!item.meta.hidden"
              class="px-12 text-16 cursor-pointer flex items-center"
              @click="route.meta.topMenu !== item.name ? toRoute(item.name) : null"
            >
              <span
                class="flex items-center"
                :class="[
                  route.meta.topMenu === item.name
                    ? 'active-menu'
                    : 'border-transparent'
                ]"
              >
                {{ item.meta.title }}
              </span>
            </li>
          </template>
          <li
            v-if="hidNum>0"
            class="px-20 text-16 cursor-pointer whitespace-nowrap relative flex items-center"
            @click.stop="moreMenuClick"
          >
            <span
              class="flex items-center"
              :class="[
                hidMenus.some((i)=>i.name === route.meta.topMenu)
                  ? 'active-menu'
                  : 'border-transparent'
              ]"
            >
              <el-icon class="mr-8" :size="16"><More /></el-icon>
              更多菜单
            </span>
            <div
              class="absolute hidMenus w-full top-full z-10  text-center overflow-hidden"
              :style="{height:hidMenuActive?`${hidMenuHeight}px`:0,opacity:hidMenuActive?`100%`:0}"
            >
              <div ref="hidMenuRef" class="py-10">
                <p
                  v-for="i in hidMenus"
                  :key="i.name"
                  class="px-20 hidMenu"
                  @click="toRoute(i.name)"
                >
                  <span
                    class="flex items-center"
                    :class="[
                      route.meta.topMenu === i.name
                        ? 'active-menu'
                        : 'border-transparent'
                    ]"
                  >
                    {{ i?.meta?.title }}
                  </span>
                </p>
              </div>
            </div>
          </li>
        </ul>
      </div>
      <div class="flex items-center flex-shrink-0">
        <span class="text-14 cursor-pointer mr-8 pointTit" @click="openUrl(`https://xmglhejia.dsj.lishui.gov.cn/sys/thirdLogin/zzd/login?employeeCode=${userInfo.employeeCode}&employeeName==${userInfo.realName}`)">核价组件</span>
        <span class="text-14 cursor-pointer mr-8 pointTit" @click="openUrl(mode==='production'?`https://xmglchacho.dsj.lishui.gov.cn:4430/login?code=${userInfo.employeeCode}`:`http://xmcc.ningdatech.com/login?code=${userInfo.employeeCode}`)">查重组件</span>
        <el-tooltip content="操作手册" placement="bottom" effect="light">
          <svg-icon name="czsc" class="cursor-pointer text-16" />
        </el-tooltip>
        <el-badge
          :value="projectCount"
          :hidden="!projectCount"
          class="h-16 ml-12 mr-28"
        >
          <el-dropdown trigger="hover">
            <span class="el-dropdown-link">
              <svg-icon name="bell" class="cursor-pointer text-16" />
            </span>
            <template #dropdown>
              <el-dropdown-menu style="width:305px" class="newsDropDownMenu">
                <p class="text-center font-semibold border-b border-gray-300 text-14 py-9">消息通知</p>
                <el-dropdown-item
                  v-for="item in infoList?.sort((a, b) => {
                    return moment(b.createTime).valueOf() - moment(a.createTime).valueOf()
                  }).filter((item, index) => index < 5)"
                  :key="item.id"
                  @click="toNewsDetail(item)"
                >
                  <div class="w-11/12 items-center text-14"><div class="truncate" style="color: rgba(0, 0, 0, 0.65)">{{ item.content }}</div><div style="color: rgba(0, 0, 0, 0.25)">{{ item.createTime }}</div></div>
                </el-dropdown-item>
                <el-dropdown-item class="justify-center font-semibold border-t border-gray-300" style="color:rgba(0, 87, 255, 1)" @click="router.push({name:'infoCenter'})">查看更多<svg-icon name="forward" svg-class="message-icon mr-8" /></el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-badge>
        <el-popover
          placement="bottom"
          :width="200"
          trigger="click"
          popper-class="loginOutPop"
        >
          <template #reference>
            <a class="flex items-center text-[rgba(0,0,0,0.85)] text-14">
              {{ userInfo.realName }}
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </a>
          </template>
          <div>
            <div class="flex p-8">
              <span class="flex-shrink-0">当前角色：</span>
              <div>
                <p v-for="(item,index) in userInfo.userRoleInfoList" :key="index">{{ item.name }}</p>
              </div>
            </div>
            <div class="flex p-8">
              <span class="flex-shrink-0">当前区域：</span>
              <div>
                {{ userInfo.regionName }}
              </div>
            </div>
            <div class="flex p-8">
              <span class="flex-shrink-0">当前单位：</span>
              <div>
                {{ userInfo.empPosUnitName }}
              </div>
            </div>
            <el-divider style="margin: 8px 0 0 0" />
            <p v-if="userInfo.regionCode==='330000'&&userInfo.userRoleInfoList?.length<2&&userInfo.userRoleInfoList?.[0].code==='VISITOR'" class="cursor-pointer p-8 login-out" @click="apply"><el-icon><SwitchButton /></el-icon>申请权限</p>
            <p class="cursor-pointer p-8 login-out flex items-center" @click="loginOut">
              <el-icon class="mr-4"><SwitchButton /></el-icon>
              <span>退出登录</span>
            </p>
          </div>
        </el-popover>
      </div>
    </el-header>
    <router-view v-slot="{ Component }">
      <component :is="Component" />
    </router-view>
  </el-container>
</template>

<style lang="less" scoped>
.header {
  &.el-header {
    height: auto;
    background: linear-gradient(180deg, rgba(0, 127, 237, 0.40) 12.79%, rgba(0, 127, 237, 0.13) 64.55%, rgba(0, 127, 237, 0.00) 100%), #FFF;
    padding: 25px 24px 47px;
    border: 1px solid #CBE4FA;
    .title{
      color: rgba(0, 0, 0, 0.85);
      font-family: PangMenZhengDao;
      font-size: 24px;
      font-style: normal;
      font-weight: 400;
      line-height: 24px;
      margin-right: 24px;
    }

    .message-icon {
      width: 16px;
      height: 16px;
    }
    .title-icon {
      width: 300px;
      height: 32px;
    }
    .right {
      height: 32px;
      background-color: rgba(27, 113, 227, 0.4);
    }
  }
  .header-menu {
    color: rgba(0, 0, 0, 0.85);;
    font-weight: 500;
    padding-top: 4px;
    li:hover {
      //background: linear-gradient(90deg, #20DEEF 0%, #007FED 100%);
      color:#007FED;
      padding: 2px 12px;
      //background-color: rgba(0, 0, 0, 0.1);
    }
    .hidMenus {
      left: 0;
      border-radius: 4px;
      margin-top: 2px;
      color:rgba(0, 0, 0, 0.85);
      background: linear-gradient(180deg, rgba(0, 127, 237, 0.4) 12.79%, rgba(0, 127, 237, 0.13) 64.55%, rgba(0, 127, 237, 0) 100%), #FFF;
      border: 1px solid #CBE4FA;
      //background: linear-gradient(90deg, #20DEEF 0%, #007FED 100%);
      //background: linear-gradient(270deg, #1b71e3 0%, #27b0e9 100%);
      transition: all 0.2s;
      z-index: 999;
      width: auto;
      &.h-0 {
        height: 0;
      }

      &.h-100 {
        height: 200px;
      }

      .hidMenu {
        padding-top: 4px;
        padding-bottom: 4px;
        &:hover {
          color:#007FED;
        }
      }
    }
  }
    #infoDropdown {
      width: 305px;
    }
  .active-menu{
    border-radius: 13px;
    background: linear-gradient(90deg, #20DEEF 0%, #007FED 100%);
    color:#ffffff;
    padding: 2px 12px;
  }
}
.newsDropDownMenu{
  .el-dropdown-menu__item:not(.is-disabled):focus{
    background: rgba(0, 87, 255, 0.08);
  }
}

</style>
