<template>
  <guns-layout
    :menus="menus"
    :tabs="tabs"
    :collapse="collapse"
    :side-nav-collapse="sideNavCollapse"
    :body-fullscreen="bodyFullscreen"
    :show-tabs="showTabs"
    :show-footer="showFooter"
    :head-style="headStyle"
    :side-style="sideStyle"
    :layout-style="layoutStyle"
    :side-menu-style="sideMenuStyle"
    :tab-style="tabStyle"
    :fixed-body="fixedBody"
    :body-full="bodyFull"
    :logo-auto-size="logoAutoSize"
    :side-unique-open="sideUniqueOpen"
    :side-init-open-all="sideInitOpenAll"
    :project-name="projectName"
    :hide-footers="HIDE_FOOTERS"
    :hide-sidebars="HIDE_SIDEBARS"
    :repeatable-tabs="REPEATABLE_TABS"
    :home-title="HOME_TITLE || t('layout.home')"
    :home-path="HOME_PATH"
    :layout-path="LAYOUT_PATH"
    :redirect-path="REDIRECT_PATH"
    :tab-sortable="true"
    :locale="locale"
    :i18n="i18n"
    :side-default-openeds="sideDefaultOpeneds"
    @update:collapse="updateCollapse"
    @update:side-nav-collapse="updateSideNavCollapse"
    @update:body-fullscreen="updateBodyFullscreen"
    @tab-add="addPageTab"
    @tab-remove="removePageTab"
    @tab-remove-all="removeAllPageTab"
    @tab-remove-left="removeLeftPageTab"
    @tab-remove-right="removeRightPageTab"
    @tab-remove-other="removeOtherPageTab"
    @tabSortChange="setPageTabs"
    @reload-page="reloadPageTab"
    @logo-click="onLogoClick"
    @screen-size-change="screenSizeChange"
    @set-home-components="setHomeComponents"
    @tab-context-menu="onTabContextMenu"
    ref="gunsLayoutRef"
  >
    <!-- 路由出口 -->
    <router-layout />
    <!-- logo 图标 -->
    <template #logo>
      <img :src="logo" alt="logo" />
    </template>
    <!-- 顶栏左侧 -->
    <template #left>
      <div class="guns-admin-header-tool-title" v-if="currentMenuData?.title">
        <!-- 是否显示首页图标 -->
        <span class="header-icon" v-if="showHomeIcon">
          <i :class="'f-s-24 iconfont ' + currentMenuData.icon + '-p'" style="color: #6698ff" class="other"></i>
          <i class="f-s-24 iconfont icon-nav-zhuye home" style="color: #6698ff" @click="jumpHome"></i>
        </span>
        <i :class="'f-s-24 iconfont ' + currentMenuData.icon + '-p'" style="color: #6698ff" v-else></i>
        <span class="menu-title" v-else>{{ currentMenuData?.title }}</span>
      </div>
    </template>
    <!-- 顶栏菜单右侧 -->
    <template #center>
      <div class="guns-admin-header-line"></div>
      <!-- 流程发起tab栏 -->
      <div class="flow-start" v-if="showFlowStart">
        <a-tabs v-model:activeKey="flowStartTabsActiveKey" @change="flowStartTabChange">
          <a-tab-pane :key="fItem.id" :tab="fItem.name" v-for="fItem in flowStartTabList"> </a-tab-pane>
        </a-tabs>
      </div>
    </template>
    <!-- 顶栏右侧区域 -->
    <template #right="rightProp">
      <header-tools :is-mobile="rightProp.isMobile" :sideMenuStyle="sideMenuStyle"/>
    </template>
    <!-- 全局页脚 -->
    <template #footer>
      <page-footer />
    </template>
    <!-- 菜单图标 -->
    <template #icon="{ icon, item }">
      <img :src="item.appIconWrapper" alt="" v-if="item?.appId" style="width: 20px;">
      <i :class="'iconfont ' + icon" v-else></i>
    </template>
    <!-- 自定义菜单标题增加徽章、小红点 -->
    <template #title="{ item }">
      <menu-title :item="item" />
    </template>
    <template #top-title="{ item }">
      <menu-title :item="item" />
    </template>
    <template #nav-title="{ item }">
      <menu-title :item="item" />
    </template>
  </guns-layout>
</template>

