<template>
  <div class="app-header">

    <div class="fixed-inner">

      <div class="nav-lft">
        <template v-for="item in navs.slice(0, -1)" :key="item.icon">
          <NavItem v-model="act" v-bind="{ xnav: item, iconMap }"  />
        </template>
      </div>

      <div class="title"></div>

      <div class="nav-rgt">
        <template v-for="item in navs.slice(-1)" :key="item.icon">
          <NavItem v-model="act" v-bind="{ xnav: item, iconMap }" />
        </template>

        <div class="after">

          <!--<div @click="modeChange" class="mode" v-if='menus.includes(2) '>-->
          <div @click="modeChange" class="mode" v-if='false'>
            <div class="icon"></div>
            <div class="text">{{ appMode }}隧道</div>
          </div>

          <Timer />

          <div class="user-info">
            <el-dropdown ref="dropdownRef" trigger="click" :teleported="false">
              <div class="name c-#ffffff font-size-4 cursor-pointer">
                {{ userStore.getUser.nickname }}
              </div>

              <template #dropdown>
                <div class="name_submenu">
                  <!--<div :class="['x-submenu']" @click="navChange(1)"> 菜单配置 </div>-->
                  <div :class="['x-submenu']" @click="navChange(2)"> 退出系统 </div>
                </div>
              </template>
            </el-dropdown>

            <div @click="loginOut" class="exit"></div>
          </div>
        </div>
      </div>

      <menusConfig ref='menusref' />

    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onBeforeMount, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStoreWithOut } from '@/store/modules/user'
import { useAppStoreWithOut } from '@/store/modules/app'
import { getOrgainzations } from '@/api/system/role'
import {
  getDetails,
} from '@/api/system/role'
import menusConfig from './components/menusConfig.vue'
import Timer from '../Timer/index.vue'
import NavItem from './components/NavItem.vue'
import { CACHE_KEY, useCache, deleteUserCache } from '@/config/hooks/web/useCache'
const { wsCache } = useCache()

// 图标库
const iconMap = reactive({})

// 权限菜单
const menus = ref([])

const navs_2d = ref([
  { name: '首页', key: 'home', icon: 'nav_1', code: '101144',value:1 },
  { name: '留存车辆', key: 'remain', icon: 'nav_2', code: '101146',value:3 },
  { name: '事件检测', key: 'event', icon: 'nav_3', code: '101147',value:4 },
  { name: '历史记录', key: 'history', icon: 'nav_4', code: '101148' ,value:5},
  {
    name: '系统设置',
    key: 'system',
    icon: 'nav_5',
    code: '101149',
    value:6,
    subs: [
      { name: '设施设备配置', key: 'tunnel-set' },
      { name: '组织管理', key: 'organization' },
      { name: '角色管理', key: 'role' },
      { name: '用户管理', key: 'user' },
      { name: '字典管理', key: 'dict' },
    ]
  }
])

const navs_3d = ref([
  { name: '首页', key: '3d-model', icon: 'nav_1',value:1 },
  {
    name: '系统设置',
    key: 'system',
    icon: 'nav_5',
    value:6,
    subs: [
      { name: '设施设备配置', key: 'tunnel-set' },
      { name: '组织管理', key: 'organization' },
      { name: '角色管理', key: 'role' },
      { name: '用户管理', key: 'user' },
      { name: '字典管理', key: 'dict' },
    ]
  }
])

const navs = computed(() => {
  if (appStore.getMode === '2D') {
    const role = userStore.getRoles[0]
    if (role === 'super_admin') {
      return navs_2d.value
    }
    
    return navs_2d.value.filter(item => menus.value.includes(item.value))
   
  }

  if (appStore.getMode === '3D') {
    // return navs_3d.value
    return navs_3d.value.filter(item => menus.value.includes(item.value))

  }

})

const menusref = ref(null)

const act = ref('home')

const router = useRouter()
const route = useRoute()
const userStore = useUserStoreWithOut()
const appStore = useAppStoreWithOut()

// 模式
const appMode = computed(() => {
  return appStore.getMode
})

// 模式手动切换
const modeChange = () => {
  if (appMode.value === '2D') {
    appStore.setMode('3D')
    router.push({
      path: '3d-model'
    })
  } else {
    appStore.setMode('2D')
    router.push({
      path: 'home'
    })
  }
}

// 是否被选中
const isAct = (item) => {
  if (item.subs) {
    return item.subs.some((item) => item.key === act.value)
  } else {
    return item.key === act.value
  }
}

