<template>
  <div class="es-main">
    <div
      class="es-simplicitytop-nav"
      :style="{ backgroundImage: 'url(' + topBg + ')' }"
    >
      <div class="es-simplicitytop-nav-left">
        <img class="es-simplicitytop-logo" v-if="topLogo" :src="topLogo" />
      </div>
      <div class="es-simplicitytop-nav-right">
        <handler
          slot="append"
          v-bind="handleConfig"
          :show-title-type="showTitleType"
          :data="_handleDatas"
          :nums="handleNums"
          :user="user"
          @click="handleClick"
        ></handler>
      </div>
    </div>
    <div class="es-simplicitytop-main">
      <div class="es-simplicitytop-main-left">
        <div class="es-simplicitytop-main-left-user">
          <el-popover
            class="es-simplicity-user-popover"
            placement="right"
            width="360"
            trigger="click"
          >
            <!-- 用户信息 -->
            <user
              ref="user"
              :user="user"
              :notifyList="notifyList"
              :notify="notify"
              :contents="userInfoContents"
              @success="handleSuccess"
              @change="handleChangeConfig"
              @close="handlerClose"
            ></user>
            <div slot="reference" class="es-simplicity-pannel-user">
              <!-- <avatar :user="user" :size="56" :show-name="true"></avatar> -->
              <div class="es-simplicitytop-greeting">
                {{ user.username || '-' }}，{{ greeting }}
              </div>
              <!-- <div class="es-simplicity-username"></div> -->
            </div>
            <!-- 用户信息 end -->
          </el-popover>
        </div>
        <div class="es-simplicitytop-menu-item" style="padding-right: 16px">
          <div class="es-simplicitytop-menu-title">
            <span class="es-simplicitytop-menu-name">我的提醒</span>
            <span class="es-simplicitytop-menu-reload" @click="getNums">
              <i
                class="es-icon-shuaxin"
                :class="{ 'es-icon-shuaxin-rotate': reladding }"
              ></i>
            </span>
          </div>
          <div class="es-simplicitytop-menu-children">
            <!-- <my-remind :list="myRemindMenu"></my-remind> -->
            <div
              class="es-simplicitytop-menu-children-item"
              v-for="(child, i) in myRemindMenu"
              :key="i"
              @click="remindSelect(child)"
            >
              <div class="es-simplicitytop-menu-children-icon">
                <i
                  :class="child.icons ? child.icons : 'es-icon-application'"
                ></i>
              </div>
              <div class="es-simplicitytop-menu-children-name">
                {{ child.text || child.name }}
              </div>
              <div
                class="es-simplicitytop-menu-children-badge"
                v-if="child.num"
              >
                {{ child.num }}
              </div>
            </div>
          </div>
        </div>
        <div class="es-simplicitytop-menu-item" v-if="myShortcut.length > 0">
          <div class="es-simplicitytop-menu-title">
            <span class="es-simplicitytop-menu-name" @click="testReloadPage"
              >我的快捷</span
            >
          </div>
          <el-scrollbar style="height: calc(100% - 45px)">
            <div class="es-simplicitytop-menu-children">
              <div
                class="es-simplicitytop-menu-children-item"
                v-for="(child, i) in myShortcut"
                :key="i"
                @click="remindSelect(child)"
              >
                <div class="es-simplicitytop-menu-children-icon">
                  <i
                    :class="child.icons ? child.icons : 'es-icon-application'"
                  ></i>
                </div>
                <div class="es-simplicitytop-menu-children-name">
                  {{ child.text }}
                </div>
              </div>
            </div>
          </el-scrollbar>
        </div>
      </div>
      <div class="es-simplicitytop-main-content">
        <div class="es-simplicitytop-main-menu">
          <es-menu
            class="es-fourth-tabs"
            mode="horizontal"
            :data="menus"
            :deep="true"
            :popperClass="`el-menu--popup-simplicitytop`"
            @select="(res) => handleSelect(res)"
          ></es-menu>
        </div>
        <div
          class="es-simplicitytop-main-fourth-tabs"
          v-if="appCodes && appCodes !== 'indexUrl'"
        >
          <el-tabs
            ref="fourthTab"
            v-model="tabActiveName"
            @tab-click="fourthTabClick"
          >
            <el-tab-pane
              :label="item.text"
              v-for="(item, index) in fourthTabs"
              :key="index"
              :name="item.id"
            ></el-tab-pane>
          </el-tabs>
        </div>
        <div class="es-simplicitytop-main-router" :key="count">
          <router-page
            v-if="currentPage.method === 'router'"
            v-bind="currentPage"
            :query="$parent.params"
          ></router-page>
          <iframe
            v-else-if="isIE || currentPage.method == 'iframe'"
            v-loading="currentPage.loading"
            frameborder="0"
            width="100%"
            height="100%"
            :id="
              activeName == currentPage.id
                ? currentPage
                : currentPage.id || currentPage.appCode
            "
            :name="
              activeName == currentPage.id
                ? iframeId
                : currentPage.id || currentPage.appCode
            "
            :onload="handleLoadIframe(currentPage)"
            :src="currentPage.url"
          ></iframe>
          <es-wujie
            v-else-if="currentPage.method === 'wujie' && currentPage.url"
            :host="host"
            :show="true"
            :props="wjProps"
            :attrs="wjAttrs"
            :name="currentPage.appCode"
            :url="currentPage.url"
          ></es-wujie>
        </div>
        <!-- <router-view></router-view> -->
        <!-- 消息列表 -->
        <message
          v-if="showMsg"
          ref="message"
          :total.sync="handleNums.notice"
          :visible.sync="showMsg"
          :winopen="winopen"
          @ignore="handleChange"
          @handle="handleMenuTips"
        ></message>
        <!-- 消息列表 end-->
        <!-- 应用 -->
        <!-- <apps
          :visible.sync="showApps"
          :menu-icon="menuIcon"
          :color="appColor"
          :backgroundColor="appBackgroundColor"
          :applications="applications"
          :business="business"
          :systems="systems"
          :user="user"
          @click="handlerClickApps"
        ></apps> -->
        <!-- 应用 end -->

        <!-- AI/IM -->
        <el-drawer
          class="es-simplicity-public-drawer"
          :direction="drawer.direction"
          modal-class="es-simplicity-apps-modal"
          size="100%"
          show-close
          :modal-append-to-body="false"
          :visible.sync="drawer.visible"
        >
          <div
            class="es-public-drawer-main"
            v-if="drawer.ai && drawer.ai.url"
            v-show="drawer.active == 'ai'"
          >
            <template v-if="isIE || drawer.ai.method !== 'wujie'">
              <iframe
                frameborder="0"
                width="100%"
                height="100%"
                :src="drawer.ai.url"
              ></iframe>
            </template>
            <template v-else>
              <es-wujie
                :host="host"
                :show="true"
                :props="wjProps"
                :attrs="wjAttrs"
                :name="drawer.ai.name"
                :url="drawer.ai.url"
              ></es-wujie>
            </template>
          </div>
          <div
            class="es-public-drawer-main"
            v-if="drawer.im && drawer.im.url"
            v-show="drawer.active == 'im'"
          >
            <template v-if="isIE || drawer.im.method !== 'wujie'">
              <iframe
                frameborder="0"
                width="100%"
                height="100%"
                :src="drawer.im.url"
              ></iframe>
            </template>
            <template v-else>
              <es-wujie
                :host="host"
                :show="true"
                :props="wjProps"
                :attrs="wjAttrs"
                :name="drawer.im.name"
                :url="drawer.im.url"
              ></es-wujie>
            </template>
          </div>
        </el-drawer>
        <!-- AI/IM end -->
      </div>
    </div>
    <!-- 设置 -->
    <settings
      v-bind="$attrs"
      layout-type="simplicityTop"
      active="simplicity"
      :theme="themeColor"
      :showSimplicityTop="showSimplicityTop"
      :predefine="themes"
      :visible.sync="showSet"
      @change="handleChange"
      @layout="handleLayout"
    ></settings>
    <!-- 设置 end-->

    <!-- 消息提醒 -->
    <notice :data="sysMsg" :winopen="winopen" @opened="handleOpened"></notice>
    <!-- 消息提醒 end -->

    <!-- 公用弹窗 -->
    <es-dialog :title="dialog.title" :visible.sync="dialog.show" size="md">
      <template v-if="dialog.title == '查看在线人员' && !dialog.src">
        <online></online>
      </template>
      <iframe
        v-else-if="dialog.show"
        width="100%"
        height="100%"
        frameborder="0"
        :src="dialog.src"
      ></iframe>
    </es-dialog>
    <!-- 公用弹窗 end -->
  </div>
</template>

<script>
import avatar from './avatar.vue';
import handler from './handler.vue';
// import subMenu from './sub-menu.vue';
// import apps from './apps.vue';
import user from './user.vue';
import message from './message.vue';
import notice from './notice.vue';
import settings from '../public/settings.vue';
import routerPage from './router-page.vue';
import online from '../public/online.vue';
import search from '../public/search.vue';
import WujieVue from 'wujie-vue2';