<script setup>
import { computed, onMounted, ref, unref, onUnmounted, watch, nextTick, provide } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { storeToRefs } from 'pinia';
import { useI18n } from 'vue-i18n';
import { useUserStore } from '@/store/modules/user';
import { useThemeStore } from '@/store/modules/theme';
import RouterLayout from '@/components/RouterLayout/index.vue';
import HeaderTools from './components/header-tools.vue';
import PageFooter from './components/page-footer.vue';
import MenuTitle from './components/menu-title.vue';
import {
  HIDE_SIDEBARS,
  HIDE_FOOTERS,
  REPEATABLE_TABS,
  HOME_TITLE,
  HOME_PATH,
  LAYOUT_PATH,
  REDIRECT_PATH,
  I18N_ENABLE,
  WEBSOCKET_MESSAGE_TYPE
} from '@/config/setting';
import {
  addPageTab,
  removePageTab,
  removeAllPageTab,
  removeLeftPageTab,
  removeRightPageTab,
  removeOtherPageTab,
  reloadPageTab,
  setHomeComponents,
  setPageTabs
} from '@/utils/page-tab-util';
import { eachTreeData } from '@/utils/common/menu-util';
import { useSystemStore } from '@/store/modules/system';
import GunsLayout from '@/components/layout/index.vue';
import { getRouteMatched, findParentIcon } from '@/components/layout/util';
import { GunsWebsocket } from '@/utils/websocket';
import { useNoticeStore } from '@/store/modules/notice';
import { useGeneratorStore } from '@/store/modules/generator';

const { currentRoute, push } = useRouter();
const route = useRoute();
const { t, locale } = useI18n();
const userStore = useUserStore();
const themeStore = useThemeStore();
const noticeStore = useNoticeStore();
const generatorStore = useGeneratorStore();

// 页面左上角logo链接和显示的系统名称
const logo = ref('');

// 项目名
const projectName = ref(import.meta.env.VITE_APP_NAME);

// 菜单数据
const { menus } = storeToRefs(userStore);
// 加载store数据
let systemStore = useSystemStore();

// 布局风格
const {
  tabs,
  collapse,
  sideNavCollapse,
  bodyFullscreen,
  showFooter,
  headStyle,
  showTabs,
  sideStyle,
  layoutStyle,
  sideMenuStyle,
  tabStyle,
  fixedBody,
  bodyFull,
  logoAutoSize,
  sideUniqueOpen,
  sideInitOpenAll
} = storeToRefs(themeStore);

// 当前菜单数据
const currentMenuData = computed(() => {
  const { path, fullPath, meta } = unref(currentRoute);
  const { title } = getRouteMatched(path, fullPath, meta, menus.value);
  const icon = findParentIcon(menus.value, path);
  return { icon, title };
});

// ref
const gunsWebsocket = ref(null);

// ref
const gunsLayoutRef = ref(null);

// 流程发起tab列表
const flowStartTabList = ref([
  {
    name: '表单信息',
    id: '1'
  },
  {
    name: '流程图',
    id: '2'
  }
]);

// 是否显示流程发起tab栏
const showFlowStart = ref(false);

// 流程发起tab选中
const flowStartTabsActiveKey = ref('1');

// 是否显示首页图标
const showHomeIcon = ref(false);
// 首页路径
const homePath = ref('');

/* 侧栏折叠切换 */
const updateCollapse = value => {
  themeStore.setCollapse(value);
};

/* 双侧栏一级折叠切换 */
const updateSideNavCollapse = value => {
  themeStore.setSideNavCollapse(value);
};

/* 内容区域全屏切换 */
const updateBodyFullscreen = value => {
  themeStore.setBodyFullscreen(value);
};

/* logo 点击事件 */
const onLogoClick = isHome => {
  isHome || push(LAYOUT_PATH);
};

/* 监听屏幕尺寸改变 */
const screenSizeChange = () => {
  themeStore.updateScreenSize();
};

/* 页签右键菜单点击事件 */
const onTabContextMenu = ({ key, tabKey, item, active }) => {
  switch (key) {
    case 'reload': // 刷新
      reloadPageTab({
        isHome: !item,
        fullPath: item?.fullPath ?? tabKey
      });
      break;
    case 'close': // 关闭当前
      removePageTab({
        key: item?.fullPath ?? tabKey,
        active
      });
      break;
    case 'left': // 关闭左侧
      removeLeftPageTab({
        key: tabKey,
        active
      });
      break;
    case 'right': // 关闭右侧
      removeRightPageTab({
        key: tabKey,
        active
      });
      break;
    case 'other': // 关闭其他
      removeOtherPageTab({
        key: tabKey,
        active
      });
      break;
  }
};

/* 菜单标题国际化 */
const i18n = (_path, key) => {
  if (!I18N_ENABLE || !key) {
    return;
  }
  const k = 'route.' + key + '._name';
  const title = t(k);
  if (title !== k) {
    return title;
  }
};

/* 默认展开菜单 */
const sideDefaultOpeneds = computed(() => {
  const openeds = [];
  eachTreeData(menus.value, d => {
    if (d.children?.length) {
      openeds.push(d.path);
    }
  });
  return openeds;
});