// 导航切换
const navChange = (item) => {
  if (item == 2) {
    loginOut()
  }
  if(item == 1){
    menusref.value.diaOpen(1, 1)
  }
}

// 退出登录
const loginOut = async () => {
  await userStore.loginOut().catch(() => {})
  deleteUserCache() // 清空用户缓存
  router.replace('/login')
}

// 系统模型初始化
const modeInit = (name) => {
  const target = name.includes('3d-mode') ? '3D' : '2D'
  if (target !== appStore.getMode) {
    appStore.setMode(target)
  }
}

// 图标加载

watch(
  () => route.fullPath,
  () => {

    const current = router.currentRoute.value.path

    modeInit(current)

    const keys = navs.value
      .map((item) => {
        if (item.subs) {
          return [item.key, item.subs.map((xsub) => xsub.key)]
        } else {
          return item.key
        }
      })
      .flat(Infinity)

    const key = keys.find((key) => {
      return current.includes(key) || key === route.query.from
    })

    act.value = key as any

    // 未开通权限不可访问
    if (!key) {
      appStore.setMode('2D')
      router.push({
        path: 'home'
      })
    }

  },
  {
    immediate: true
  }
)

const setAuths = async () => {
  const role = userStore.getRoles[0]
  console.log(role,'ccc')
  const res = await getOrgainzations({ code: role })
    const resList = await getDetails({ id: res.list[0].id || '' })
  menus.value = resList.menuIds || []

}

onBeforeMount(() => {
  // setAuths()
  navs_2d.value.filter(item => item.icon).forEach((item) => {
    ;(async (xnav) => {
      const res = await import(`../../assets/images/home/${xnav.icon}.png`)
      ;iconMap[xnav.icon] = {
        backgroundImage: `url(${res.default})`,
        backgroundSize: 'cover'
      }
    })(item)
  })
})

onMounted(async () => {
  await userStore.setUserInfoAction()
  setAuths()

  // console.log('user: ', userStore.getRoles)

})

</script>

<style lang="scss" scoped>
$url-home: '@/assets/images/home/';
$url-common: '@/assets/images/common/';

.app-header {
  // height: 100px;
  position: relative;
  z-index: 6;
}

.fixed-inner {
  height: 100px;
  padding: 0 45px;
  // overflow: hidden;
  // position: fixed;
  // top: 0;
  // left: 0;
  width: 100%;
  box-sizing: border-box;
  z-index: 4;
  background-image: url($url-home + 'header.png');
  background-size: cover;
  display: flex;
  justify-content: space-between;
    :deep(.el-form-item__label) {
    color: #ffffff;
    width: 0px;
    overflow:hidden;
  }
  :deep(.el-form-item__content) {
    width: 447px;
  }
  .title {
    width: 417px;
    height: 50px;
    margin-top: 16px;
    background-image: url($url-home + 'title.png');
    background-size: cover;
  }

  .nav-lft,
  .nav-rgt {
    display: flex;
    justify-content: space-between;
    color: white;
    height: 36px;
    margin-top: 26px;
    width: 540px;
  }

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

  .after {
    display: flex;
    align-items: center;
    margin-left: auto;

    .mode {
      display: flex;
      align-items: center;
      font-size: 14px;
      padding: 5px 10px;
      background: rgba(15, 96, 219, 0.5);
      border-radius: 4px;
      margin-right: 10px;
      cursor: pointer;
      .icon {
        width: 14px;
        height: 14px;
        background: url($url-common + 'sys-trans.png') no-repeat;
        background-size: 100% auto;
        background-position: center;
        margin-right: 4px;
      }
    }

    .user-info {
      margin-left: 10px;
      display: flex;
      align-items: center;
      .exit {
        width: 16px;
        height: 16px;
        background-image: url($url-common + 'exit.png');
        background-size: cover;
        margin-left: 8px;
        cursor: pointer;
      }
      .name{
        white-space: nowrap;
        overflow: hidden;
      text-overflow: ellipsis;
      max-width:70px;
      }
    }
  }
}
.name_submenu {
  padding: 8px 0;
  .x-submenu {
    padding: 6px 20px;
    white-space: nowrap;
    cursor: pointer;
    color: white;
    font-size: 16px;

    &.act {
      color: #00aeff;
    }

    &:not(.act):hover {
      background: rgba(124, 213, 255, 0.15);
    }
  }
}
</style>