import {
  wss,
  logout,
  topic,
  getUserAppWithTag,
  recordUserApp,
  getComplexApplications,
  getComplexApplicationsNew,
  queryUseCommonMenu,
  getIndexCount,
  getUserTipsInstanceNum,
  getShareFilesReceiveCountNew,
  getVoteMeetingNum,
  queryChildMenuUrl
} from 'eoss-ui/src/config/api.js';
import store from 'eoss-ui/src/utils/store';
import util from 'eoss-ui/src/utils/util';
const isIE = /MSIE|Trident/.test(navigator.userAgent);
const systemMode = util.getWinTopProperty('systemMode', 'default');
// let events = [
//   (tabs, index, that) => {
//     let tab = tabs[index];
//     if (tab.method == 'iframe') {
//       tabs[index].url = util.handlerUrl(tab.url);
//     }
//     if (tab.method === 'wujie' && tab.appCode) {
//       const url = tab.url;
//       tab.url = '';
//       that.$nextTick(() => {
//         tab.url = url;
//       });
//     }
//     if (tab.method === 'router') {
//       that.$set(tabs[index], 'keys', util.uuid());
//     }
//     return tabs;
//   },
//   (tabs, index, that) => {
//     let i = util.indexOfObj(tabs, that.activeName, 'id');
//     if (tabs.length == 1) {
//       that.activeName = '';
//     } else if (i == index) {
//       if (index < tabs.length - 1) {
//         that.activeName = tabs[index + 1].id;
//       } else {
//         that.activeName = tabs[index - 1].id;
//       }
//     }
//     tabs.splice(index, 1);
//     return tabs;
//   },
//   (tabs, index, that) => {
//     let tab = tabs.slice(index, index + 1);
//     that.activeName = tab[0].id;
//     return tab;
//   },
//   (tabs, index, that) => {
//     let i = util.indexOfObj(tabs, that.activeName, 'id');
//     if (i < index) {
//       that.activeName = tabs[index].id;
//     }
//     tabs.splice(0, index);
//     return tabs;
//   },
//   (tabs, index, that) => {
//     let i = util.indexOfObj(tabs, that.activeName, 'id');
//     if (i > index) {
//       that.activeName = tabs[index].id;
//     }
//     tabs.splice(index + 1, tabs.length - index);
//     return tabs;
//   }
// ];
export default {
  name: 'SimplicityTop',
  provide() {
    return {
      esMain: this,
      menuRefresh: this.handleRefresh,
      jumpMenu: this.jumpTopMenu
    };
  },
  components: {
    avatar,
    handler,
    // subMenu,
    // apps,
    user,
    message,
    notice,
    settings,
    routerPage,
    online,
    search
  },
  props: {
    //是否显示头像
    avatar: {
      type: Boolean,
      default: true
    },
    //是否显示顶部
    showSimplicityTop: {
      type: Boolean,
      default: false
    },
    //im用例编码
    imUseCaseCode: String,
    //ai用例编码
    aiUseCaseCode: String,
    //模式
    mode: {
      type: String,
      default: systemMode
    },
    sysCode: String,
    appCode: String,
    //logo
    logo: String,
    // 顶部背景颜色
    topBg: {
      type: String,
      default: ''
    },
    topLogo: {
      type: String,
      default: ''
    },
    //菜单、应用默认图标
    menuIcon: {
      type: String,
      default: 'es-icon-application'
    },
    //默认主题颜色
    theme: {
      type: String,
      default: '#409eff'
    },
    //菜单显示类型
    scene: {
      type: String,
      default: 'default'
    },
    //主题颜色选择颜色集合
    themes: Array,
    //操作栏配置
    handleData: {
      type: Array,
      default: () => [
        {
          type: 'contact'
        },
        { type: 'dateTime' },
        { type: 'online' },
        {
          type: 'search',
          icon: 'es-icon-sousuo',
          title: '搜索'
        },
        {
          type: 'im',
          icon: 'es-icon-message',
          title: 'IM'
        },
        {
          type: 'index',
          icon: 'es-icon-zhuomian1',
          title: '门户'
        },
        {
          type: 'home',
          icon: 'es-icon-zhuye',
          title: '首页'
        },
        {
          type: 'notice',
          icon: 'es-icon-xiaoxi1',
          title: '消息'
        },
        {
          type: 'quit',
          icon: 'es-icon-tuichu1',
          title: '退出'
        },
        {
          type: 'set',
          icon: 'es-icon-shezhi',
          title: '设置'
        }
      ]
    },
    //操作栏单项配置
    handleConfig: Object,
    //需要隐藏的头部功能
    hides: Object,
    //菜单颜色
    menuColor: [String, Array],
    //菜单背景颜色
    menuBackgroundColor: [String, Array],
    //菜单是否折叠形式
    collapse: Boolean,
    //应用颜色
    appColor: [String, Array],
    //应用背景颜色
    appBackgroundColor: [String, Array],
    //默认头像
    userHead: String,
    //应用列表接口
    appsUrl: {
      type: String,
      default: getUserAppWithTag
    },
    //是否启用子应用菜单接口
    application: {
      type: Boolean,
      default: false
    },
    //菜单接口
    menuUrl: String,
    //远程请求菜单
    remote: {
      type: Boolean,
      default: true
    },
    //websocket
    socket: {
      type: Boolean,
      default: true
    },
    //iframeId
    iframeId: {
      type: String,
      default: 'stage'
    },
    //查看在线人数
    onlineView: {
      type: [String, Boolean],
      default: true
    },
    //消息办理是否采用window.open的方式打开
    winopen: {
      type: Boolean,
      default: true
    },
    //是否采用wujie微前端加载页面
    loadWujie: {
      type: Boolean,
      default: true
    },
    //无界微前端Props属性
    wjProps: Object,
    //无界微前端Attrs属性
    wjAttrs: Object,
    //菜单宽度
    menuWidth: {
      type: Number,
      default: 220
    },
    //路由方式
    routeType: String,
    host: {
      type: String,
      default() {
        return sessionStorage.getItem('host') || '';
      }
    },
    //切换旧版样式
    oldVersion: Boolean,
    //运维联系人
    contacts: Object,
    //展示系统操作按钮标题类型
    showHandlerTitleType: {
      type: String,
      default: 'tooltip',
      validator(val) {
        return ['tooltip', 'text'].includes(val);
      }
    },
    icons: Object,

    userCommonMenu: {
      type: String,
      default: queryUseCommonMenu
    },
    queryChildMenu: {
      type: String,
      default: queryChildMenuUrl
    },
    showTipNums: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      winTop: util.getWinTop(),
      appCodes: 'indexUrl',
      tabActiveName: '',
      count: 0,
      currentPage: {
        method: ''
      },
      userCommonMenuList: [],
      //是否显示头像
      showAvatar: this.avatar,
      // 问候语
      greeting: util.timeCycle() + '好！',
      //用例权限编码
      useCaseCodes: util.getStorage('useCaseCodes'),
      //显示用户信息
      showUser: false,
      //主题色
      themeColor: this.theme,
      //是否ie浏览器
      isIE: isIE,
      //logo
      mainLogo: this.logo,
      //侧边用户应用
      userApps: [],
      //点击应用存侧边
      newApps: [],
      //所有菜单
      menus: [],
      //菜单名称
      title: '',
      //子菜单
      subMenus: null,
      //展示菜单导航
      showMenu: false,
      //子菜单选中
      subActive: '',
      //折叠菜单
      fold: false,
      //菜单样式是否折叠形式
      isCollapse: this.collapse,
      //人工智能配置
      aiConfig: null,
      //im配置
      imConfig: null,
      //公用窗口面板配置
      drawer: {
        visible: false,
        direction: 'ltr',
        ai: {},
        im: {},
        active: ''
      },
      //所有应用
      applications: [],
      //业务系统
      business: [],
      //系统管理
      systems: [],
      //气泡数
      menuTips: {},
      //展示所有应用
      showApps: false,
      //用户信息
      userModel: {},
      //通知类型列表
      notifyList: [],
      //用户样式
      userStyle: {},
      //通知类型
      notify: '',
      //用户信息表单结构
      userInfoContents: undefined,
      //窗口页签
      tabs: [],
      //页签选中name
      activeName: '',
      //初始应用菜单页
      initApps: null,
      //首页地址
      indexUrl: '',
      //首页名称
      indexTitle: '首页',
      //首页配置
      homePage: {},
      //门户跳转页地址
      doorIndex: '',
      //弹窗
      dialog: {},
      handleNums: {
        //消息数
        notice: 0,
        //在线人数
        online: 1
      },
      //消息列表展示状态
      showMsg: false,
      //搜索
      showSearch: false,
      //即时消息
      sysMsg: [],
      //定时关闭及时消息对象
      sysMsgOut: null,
      //额外信息数据
      extraData: '',
      //显示设置面板
      showSet: false,
      //窗口是否可选
      isDisabled: {},
      //显示页签操作
      showTabsHandler: false,
      //页签对象
      pane: null,
      //选中菜单
      active: '',
      //单位名称
      simpleUserInfo: {},
      handleDatas: this.handleData,
      //顶部右侧工具隐藏
      handleHides: '',
      // 显示旧设计
      showOld: this.oldVersion,
      //运维联系人
      contact: this.contacts,
      //单点退出地址
      singleLogout: null,
      //展示系统操作按钮标题类型
      showTitleType: this.showHandlerTitleType,
      layout: this.scene.toLowerCase(),
      reladding: false,
      fourthTabs: [],
      jumpMenu: this.handleSelect,
      myRemind: [
        {
          badge: true,
          icon: 'es-icon-solid-shijian',
          id: '589cdcff17f44a58bccb5b44de0e90c5',
          text: '待办事项',
          icons: '',
          url: '/bpm/wfPending/wfPending/makeList.dhtml',
          target: 'stage',
          sort: 1,
          remindurl:
            'http://boot-gateway:8080/bpm/wfPending/wfPending/getMakeNum.dhtml',
          pid: 'd92e4c724cc74b13a4119f644eff0be8',
          level: 3,
          quickicons: '',
          appType: '0',
          appCode: 'pengding_make1',
          urlopenmode: 0,
          hasPermission: false,
          appId: '',
          extendData: {
            businessStatus: 1,
            businessWarnMsg: ''
          },
          fourthTabs: [],
          children: [],
          method: 'iframe',
          loading: false,
          num: 0
        },
        {
          badge: false,
          icon: 'es-icon-solid-yiban',
          id: '259600a64a6840a4952251fe0a7bd890',
          text: '已办事项',
          icons: '',
          url: '/bpm/wfpened/wfPended/list.dhtml?viewName=yibing',
          target: 'stage',
          sort: 3,
          remindurl: '',
          pid: 'd92e4c724cc74b13a4119f644eff0be8',
          level: 3,
          quickicons: '',
          appType: '0',
          appCode: 'yibingwdyb',
          urlopenmode: 0,
          hasPermission: false,
          appId: '',
          fourthTabs: [],
          children: [],
          method: 'iframe',
          loading: false,
          num: 0
        },
        {
          text: '待签公文',
          badge: true,
          num: 0,
          icon: 'es-icon-solid-daiqiangongwen',
          id: '03158b72e0d644f6ae97e55ee598a17d',
          url: '/archives-ui/webpack/index.html#/sign/signList',
          remindurl: '',
          pid: 'ec4a6e89b1b346a4a2e8f4245e315da3',
          appCode: 'signList',
          appId: 'q291a124fc151se5b4b890191c65e485',
          fourthTabs: [],
          children: [],
          method: 'wujie'
        },
        {
          badge: true,
          icon: 'es-icon-juqiangongwen',
          id: 'bbc03189766441e6a46550c556d61f03',
          text: '拒签公文',
          icons: '',
          url: '/archives-ui/webpack/index.html#/dispatch/rejectedList',
          target: 'stage',
          sort: 4,
          remindurl: '',
          pid: '7fd13c86f596417b95d2b7622906f70f',
          level: 3,
          quickicons: '',
          appType: '0',
          appCode: 'rejectedList',
          urlopenmode: 0,
          hasPermission: false,
          appId: 'q291a124fc151se5b4b890191c65e485',
          extendData: {
            businessStatus: 1,
            businessWarnMsg: ''
          },
          fourthTabs: [],
          children: [],
          method: 'wujie'
        },
        {
          badge: true,
          num: 0,
          icon: 'es-icon-solid-ziliao',
          routerName: '',
          id: 'df9d1baedf6a4107bfa9f5d763a98fc0',
          text: '待收资料',
          icons: '',
          url: '/oa/sharefiles/receive/list.dhtml',
          target: 'stage',
          sort: 0,
          remindurl: '',
          pid: 'd648a3e7ae16458a823fdbe911e4d76e',
          level: 2,
          quickicons: '',
          appType: '1',
          appCode: 'sharefilesReceive',
          urlopenmode: 0,
          hasPermission: false,
          appId: 'q291a124fc151se5b4b890191c65e485',
          extendData: {
            businessStatus: 1,
            businessWarnMsg: ''
          },
          fourthTabs: [],
          children: [],
          method: 'iframe',
          loading: false
        },
        {
          text: '待签会议',
          badge: true,
          num: 0,
          icon: 'es-icon-solid-huiyileixing',
          id: '407eff212ecd4355ad1fb28c8de6e882',
          icons: '',
          url: '/conference/meetingReceive/receive_list.dhtml?meetState=-5',
          target: 'stage',
          sort: 0,
          remindurl: '',
          pid: 'bc1b01feafc64ae68beed2da5559ff7c',
          level: 3,
          quickicons: '',
          appType: '0',
          appCode: 'hyqs',
          urlopenmode: 0,
          hasPermission: false,
          appId: '',
          extendData: {
            businessStatus: 1,
            businessWarnMsg: ''
          },
          fourthTabs: [
            {
              id: 'c2d3fb3c7d684b06b4511233a6b5f03b',
              text: '未签收',
              icons: '',
              url: '/conference/meetingReceive/receive_list.dhtml?meetState=-5',
              target: 'stage',
              sort: 1,
              remindurl: '',
              pid: '407eff212ecd4355ad1fb28c8de6e882',
              level: 4,
              quickicons: '',
              appType: '0',
              appCode: 'wqsmeeting',
              urlopenmode: 0,
              hasPermission: false,
              appId: '',
              extendData: {
                businessStatus: 1,
                businessWarnMsg: ''
              },
              fourthTabs: [],
              children: []
            },
            {
              id: '9990c8064694403ba5ee85f098738aab',
              text: '已签收',
              icons: '',
              url: '/conference/meetingReceive/receive_list.dhtml?meetState=-6',
              target: 'stage',
              sort: 2,
              remindurl: '',
              pid: '407eff212ecd4355ad1fb28c8de6e882',
              level: 4,
              quickicons: '',
              appType: '0',
              appCode: 'yqs',
              urlopenmode: 0,
              hasPermission: false,
              appId: '',
              extendData: {
                businessStatus: 1,
                businessWarnMsg: ''
              },
              fourthTabs: [],
              children: []
            }
          ],
          children: [],
          method: 'iframe',
          loading: false
        }
      ],
      myRemindMenu: [],
      myShortcut: []
    };
  },
  computed: {
    _handleDatas() {
      const handleDatas = this.handleDatas.filter((item, index) => {
        if (item.type === 'contact' && this.contact) {
          this.$set(this.handleDatas, index, { ...item, ...this.contact });
        }
        if (item.type === 'contact' && !this.contact) {
          return false;
        }
        return !item.hide && !this.hide[item.type];
      });
      return handleDatas;
    },
    //菜单接口
    _menuUrl() {
      if (this.menuUrl) {
        return this.menuUrl;
      }
      if (this.application) {
        return getComplexApplicationsNew;
      }
      return getComplexApplications;
    },
    //人工智能配置
    _aiConfig() {
      return this.aiConfig
        ? {
            ...this.aiConfig,
            icon: 'data:image/png;base64, '
          }
        : false;
    },
    showAi() {
      return this.aiUseCaseCode
        ? this.useCaseCodes.indexOf(this.aiUseCaseCode) > -1
        : true;
    },
    //用户信息
    user() {
      return this.userModel ? this.userModel : store.get('userModel');
    },
    //在线人数列表地址
    onlineUrl() {
      if (this.onlineView) {
        return typeof this.onlineView == 'string' ? this.onlineView : '';
      }
      return false;
    },
    //隐藏操作按键
    hide() {
      let handleHides = {};
      if (this.handleHides) {
        handleHides = JSON.parse(
          this.handleHides.replace(/(['"])?([a-zA-Z0-9_]+)(['"])?:/g, '"$2":')
        );
      }
      let hides = {
        contact: this.contact ? false : true,
        im: this.imConfig
          ? this.imUseCaseCode
            ? this.useCaseCodes.indexOf(this.imUseCaseCode) == -1
            : false
          : true,
        home: this.indexUrl ? false : true,
        index: this.doorIndex ? false : true,
        old: this.showOld ? false : true
      };

      if (this.layout === 'subsystem' || this.application) {
        hides.system = false;
      }
      if (this.layout === 'topside' || this.layout === 'side') {
        hides.user = true;
      }
      return { ...hides, ...this.hides, ...handleHides };
    }
  },
  watch: {
    menuTips: {
      deep: true,
      handler() {
        // console.log('menuTips', this.menuTips);
        // this.setTips(this.userApps);
        // this.setTips(this.applications);
        // this.setTips(this.business);
        // this.setTips(this.systems);
        // this.setTips(this.menus);
        this.getNums();
      }
    },
    scene(val) {
      if (val) {
        this.layout = val.toLowerCase();
      }
    }
  },
  created() {
    this.doorIndex = sessionStorage.getItem('doorIndex');
  },
  mounted() {
    // this.handleListener();
    window.jumpMenu = this.wintop.jumpTopMenu = this.handleSelect;
    this.queryChildMenuData();
  },
  methods: {
    remindSelect(menu) {
      let fourthTabs = [];
      if (menu.children && menu.children.length > 0) {
        fourthTabs = [...menu.children];
      } else {
        fourthTabs = [...menu];
      }
      this.fourthTabs = [...fourthTabs];
      this.tabActiveName = fourthTabs[0].id;
      this.appCodes = this.fourthTabs[0].appCode;
      this.currentPage = this.setIframeType(this.fourthTabs[0]);
    },
    /**
     * queryChildMenu: 查询左侧我的提醒和我的快捷菜单
     */
    queryChildMenuData() {
      util
        .ajax({
          url: queryChildMenuUrl,
          method: 'get'
        })
        .then((res) => {
          if (res.rCode === 0) {
            const tree = this.flatToNestedTree(res.results);
            this.myRemindMenu = [...tree[0].children];
            this.myShortcut = [...tree[1].children];
            this.getNums();
          }
        });
    },

    flatToNestedTree(flatTree, rootPid = 'root') {
      if (!Array.isArray(flatTree)) {
        console.error('flatTree must be an array');
        return [];
      }

      // 创建ID映射表，用于快速查找节点
      const idMap = new Map();
      // 存储根节点
      const rootNodes = [];

      // 首次遍历：创建映射表并初始化每个节点的children数组
      flatTree.forEach((node) => {
        // 深拷贝节点，避免修改原数据
        const nodeCopy = { ...node };
        // 确保children数组存在且为空
        nodeCopy.children = [];
        // 建立ID到节点的映射
        idMap.set(nodeCopy.id, nodeCopy);

        // 找出根节点
        if (nodeCopy.pid === rootPid) {
          rootNodes.push(nodeCopy);
        }
      });

      // 第二次遍历：建立父子关系
      flatTree.forEach((node) => {
        const currentNode = idMap.get(node.id);
        const parentNode = idMap.get(node.pid);

        // 如果找到父节点且父节点不是根节点
        if (parentNode && node.pid !== rootPid) {
          parentNode.children.push(currentNode);
        }
      });

      return rootNodes;
    },
    // tab点击事件
    fourthTabClick(res) {
      const index = res.index;
      this.currentPage = {};
      this.appCodes = this.fourthTabs[index].appCode;

      // console.log(this.fourthTabs[index], 'this.fourthTabs[index]');
      // 增加阻塞 重载页面
      setTimeout(() => {
        this.currentPage = this.setIframeType(this.fourthTabs[index]);
      }, 0);
    },
    //获取数量
    async getNums() {
      await this.getIndexCount();
      await this.getUserTipsInstanceNum(0);
      await this.getUserTipsInstanceNum(1);
      await this.getShareFilesReceiveCountNew();
      await this.getVoteMeetingNum();
      this.reladding = true;
      if (this.reladding) {
        setTimeout(() => {
          this.reladding = false;
        }, 1000);
      }
    },
    /**
     * getVoteMeetingNum: 查询会议数量
     */
    getVoteMeetingNum() {
      util
        .ajax({
          url: getVoteMeetingNum,
          params: {
            userId: util.getStorage('userId'),
            type: 10
          },
          method: 'get'
        })
        .then((res) => {
          if (res.rCode === 0) {
            const myRemindMenu = [...this.myRemindMenu];
            myRemindMenu.forEach((item) => {
              if (item.appCode === 'conference_meeting') {
                item.num = res.results > 99 ? '99+' : res.results;
              }
            });
            this.myRemindMenu = [...myRemindMenu];
          }
        });
    },
    /**
     * getShareFilesReceiveCountNew: 查询待接收文件数量
     */
    getShareFilesReceiveCountNew() {
      util
        .ajax({
          url: getShareFilesReceiveCountNew,
          params: {
            userId: util.getStorage('userId')
          },
          method: 'get'
        })
        .then((res) => {
          if (res.rCode === 0) {
            const myRemindMenu = [...this.myRemindMenu];
            myRemindMenu.forEach((item) => {
              if (item.appCode === 'favoriteCount') {
                item.num = res.results > 99 ? '99+' : res.results;
              }
            });
            this.myRemindMenu = [...myRemindMenu];
          }
        });
    },

    /**
     * getUserTipsInstanceNum: 查询待签收/据签收任务数量 1是拒签收 0是待签收
     */
    getUserTipsInstanceNum(type) {
      let params = `?subjectCode=signCount&state=0&userId=${util.getStorage(
        'userId'
      )}&queryOrgType=-1`;
      if (type) {
        params = `?subjectCode=signCount&queryOrgType=-1&viewState=0&userId=${util.getStorage(
          'userId'
        )}&queryAccType=-1&queryArcType=0`;
      }
      util
        .ajax({
          url: getUserTipsInstanceNum + params,
          method: 'get'
        })
        .then((res) => {
          if (res.rCode === 0) {
            const appCode = type ? 'wdtxjqgw' : 'wdtxgwqssignList';
            const myRemindMenu = [...this.myRemindMenu];
            myRemindMenu.forEach((item) => {
              if (item.appCode === appCode) {
                item.num = res.results > 99 ? '99+' : res.results;
              }
            });
            this.myRemindMenu = [...myRemindMenu];
          } else {
            console.error('查询待签收/据签收任务数量失败', res);
          }
        });
    },
    /**
     * getIndexCount: 查询待办任务数量
     */
    getIndexCount() {
      util
        .ajax({
          url: getIndexCount,
          params: {
            userId: util.getStorage('userId')
          },
          method: 'get'
        })
        .then((res) => {
          if (res.rCode === 0) {
            // 待办
            const makePendingCount = res.results.makePendingCount || 0;
            const myRemindMenu = [...this.myRemindMenu];
            myRemindMenu.forEach((item) => {
              if (item.appCode === 'makePendingCount') {
                item.num = makePendingCount > 99 ? '99+' : makePendingCount;
              }
            });
            this.myRemindMenu = [...myRemindMenu];
          } else {
            console.error('查询待办任务数量失败', res);
          }
        });
    },

    handleDepSelect(res) {
      this.$refs.user.handleSelect(res);
    },
    /**
     * @desc:匹配路由
     * @author huangbo
     * @date 2024年9月7日
     **/
    hasRouter(res, url, code) {
      if (!url) {
        return false;
      }
      if (Array.isArray(res)) {
        for (let i in res) {
          let path = this.hasRouter(res[i], url, code);
          if (path) {
            return path;
          }
        }
      } else {
        let path = res.path;
        if (path !== '/' && path !== '/404') {
          path = path.replace(path[1], path[1].toLowerCase());
        }
        let pathname = url.substring(url.indexOf('#/') + 1);
        pathname = pathname.split('?')[0];
        let appCode;
        if (res.path !== '/' && pathname == path) {
          if (res.components) {
            if (!res.components[code]) {
              console.error(
                '路由“命名视图”规范属性名称与菜单appCode不一致',
                res,
                code
              );
              appCode = Object.keys(res.components).filter((item) => {
                return item !== 'default';
              })[0];
            }
          } else {
            console.error(
              '请根据路由“命名视图”规范，正确添加components属性名称',
              res
            );
          }
          return appCode ? { path: pathname, appCode } : pathname;
        }
        if (res && Object.prototype.hasOwnProperty.call(res, 'children')) {
          let path = this.hasRouter(res.children, url, code);
          if (path) {
            return path;
          }
        }
      }
      return false;
    },
    /**
     * @desc:获取初始数据
     * @author huangbo
     * @date 2024年9月7日
     **/
    init(results) {
      this.setConfig(results);
      // if (this.remote && first) {
      this.getApplications();
      // 此处的快捷 是用户自定义的 不是系统配置的快捷菜单 所以注释掉
      // this.getUseCommonMenu();
      // }
    },
    /**
     * @desc:设置用户配置及信息
     * @author huangbo
     * @date 2024年9月7日
     **/
    setConfig(results) {
      localStorage.setItem('mainConfig', JSON.stringify(results));
      util.setStorage({
        type: this.storage,
        key: {
          depId: results.userModel.depId,
          orgId: results.userModel.orgId,
          userId: results.userModel.userId,
          userName: results.userModel.username || results.userModel.userName,
          useCaseCodes: results.resourceCodes || results.userModel.resourceCodes
        }
      });
      for (let i in results) {
        if (i === 'mainLogoUrl' && results[i]) {
          this.mainLogo = results[i];
        }
        if (
          i === 'mainBannerUrl' &&
          results[i] &&
          this.headerImage === undefined
        ) {
          this.headerImg = results[i];
        }
        if (i === 'initApplication' && results[i]) {
          this.initApps = results[i].split(',');
        }
        if (i === 'indexUrl' && results[i]) {
          this.indexUrl = results[i];
        }
        if (i === 'doorIndex' && results[i]) {
          util.win.open(results[i]);
          this.doorIndex = results[i];
        }
        if (i === 'subsystemName' && results[i]) {
          document.title = results[i];
        }
        if (i === 'loginPage' && results[i]) {
          util.setStorage({ key: 'loginPage', value: results[i] });
        }
        if (i === 'sysLogoIco' && results[i]) {
          localStorage.setItem('sysLogoIco', results[i]);
          util.setFavicon(results[i]);
        }
        if (i === 'userStyle' && results[i]) {
          if (results[i].color) {
            let color = unescape(results[i].color).toLowerCase();
            if (util.startWith(color, '#')) {
              this.themeColor = color;
            }
          }
          if (results[i].indexUrl) {
            this.indexUrl = results[i].indexUrl;
          }
          this.userStyle = results[i];
          this.notify = results[i].notify || '';
        }
        if (i === 'subsystemExtend' && results[i]) {
          if (results[i].indexTitle) {
            this.indexTitle = results[i].indexTitle;
          }
          if (Object.prototype.hasOwnProperty.call(results[i], 'showAvatar')) {
            this.showAvatar = JSON.parse(results[i].showAvatar);
          }
          if (results[i].themeColor) {
            let color = unescape(results[i].themeColor).toLowerCase();
            if (util.startWith(color, '#')) {
              this.themeColor = color;
            }
          }
          //三方单点登录退出地址
          if (results[i].singleLogout) {
            this.singleLogout = results[i].singleLogout.split(',');
          }
          if (results[i].userInfoContents) {
            this.userInfoContents = JSON.parse(results[i].userInfoContents);
          }
          //水印配置
          if (results[i].webPageWatermark) {
            try {
              util.win.webPageWatermark = results[i].webPageWatermark;
              util.watermark(results[i].webPageWatermark);
            } catch (error) {}
          }
          //登录页页面地址
          if (results[i].loginPage) {
            util.setStorage({ key: 'loginPage', value: results[i].loginPage });
          }
          //登录页页面地址
          if (results[i].openModel) {
            util.setStorage({ key: 'openModel', value: results[i].openModel });
          }
          //ai配置
          if (results[i].aiConfig) {
            if (typeof results[i].aiConfig == 'string') {
              try {
                this.aiConfig = JSON.parse(results[i].aiConfig);
              } catch (error) {
                this.aiConfig = { url: results[i].aiConfig };
              }
            } else {
              this.aiConfig = results[i].aiConfig;
            }
          }
          //im配置
          if (results[i].imConfig) {
            if (typeof results[i].imConfig == 'string') {
              try {
                this.imConfig = JSON.parse(results[i].imConfig);
              } catch (error) {
                this.imConfig = { url: results[i].imConfig };
              }
            } else {
              this.imConfig = results[i].imConfig;
            }
          }
          if (results[i].portalPage || results[i].portalpage) {
            this.doorIndex = results[i].portalPage || results[i].portalpage;
          }
          if (results[i].multipleVersion || results[i].oldVersion) {
            this.showOld = results[i].oldVersion
              ? JSON.parse(results[i].oldVersion)
              : true;
          }

          if (results[i].handleDatas) {
            this.handleDatas = JSON.parse(results[i].handleDatas);
          }
          if (results[i].topRightToolHide || results[i].handleHides) {
            this.handleHides = JSON.parse(
              results[i].topRightToolHide || results[i].handleHides
            );
          }
          if (results[i].contact) {
            let contact = JSON.parse(results[i].contact);
            let content = contact.content.split(',');
            this;
            this.contact = {
              ...contact,
              content
            };
          }
          //展示系统操作按钮标题类型
          if (results[i].showHandlerTitleType) {
            this.showTitleType = results[i].showHandlerTitleType;
          }
          //菜单样式是否折叠形式
          if (results[i].menuCollapse !== undefined) {
            this.isCollapse =
              results[i].menuCollapse !== false &&
              results[i].menuCollapse !== 'false';
          }
        }
        if (i === 'userModel' && results[i]) {
          if (results[i].userHeadUrl) {
            results[i].userHeadUrl = util.jointUrl({
              url: results[i].userHeadUrl,
              reg: '/main2'
            });
          } else {
            results[i].userHeadUrl = this.userHead;
          }
          this.userModel = results[i];
          if (results[i].openModel) {
            util.setStorage({ key: 'openModel', value: results[i].openModel });
          }
        }
        if (i === 'notifyList' && results[i]) {
          this.notifyList = results[i];
        }
        store.set(i, results[i]);
      }
    },
    /**
     * @desc:获取用户自定义菜单
     **/
    getUseCommonMenu() {
      util
        .ajax({
          url: this.userCommonMenu,
          defaults: true,
          params: {
            userId: util.getStorage('userId')
          },
          method: 'get'
        })
        .then((res) => {
          if (res.rCode === 0) {
            if (res.results && Object.keys(res.results).length) {
              this.userCommonMenuList = res.results;
            } else {
              this.$message.error('未分配应用菜单权限，请联系管理员！');
            }
          } else {
            let msg = res.msg || '系统错误，请联系管理员！';
            this.$message.error(msg);
          }
        })
        .catch((err) => {
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    },
    /**
     * @desc:获取所有应用
     * @author huangbo
     * @date 2024年9月7日
     **/
    getApplications() {
      let loading = util.loading('', '加载中...');
      util
        .ajax({
          url: this.appsUrl,
          defaults: true
        })
        .then((res) => {
          if (this.socket) {
            this.initWebSocket();
          }
          if (res.rCode === 0) {
            if (res.results && Object.keys(res.results).length) {
              let { all, app_special_business_system, app_system, app_user } =
                res.results;
              this.userApps = app_user.filter((item) => {
                return item.permission !== false;
              });
              this.applications = all;
              this.business = app_special_business_system;
              this.systems = app_system;
              this.setTips(this.userApps);
              this.setTips(this.applications);
              this.setTips(this.business);
              this.setTips(this.systems);
            } else {
              this.$message.error('未分配应用菜单权限，请联系管理员！');
            }
            this.getMenus(loading);
          } else {
            loading.close();
            let msg = res.msg || '系统错误，请联系管理员！';
            this.$message.error(msg);
          }
        })
        .catch((err) => {
          loading.close();
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    },
    /**
     * @desc:获取菜单列表
     * @author huangbo
     * @date 2024年9月7日
     **/
    getMenus(loading) {
      util
        .ajax({ url: this._menuUrl })
        .then((res) => {
          loading.close();
          if (res.rCode === 0) {
            if (res.results && res.results.length) {
              //this.$emit('update:menuData', res.results);
              store.set('nav', JSON.parse(JSON.stringify(res.results)));
              this.renderMenus(JSON.parse(JSON.stringify(res.results)));
            } else {
              this.$message.error('未分配菜单权限，请联系管理员！');
            }
          } else {
            let msg = res.msg || '系统错误，请联系管理员！';
            this.$message.error(msg);
          }
        })
        .catch((err) => {
          loading.close();
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    },
    /**
     * @desc:处理菜单列表
     * @author huangbo
     * @date 2024年9月7日
     **/
    renderMenus(res) {
      // // console.log(res, 'renderMenus');
      // 此主题样式的情况下 只显示二级菜单  三级菜单以tab的形式加载   如果没有三级菜单 1.不需要展示tab,2.tab为二级菜单
      const rebuildMenu = res.map((level1Menu) => {
        const transformedLevel1 = {
          ...level1Menu,
          children: level1Menu.children.map((level2Menu) => {
            const transformedLevel2 = {
              ...level2Menu,
              // 处理三级菜单
              fourthTabs:
                level2Menu.children && level2Menu.children.length > 0
                  ? level2Menu.children.map((level3Menu) => ({
                      ...level3Menu
                    }))
                  : [
                      {
                        // 如果没有三级菜单，将二级菜单自身作为三级菜单
                        ...level2Menu
                      }
                    ]
            };

            // 清除children，避免渲染问题
            transformedLevel2.children = [];

            return transformedLevel2;
          })
        };

        return transformedLevel1;
      });

      // 判断myRemind中每个项是否在菜单列表中，并设置hasPermission
      this.updateRemindPermission(res);

      // console.log('rebuildMenu', rebuildMenu);

      this.menus = rebuildMenu;
      this.setTips(this.menus);
      // store.set('nav', this.menus);
      let obj = this.getMenu(this.menus, this.indexUrl);
      obj = obj
        ? JSON.parse(JSON.stringify(obj))
        : {
            url: this.indexUrl,
            text: this.indexTitle,
            id: '0',
            appCode: 'indexUrl'
          };
      this.homePage = this.setIframeType(obj);
      this.currentPage = { ...this.homePage };
      this.appCodes = 'indexUrl';
      // console.log(this.currentPage, 'currentPage');
    },
    /**
     * 更新myRemind中各项的权限状态
     * @param {Array} menus - 完整的菜单列表
     */
    updateRemindPermission(menus) {
      // 创建一个Set存储所有菜单的id，方便快速查找
      const menuIdSet = new Set();
      // 递归遍历菜单列表，收集所有id
      const collectMenuIds = (menuList) => {
        menuList.forEach((menu) => {
          menuIdSet.add(menu.id);
          if (menu.children && menu.children.length > 0) {
            collectMenuIds(menu.children);
          }
        });
      };
      // 收集所有菜单id
      collectMenuIds(menus);
      // 更新myRemind中各项的hasPermission
      this.myRemind.forEach((remind) => {
        // 判断remind.id是否存在于菜单id集合中
        remind.hasPermission = menuIdSet.has(remind.id);
      });
      // 同时更新userCommonMenuList中各项的hasPermission
      this.userCommonMenuList.forEach((item) => {
        // 判断item.id是否存在于菜单id集合中
        item.hasPermission = menuIdSet.has(item.id);
      });
    },
    /**
     * @desc:设置页面加载类型
     * @author huangbo
     * @date 2024年9月7日
     **/
    setIframeType(res) {
      let { url } = res;
      let urls = url.split('?');
      // console.log(res);
      if (urls[0].indexOf('.js') > 1 && !isIE) {
        res.method = 'wujie';
        if (!res.appCode) {
          res.appCode = 'application_' + Date.now();
        }
      } else if (
        urls[0].indexOf('.dhtml') > 0 ||
        (urls[0].indexOf('.html') > 0 && urls[0].indexOf('.html#') === -1)
      ) {
        res.method = 'iframe';
      } else {
        if (urls[0].indexOf('.html') === -1 && urls[0].indexOf('#/') === -1) {
          res.method = 'iframe';
        } else {
          const routes = this.$router.options.routes;
          if (routes) {
            let path = this.hasRouter(routes, urls[0], res.appCode);
            if (path && this.routeType !== 'wujie') {
              res.method = 'router';
              if (typeof path === 'string') {
                res.path = path;
              } else {
                res.path = path.path;
                res.appCode = path.appCode;
              }
              res.keys = util.uuid();
            } else {
              let urlopenmode = util.getParams({
                url: url,
                name: 'urlopenmode'
              });
              if (
                this.loadWujie === false ||
                isIE ||
                res.urlopenmode == 3 ||
                urlopenmode == 3
              ) {
                res.method = 'iframe';
              } else {
                res.method = 'wujie';
                if (!res.appCode) {
                  res.appCode = 'application_' + Date.now();
                }
              }
            }
          } else if (
            (urls[0].indexOf('.html') > -1 && urls[0].indexOf('#/') > -1) ||
            urls[0].indexOf('/#/') > -1
          ) {
            res.method = 'wujie';
            if (!res.appCode) {
              res.appCode = 'application_' + Date.now();
            }
          } else {
            res.method = 'iframe';
          }
        }
      }
      return res;
    },
    /**
     * @desc:获取菜单
     * @author huangbo
     * @date 2024年9月7日
     **/
    getMenu(menus, res, key) {
      if (Array.isArray(menus)) {
        for (let i = 0; i < menus.length; i++) {
          let item = menus[i];
          if (key) {
            if (item[key] === res) {
              return item;
            }
          } else if (
            item.url === res ||
            item.id === res ||
            item.appCode === res
          ) {
            return item;
          }
          if (
            Object.prototype.hasOwnProperty.call(item, 'children') &&
            item.children.length
          ) {
            let obj = this.getMenu(item.children, res, key);
            if (obj) {
              return obj;
            }
          } else if (
            Object.prototype.hasOwnProperty.call(item, 'fourthTabs') &&
            item.fourthTabs.length
          ) {
            let obj = this.getMenu(item.fourthTabs, res, key);
            if (obj) {
              return obj;
            }
          }
        }
      }
      return false;
    },
    /**
     * @desc:获取菜单第一条数据
     * @author huangbo
     * @date 2024年9月7日
     **/
    getFirst(obj) {
      if (!obj) {
        return '';
      }
      let openIdex = 0;
      if (
        obj.extendData &&
        (obj.extendData.subDefOpenIndex || obj.extendData.subDefOpen)
      ) {
        openIdex = parseInt(
          obj.extendData.subDefOpenIndex || obj.extendData.subDefOpen,
          10
        );
      }
      if (obj.children && obj.children.length && obj.children[openIdex]) {
        return this.getFirst(obj.children[openIdex]);
      } else if (
        obj.fourthTabs &&
        obj.fourthTabs.length &&
        obj.fourthTabs[openIdex]
      ) {
        return this.getFirst(obj.fourthTabs[openIdex]);
      } else if (obj.url && obj.urlopenmode !== 1 && obj.urlopenmode !== 2) {
        return obj;
      }
    },
    /**
     * @desc:遍历设置菜单气泡提醒
     * @author huangbo
     * @date 2024年9月7日
     **/
    setTips(obj) {
      // 不显示菜单气泡提醒
      if (!this.showTipNums) return;
      if (Array.isArray(obj)) {
        obj.forEach((item) => {
          this.setTips(item);
        });
      } else {
        if (
          obj &&
          Object.prototype.hasOwnProperty.call(obj, 'tips') &&
          obj.tips
        ) {
          this.$set(obj, 'tips', false);
          delete obj.tips;
        }
        let flag = 0;
        if (obj.children && obj.children.length) {
          obj.children.forEach((item) => {
            let n = this.setTips(item);
            flag += n ? parseInt(n) : 0;
          });
          if (flag) {
            this.$set(obj, 'tips', flag);
            this.setDot(this.userApps, obj.appCode);
            this.setDot(this.applications, obj.appCode);
            this.setDot(this.business, obj.appCode);
            this.setDot(this.systems, obj.appCode);
            return flag;
          }
        } else if (obj.fourthTabs && obj.fourthTabs.length) {
          obj.fourthTabs.forEach((item) => {
            let n = this.setTips(item);
            flag += n ? parseInt(n) : 0;
          });
          if (flag) {
            this.$set(obj, 'tips', flag);
            this.setDot(this.userApps, obj.appCode);
            this.setDot(this.applications, obj.appCode);
            this.setDot(this.business, obj.appCode);
            this.setDot(this.systems, obj.appCode);
            return flag;
          }
        } else {
          let num =
            this.menuTips[obj.id] ||
            this.menuTips[obj.code] ||
            this.menuTips[obj.appCode];
          if (num && Number(num)) {
            this.$set(obj, 'tips', Number(num));
            return num;
          }
        }
      }
      return false;
    },
    setDot(obj, code) {
      if (Array.isArray(obj)) {
        obj.forEach((item) => {
          this.setDot(item, code);
        });
      } else if (obj.code === code) {
        this.$set(obj, 'tips', true);
      }
    },
    /**
     * @desc:获取气泡提醒
     * @author huangbo
     * @date 2024年9月7日
     **/
    getBadge(res) {
      let num = res.tips || 0;
      return num === true
        ? {
            isDot: true
            //hidden: item.tips
          }
        : {
            value: num,
            max: 99,
            hidden: !num
          };
    },
    /**
     * @desc:开启weosocket
     * @author huangbo
     * @date 2024年9月7日
     **/
    initWebSocket() {
      this.webSocket = util.socket({
        url: wss,
        take: topic,
        success: (res) => {
          let data = res.data || {};
          for (let i in data) {
            if (data[i] !== null && data[i] !== undefined) {
              if (i === 'onlineUserNums' && data[i] > 0) {
                this.$set(this.handleNums, 'online', data[i]);
              }
              if (i === 'sysMsgNums' && data[i] !== null) {
                this.$set(this.handleNums, 'notice', data[i]);
                if (this.showMsg) {
                  this.$refs.message.getMsg(true);
                }
              }
              if (i === 'menuTipsMap') {
                // 处理消息提醒,更新气泡的数据,并且判断是刷新哪个列表,
                if (data[i] !== null) {
                  this.menuTips = data[i];
                  const tips = data[i];
                  // tips 处理
                  if (tips) {
                    for (let key in tips) {
                      if (
                        key == 'pcHandlePendingCount' ||
                        key == 'pcReadPendingCount'
                      ) {
                        if (
                          this.appCodes == 'indexUrl' &&
                          this.wintop.refreshList
                        ) {
                          this.wintop.refreshList(key);
                        }
                        if (this.appCodes == 'wdtxpengding_make') {
                          this.handleRefresh(1);
                        }
                      }
                    }
                  }
                } else {
                  this.getNums();
                }
              }
              if (i === 'sysMsgList' && data[i] !== null) {
                this.sysMsg = data[i];
                data[i] && data[i].length && this.$emit('bus-emit', 'waitdone');
              }
              if (i === 'extraData' && data[i] !== null) {
                this.extraData = data[i];
              }
            }
          }
          if (this.$store) {
            try {
              this.$store.commit('websocket', data);
            } catch (error) {}
          }
          const bus = this.bus || this.$eventBus || this.$root.Bus;
          if (bus) {
            bus.$emit('websocket', data);
          }
          if (util.win.eventBus) {
            util.win.eventBus.$emit('websocket', data);
          }
        }
      });
    },
    /**
     * @desc:显示用户信息
     * @author huangbo
     * @date 2024年9月7日
     **/
    showUserInfo() {
      if (this.showUser === false) {
        this.showUser = true;
      }
    },
    /**
     * @desc:删除更多应用菜单点击
     * @author huangbo
     * @date 2024年9月7日
     **/
    handleDelete(index) {
      this.newApps.splice(index, 1);
    },
    /**
     * @desc:显示Drawer界面
     * @author huangbo
     * @date 2024年9月7日
     **/
    handlerSetDrawer(res, type, direction = 'ltr') {
      this.drawer.visible = true;
      this.drawer.active = type;
      this.drawer.direction = direction;
      if (res) {
        let { mounted, url } = res;
        this.drawer[type] = {
          mounted,
          url,
          name: res.name || util.uuid()
        };
      }
    },
    /**
     * @desc:关闭Drawer界面
     * @author huangbo
     * @date 2024年9月7日
     **/
    handleCloseDrawer() {
      this.drawer = { visible: false };
    },
    /**
     * @desc:用户详情请求成功
     * @author huangbo
     * @date 2024年9月7日
     **/
    handleSuccess(res) {
      this.simpleUserInfo = res.simpleUserInfo;
    },
    /**
     * @desc:修改用户配置
     * @author huangbo
     * @date 2024年9月7日
     **/
    handleChangeConfig(name, res) {
      if (name == 'userHeadUrl') {
        this.$set(this.userModel, 'userHeadUrl', res);
        store.set('userModel', this.userModel);
        let mainConfig = JSON.parse(localStorage.getItem('mainConfig'));
        sessionStorage.setItem(
          'mainConfig',
          JSON.stringify({ ...mainConfig, userModel: this.userModel })
        );
      } else {
        this.$set(this.userStyle, 'notify', res);
        store.set('userStyle', this.userStyle);
        let mainConfig = JSON.parse(localStorage.getItem('mainConfig'));
        localStorage.setItem(
          'mainConfig',
          JSON.stringify({ ...mainConfig, userStyle: this.userStyle })
        );
      }
    },
    /**
     * @desc:关闭webSocket
     * @author huangbo
     * @date 2024年9月7日
     **/
    handlerClose() {
      if (this.webSocket) {
        this.webSocket.destroy();
      }
    },
    testReloadPage() {
      this.handleRefresh(1);
    },
    /**
     * @desc:刷新选中iframe页签
     * @author huangbo
     * @date 2024年9月7日
     **/
    handleRefresh(arg) {
      if (arg !== 1) {
        this.getNums();
      }
      // console.log(arg, 'arg');
      if (this.wintop.refreshList) {
        this.wintop.refreshList();
      }
      if (arg != undefined) {
        let tab = this.currentPage;
        if (tab.appCode == 'indexUrl') return;
        if (isIE || tab.method === 'iframe') {
          if (arg && arg === 'pageData') {
            let iframe = document.getElementById(tab.id || tab.appCode);
            let source = tab.url;
            if (source && !util.startWith(source, ['http', 'https'], true)) {
              source = location.origin + source.replace('./', '/');
            }
            !iframe && (iframe = document.getElementById(this.iframeId));
            iframe &&
              iframe.contentWindow.postMessage(
                { method: 'pageData' },
                source || '*'
              );
          } else {
            this.$set(this.currentPage, 'url', util.handlerUrl(tab.url));
          }
          return;
        }
        if (tab.method === 'wujie' && tab.appCode) {
          if (arg && arg === 'pageData') {
            WujieVue.$emit('pageData', tab);
          } else {
            // window.document
            //   .querySelector(`iframe[name=${tab.appCode}]`)
            //   .contentWindow.location.reload(true);
            let url = tab.url;
            // 如果传入了路由参数，需要更新 URL
            if (arg && typeof arg === 'object' && arg.path) {
              url = this.buildWujieUrl(tab.url, arg);
            }

            tab.url = '';
            this.$nextTick(() => {
              tab.url = util.handlerUrl(url);
            });
          }
          return;
        }
        if (tab.method === 'router') {
          if (arg && arg === 'pageData') {
            const bus = this.bus || this.$root.Bus;
            bus.$emit('pageData', tab);
          } else {
            this.$set(this.currentPage, 'keys', util.uuid());
          }
        }
      }
    },
    /**
     * @desc:构建 Wujie 子应用 URL（处理路由参数）
     * @param {String} baseUrl - 基础 URL
     * @param {Object} routeInfo - 路由信息 { path, params, query }
     * @returns {String} 拼接后的完整 URL
     **/
    buildWujieUrl(baseUrl, routeInfo) {
      const { path, params = {}, query = {} } = routeInfo;

      if (!path) {
        return baseUrl;
      }

      // 1. 处理 path + params（Vue Router 风格：params 作为路径参数）
      let fullPath = path;

      // 如果 params 中有值，将其拼接到 path 后面
      // 例如：path='/aa/bb', params={action:'action', id:'ddd', did:'33333'}
      // 结果：'/aa/bb/action/ddd/33333'
      const paramValues = Object.values(params).filter(
        (val) => val !== undefined && val !== null
      );
      if (paramValues.length > 0) {
        // 确保 path 不以 / 结尾
        const cleanPath = path.endsWith('/') ? path.slice(0, -1) : path;
        fullPath = cleanPath + '/' + paramValues.join('/');
      }

      // 2. 处理 query 参数
      const queryKeys = Object.keys(query);
      if (queryKeys.length > 0) {
        const queryString = queryKeys
          .map(
            (key) =>
              `${encodeURIComponent(key)}=${encodeURIComponent(query[key])}`
          )
          .join('&');
        fullPath += '?' + queryString;
      }

      // 3. 从 baseUrl 中提取基础部分（去掉 hash 路由部分）
      // 例如：baseUrl = 'http://example.com/app#/old/path'
      // 提取：'http://example.com/app#'
      let baseUrlPrefix = baseUrl;
      const hashIndex = baseUrl.indexOf('#');
      if (hashIndex > -1) {
        baseUrlPrefix = baseUrl.substring(0, hashIndex + 1); // 保留 #
      }

      // 4. 拼接最终 URL
      return baseUrlPrefix + fullPath;
    },
    /**
     * @desc:删除iframe
     * @author huangbo
     * @date 2024年9月7日
     **/
    handleRemove(name) {
      let len = this.tabs.length - 1;
      let i = util.indexOfObj(this.tabs, name, 'id,code,appCode');
      if (i > -1) {
        this.tabs.splice(i, 1);
        if (this.tabs.length == 0) {
          this.activeName = '';
        } else if (i == len) {
          this.activeName = this.tabs[len - 1].id;
        } else {
          this.activeName = this.tabs[i].id;
        }
      }
    },
    /**
     * @desc:tabs鼠标右键事件
     * @author huangbo
     * @date 2024年9月7日
     **/
    handleContextmenu(tabs, e) {
      let disabled = {};
      let index = parseInt(tabs.index, 10);
      if (index == 0) {
        disabled.left = true;
      }
      if (index == this.tabs.length - 1) {
        disabled.right = true;
      }
      if (this.tabs.length == 1) {
        disabled.other = true;
      }
      if (this.tabs[index].id != this.activeName) {
        disabled.refresh = true;
      }
      this.isDisabled = disabled;
      this.$refs.tabsHandler.$el.style.setProperty('left', `${e.x}px`);
      this.$refs.tabsHandler.$el.style.setProperty('top', `${e.y}px`);
      this.showTabsHandler = true;
      this.pane = index;
      window.addEventListener('click', this.closeTabsEvents);
    },
    /**
     * @desc:tabs页签事件
     * @author huangbo
     * @date 2024年9月7日
     **/
    handleTabsEvents(num) {
      if (this.pane !== null) {
        this.tabs = events[num](this.tabs, this.pane, this);
      }
      this.showTabsHandler = false;
      window.removeEventListener('click', this.closeTabsEvents);
    },

    /**
     * @desc:关闭页签事件面板
     * @author huangbo
     * @date 2024年9月7日
     **/
    closeTabsEvents(e) {
      if (
        e.target.parentNode != this.$refs.tabsHandler.$el &&
        e.target.parentNode.parentNode != this.$refs.tabsHandler.$el
      ) {
        this.showTabsHandler = false;
      }
      window.removeEventListener('click', this.closeTabsEvents);
    },

    /**
     * @desc:tabs页签点击事件
     * @author huangbo
     * @date 2024年9月7日
     **/
    handleTabClick() {
      this.active = '';
      this.subMenus = null;
      this.showMenu = false;
    },
    /**
     * @desc:handler工具栏点击事件
     * @author huangbo
     * @date 2024年9月7日
     **/
    handleClick(res) {
      const { type, event, open, link } = res;
      if (event) {
        event();
      } else if (open) {
        util.win.open(open);
      } else if (link) {
        util.win.open(link, '_self');
      } else {
        switch (type) {
          case 'quit':
            this.handleQuit();
            break;
          case 'online':
            this.showMsg = false;
            this.showSet = false;
            this.dialog = {
              title: '查看在线人员',
              show: true,
              src: this.onlineUrl
            };
            break;
          case 'notice':
            this.showMsg = !this.showMsg;
            this.showSet = false;
            break;
          case 'index':
            // util.win.open(this.doorIndex, '_self');
            if (this.appCodes == 'indexUrl') {
              this.count++;
            } else {
              this.currentPage = { ...this.homePage };
              this.appCodes = 'indexUrl';
            }
            break;
          case 'userinfo':
            this.$refs.user.handleOpen();
            break;
          case 'set':
            this.showSet = !this.showSet;
            this.showMsg = false;
            break;
          case 'home':
            let i = util.indexOfObj(this.tabs, this.homePage.id, 'id');
            if (i == -1) {
              this.tabs.unshift(this.homePage);
            } else {
              let tab = this.tabs[i];
              if (tab.method === 'iframe') {
                this.$set(this.tabs[i], 'url', util.handlerUrl(tab.url));
              }
              if (tab.method === 'wujie' && tab.appCode) {
                window.document
                  .querySelector(`iframe[name=${tab.appCode}]`)
                  .contentWindow.location.reload(true);
              }
              if (tab.method === 'router') {
                this.$set(this.tabs[i], 'keys', util.uuid());
              }
            }
            this.activeName = this.homePage.id;
            this.showMsg = false;
            this.showSet = false;
            this.active = '';
            this.subMenus = null;
            this.showMenu = false;
            break;
          case 'search':
            this.showSearch = true;
            this.showMsg = false;
            this.showSet = false;
            break;
          case 'ai':
            this.handlerSetDrawer(this._aiConfig, 'ai', 'rtl');
            break;
          case 'im':
            this.handlerSetDrawer(this.imConfig, 'im', 'rtl');
            break;
          case 'goView':
            util.win.open(res.path, '_blank');
            break;
        }
      }
      this.$emit('handler-click', res);
    },
    /**
     * @desc:退出登录
     * @author huangbo
     * @date 2024年9月7日
     **/
    handleQuit() {
      this.$confirm('确定退出吗?', '退出系统', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let iframes = document.getElementsByTagName('iframe');
          for (let i = 0; i < iframes.length; i++) {
            let src = iframes[i] ? iframes[i].src : null;
            let origin = util.win.location.origin;
            if (
              src &&
              util.startWith(src, 'http') &&
              src.indexOf(origin) === -1
            ) {
              iframes[i] && iframes[i].contentWindow.postMessage('logout', '*');
            }
            break;
          }
          if (this.singleLogout) {
            for (let i = 0; i < this.singleLogout.length; i++) {
              let iframe = document.createElement('iframe');
              iframe.style.display = 'none';
              iframe.src = this.singleLogout[i];
              document.body.appendChild(iframe);
            }
          }
          util
            .ajax({ method: 'post', url: logout })
            .then((res) => {
              if (res.rCode == 0) {
                util.removeStorage([
                  'Authorization',
                  'token',
                  'ssId',
                  'userId',
                  'userName',
                  'auth',
                  'deviceUnique',
                  'menus',
                  'useCaseCodes',
                  'mainConfig',
                  'jump'
                ]);
                if (this.onQuit && typeof this.onQuit === 'function') {
                  this.onQuit();
                } else {
                  try {
                    const loginPage =
                      util.getStorage('login') || util.getStorage('loginPage');
                    if (loginPage) {
                      let src;
                      if (!util.startWith(loginPage, ['http', '/'], true)) {
                        let pathname = util.getWinTop().location.pathname;
                        if (pathname !== '/') {
                          pathname = pathname.split('/');
                          pathname.splice(pathname.length - 1);
                          pathname = pathname.join('/');
                          src = pathname + '/' + loginPage.replace('./', '');
                        } else {
                          src = pathname + loginPage.replace('./', '');
                        }
                      } else {
                        src = loginPage;
                      }
                      util.getWinTop().location.href = src;
                    } else if (
                      util.getWinTop().location.href.indexOf('main.html') > -1
                    ) {
                      util.getWinTop().location.href = './login.html';
                    } else {
                      const hash = util.getWinTop().location.hash;
                      if (hash) {
                        const len = util
                          .getWinTop()
                          .location.href.indexOf(hash);
                        util.getWinTop().location.href =
                          util.win.location.href.slice(0, len) + '#/login';
                      } else {
                        util.getWinTop().location.href = '/login.html';
                      }
                    }
                  } catch (error) {
                    util.getWinTop().postMessage({ type: 1 }, '*');
                  }
                }
              }
            })
            .catch((err) => {
              if (err.message && err.message !== 'canceled') {
                this.$message.error(err.message);
              }
            });
        })
        .catch((e) => {});
    },
    /**
     * @desc:主题、消息回调
     * @author huangbo
     * @date 2024年9月7日
     **/
    handleChange(res) {
      const { type, value } = res;
      switch (type) {
        case 'theme':
          this.setTheme(value);
          break;
        case 'ignore':
          this.$set(this.handleNums, 'notice', 0);
          break;
      }
    },
    /**
     * @desc:菜单布局样式切换
     * @author huangbo
     * @date 2024年9月7日
     **/
    handleLayout(res, active) {
      if (active) {
        localStorage.setItem('layout', active);
        localStorage.setItem('layoutType', active);
      }
      this.$emit('chang-layout', res, active);
    },
    /**
     * @desc:消息修改总数
     * @author huangbo
     * @date 2024年9月7日
     **/
    handleMenuTips(id, num) {
      if (num) {
        this.$set(this.menuTips, id, num);
      } else {
        let n = parseInt(this.menuTips[id], 10) - 1;
        this.$set(this.menuTips, id, n);
      }
    },
    /**
     * @desc:处理即时消息
     * @author huangbo
     * @date 2024年9月7日
     **/
    handleOpened(res) {
      if (res === undefined) {
        this.sysMsg = [];
      } else if (res == false && this.sysMsg.length) {
        this.sysMsgOut = setTimeout(() => {
          this.sysMsg = [];
        }, 3000);
      } else if (this.sysMsgOut) {
        clearTimeout(this.sysMsgOut);
      }
    },
    /**
     * @desc:菜单点击事件
     * @author huangbo
     * @date 2024年9月7日
     * @param {*} res 菜单点击事件参数
     * @param {*} method 菜单点击事件方法
     * 1.顶部菜单点击跳转已经实现
     * 2.其他地方点击跳转,需要选中跳转的一二级菜单
     **/
    handleSelect(res, params = {}) {
      const node = res.node ? res.node : res;
      if (node.urlopenmode == 1 || node.openModel == 1) {
        util.win.open(node.url || node.menuurl);
      } else if (node.urlopenmode == 2 || node.openModel == 2) {
        util.win.open(node.url || node.menuurl, '_self');
      } else {
        let apps = node;
        let param = params;
        let reload = true;
        if (typeof node === 'string') {
          apps = node.split(',');
        } else if (util.isObject(node)) {
          const appCode = node.appCode || node.menuCode;
          const id = node.id || node.menuId;
          apps = appCode
            ? Array.isArray(appCode)
              ? appCode
              : appCode.split(',')
            : [id];
          node.param && (param = { ...node.param, ...params });
          reload = Object.prototype.hasOwnProperty.call(node, 'reload')
            ? node.reload
            : true;
        }

        const { currentPage, fourthTabs } = this.findMenuById(
          apps[apps.length - 1]
        );
        // console.log('fourthTabs', fourthTabs, 'currentPage', currentPage);
        if (currentPage) {
          this.currentPage = {};
          this.fourthTabs = [];
          if (currentPage.fourthTabs && currentPage.fourthTabs.length > 0) {
            this.fourthTabs = currentPage.fourthTabs;
            this.currentPage = this.setIframeType(this.fourthTabs[0]);
            this.appCodes = this.currentPage.appCode;
            if (param) {
              this.currentPage.url = util.handlerUrl(
                this.currentPage.url,
                param
              );
            }
            this.tabActiveName = this.currentPage.id;
            this.appCodes = this.currentPage.appCode || this.currentPage.id;
          } else {
            this.fourthTabs = fourthTabs;
            this.currentPage = this.setIframeType(currentPage);
            this.appCodes = this.currentPage.appCode;
            if (param) {
              this.currentPage.url = util.handlerUrl(
                this.currentPage.url,
                param
              );
            }
            this.tabActiveName = this.currentPage.id;
          }
        } else {
          this.$alert('没有关联菜单，请联系管理员！', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          }).catch(() => {});
        }
      }
    },
    findMenuById(res) {
      let targetMenu = null;
      let siblingMenus = [];
      let transformedMenus = this.menus;
      // 递归查找函数
      function searchMenu(menuList) {
        for (let menu of menuList) {
          // 检查是否为一级菜单
          if (menu.url === res || menu.id === res || menu.appCode === res) {
            targetMenu = { ...menu, level: 1 };
            siblingMenus = transformedMenus;
            return true;
          }

          // 检查是否为二级菜单
          if (menu.children) {
            for (let level2Menu of menu.children) {
              if (
                level2Menu.url === res ||
                level2Menu.id === res ||
                level2Menu.appCode === res
              ) {
                targetMenu = {
                  ...level2Menu,
                  level: 2
                };
                siblingMenus = menu.children;
                return true;
              }

              // 检查是否为三级菜单（在fourthTabs中）
              if (level2Menu.fourthTabs) {
                const foundInTabs = level2Menu.fourthTabs.find(
                  (tab) =>
                    tab.id === res || tab.appCode === res || tab.url == res
                );
                if (foundInTabs) {
                  targetMenu = {
                    ...foundInTabs,
                    level: 3,
                    parentId: level2Menu.id
                  };
                  siblingMenus = level2Menu.fourthTabs;
                  return true;
                }
              }
            }
          }
        }
        return false;
      }

      // 开始查找
      searchMenu(this.menus);

      return {
        currentPage: targetMenu,
        fourthTabs: siblingMenus // 不需要过滤自身
      };
    },
    handleLoadIframe(item) {
      this.$set(item, 'loading', false);
    }
  },
  beforeDestroy() {
    clearTimeout(this.timer);
    this.timer = null;
    if (this.webSocket) {
      this.webSocket.destroy();
    }
  }
};
</script>

<style lang="scss" scoped></style>