onMounted(async () => {
  // 加载主题信息，logo和左上角的项目名
  let result = await systemStore.loadThemeInfo();
  logo.value = result.gunsMgrLogo;
  projectName.value = result.gunsMgrName;
  initData(route.path);
  createWebSocket();
});

// 监听路由变化
watch(
  () => route.path,
  newVal => {
    initData(newVal);
  },
  { deep: true }
);

// 监听头部菜单变化
watch(
  () => gunsLayoutRef.value?.headMenuData,
  val => {
    initData(route.path);
  },
  { deep: true }
);

//  websocket启动
const createWebSocket = async () => {
  // 注册消息通知的websocket
  try {
    gunsWebsocket.value = new GunsWebsocket(userStore.$state?.info?.websocketUrl);
    setWebSocketData();
    sendHeartbeat();
  } catch (e) {
    console.error(e);
  }
};

const setWebSocketData = (result = null) => {
  let data = {
    websocketRef: gunsWebsocket.value,
    result: result
  };
  generatorStore.setWebsocketData(data);
};

// 赋值
const sendHeartbeat = async () => {
  await gunsWebsocket.value.initWebSocket(result => {
    if (WEBSOCKET_MESSAGE_TYPE.server.SYS_NOTICE_MSG_TYPE === result?.res_data?.businessType) {
      noticeStore.addNotice(result.res_data);
    } else if (result?.businessType == 'DEVOPS_SSH_REQUEST') {
      setWebSocketData(result);
    }
  });
};

// 初始化数据
const initData = newVal => {
  showFlowStart.value = newVal == '/mid/workflow/task/start' ? true : false;
  const headerMenu = gunsLayoutRef.value.headMenuData;
  homePath.value = headerMenu[0]?.path ?? '';
};

// 流程发起tab切换
const flowStartTabChange = val => {
  generatorStore.setFlowStartActiveTab(val);
};

// 跳转项目页
const jumpHome = () => {
  push(homePath.value);
};

onUnmounted(() => {
  if (gunsWebsocket.value) {
    gunsWebsocket.value.close();
  }
});
</script>

<style lang="less">
// 侧栏菜单徽章样式，定位在右侧垂直居中并调小尺寸
.guns-menu-badge {
  position: absolute;
  top: 50%;
  right: 14px;
  line-height: 1;
  margin-top: -9px;
  font-size: 0;

  .ant-badge-count {
    height: 18px;
    line-height: 18px;
    border-radius: 9px;
    box-shadow: none;
    min-width: 18px;
    padding: 0 4px;
  }

  .ant-scroll-number-only {
    height: 18px;

    & > p.ant-scroll-number-only-unit {
      height: 18px;
    }
  }
}

// 父级菜单标题中右侧多定位一点，避免与箭头重合
.ant-menu-submenu-title > .ant-menu-title-content .guns-menu-badge {
  right: 36px;
}

// 折叠悬浮中样式调整
.ant-menu-submenu-popup {
  .ant-menu-submenu-title > .ant-menu-title-content .guns-menu-badge {
    right: 30px;
  }
}

// 顶栏菜单标题中样式调整
.guns-admin-header-nav > .ant-menu {
  & > .ant-menu-item,
  & > .ant-menu-submenu > .ant-menu-submenu-title {
    & > .ant-menu-title-content .guns-menu-badge {
      position: static;
      right: auto;
      top: auto;
      display: inline-block;
      vertical-align: 5px;
      margin: 0 0 0 4px;
    }
  }
}

// 双侧栏时一级侧栏菜单中样式调整，定位在右上角
.guns-admin-sidebar-nav-menu > .ant-menu {
  & > .ant-menu-item,
  & > .ant-menu-submenu > .ant-menu-submenu-title {
    & > .ant-menu-title-content .guns-menu-badge {
      top: 0;
      right: 0;
      margin: 0;
    }
  }
}

// 菜单折叠后在 tooltip 中不显示徽章
.ant-tooltip-inner .guns-menu-badge {
  display: none;
}

// 分组菜单标题
.ant-menu-item-group-title {
  position: relative;
  font-size: 12px !important;
  background: rgba(0, 0, 0, 0.02);
  padding-top: 4px !important;
  padding-bottom: 4px !important;
}
</style>
<style scoped lang="less">
.flow-start {
  :deep(.ant-tabs-nav) {
    margin: 0 !important;
  }

  :deep(.ant-tabs-tab) {
    font-size: 15px !important;
    font-weight: 400;
    padding: 15px 16px !important;
  }

  :deep(.ant-tabs-top > .ant-tabs-nav::before) {
    border-bottom: 0;
  }
}

.home {
  display: none;
}

.header-icon {
  padding-top: 6px;

  &:hover {
    .other {
      display: none;
    }

    .home {
      display: inline-block;
    }
  }
}
</style>
