<template>
  <div
    class="es-main"
    ref="esMain"
    :class="{ 'es-main-topside': layout === 'topside' }"
  >
    <div
      v-if="showHeader"
      class="es-main-header"
      :style="{ backgroundImage: headerImg ? 'url(' + headerImg + ')' : '' }"
    >
      <img
        class="es-main-logo"
        :src="logoUrl"
        v-if="layout !== 'topside' && logoUrl"
      />
      <div class="es-main-top-nav">
        <es-menu
          v-if="navs.length"
          class="es-fourth-tabs"
          mode="horizontal"
          :icons="icons"
          :menu-icon="menuIcon"
          :sub-icon="subIcon"
          :popperClass="`el-menu--popup-${layout}`"
          :data="navs"
          :deep="layout === 'topnav'"
          :height="layout === 'topnav' ? '370px' : undefined"
          :default-active="topActive"
          @select="
            (res) => {
              handleSelect(res, 'nav');
            }
          "
        ></es-menu>
      </div>
      <es-handler
        :job-scrollbar="jobScrollbar"
        :userModel="userModel"
        :hide="hide"
        :singleLogout="singleLogout"
        :subSystem="subsystem"
        :contact="contact"
        :online="online"
        :application="application"
        :storage="storage"
        :noticeNum="notice"
        :data="handleData"
        :max-height="_maxHeight"
        @visible-change="handleVisibleChange"
        @change="handleJobChange"
        @select="
          (res) => {
            handleSelect(res, 'sys');
          }
        "
        @click="handleClick"
      ></es-handler>
    </div>
    <div class="es-main-default-box" v-if="reset">
      <div class="es-main-left" v-if="layout !== 'topnav' && showSide">
        <div
          class="es-main-side"
          :class="{ 'es-main-topside': layout === 'topside' }"
          v-if="layout === 'topside' || layout === 'side'"
        >
          <div class="es-main-side-logo" v-if="layout === 'topside'">
            <img class="es-main-logo" :src="logoUrl" v-if="logoUrl" />
          </div>
          <es-handle-user
            :data="{ type: 'user' }"
            :userModel="userModel"
            @click="handleClick"
          ></es-handle-user>
        </div>
        <es-nav
          v-if="showMenu"
          :hide-sub-menu="hideSubMenu"
          :is-top="layout == 'topside'"
          :overlap="layout == 'side'"
          :data="menu"
          :default-active="active"
          :width="navsWidth"
          :nav-width="_navWidth"
          :icons="icons"
          :menu-icon="menuIcon"
          :sub-icon="subIcon"
          :biserial="biserial"
          :title="showNavTitle ? title : false"
          :showCollapse="
            showNavTitle ? (layout == 'side' ? false : showCollapse) : false
          "
          :menu-tips="menuTips"
          :is-default="isDefault"
          :paddingLeft="navPaddingLeft"
          @open="
            (res) => {
              handleSelect(res, 'menu', true);
            }
          "
          @trigger="
            (res) => {
              handleSelect(res, 'sub');
            }
          "
          @select="
            (res) => {
              handleSelect(res, 'menu');
            }
          "
        >
        </es-nav>
      </div>
      <div class="es-main-body">
        <div v-if="fourthTabs" class="es-fourth-tabs">
          <es-menu
            mode="horizontal"
            :data="tabs"
            :titleIcons="false"
            :default-active="tabsId"
            :menu-icon="menuIcon"
            :menu-tips="menuTips"
            @select="
              (res) => {
                handleSelect(res, 'tabs');
              }
            "
          ></es-menu>
        </div>
        <div class="es-body" :class="{ 'es-body-wrapper': showJobs }">
          <div
            class="es-body-main"
            v-loading="pageLoading"
            element-loading-background="rgba(0, 0, 0, 0.5)"
            v-if="showPage"
          >
            <iframe
              v-if="method === 'iframe'"
              :id="iframeId"
              :name="iframeId"
              frameborder="0"
              width="100%"
              height="100%"
              :src="page"
            ></iframe>
            <template v-else-if="method === 'wujie' && refresh">
              <es-wujie
                :show="true"
                :props="wjProps"
                :attrs="wjAttrs"
                :name="wjName"
                :url="page"
                v-bind="$attrs"
              ></es-wujie>
            </template>
            <template v-else-if="method === 'router' && refresh">
              <router-view v-if="!isKeepAlive" :key="routerKey" />
              <keep-alive>
                <router-view v-if="isKeepAlive" :key="routerKey" />
              </keep-alive>
            </template>
          </div>
          <message
            v-if="showMsg"
            ref="message"
            :total.sync="notice"
            :visible.sync="showMsg"
            :winopen="winopen"
            @ignore="handleChange"
            @handle="handleMenuTips"
          ></message
          ><!-- AI/IM -->
          <el-drawer
            class="es-public-drawer"
            :direction="drawer.direction"
            modal-class="es-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>
    </div>
    <settings
      v-bind="$attrs"
      layout-type="default"
      :active="layout"
      :theme="color"
      :predefine="themes"
      :visible.sync="showSets"
      @change="handleChange"
      @layout="handleLayout"
    ></settings>
    <es-dialog
      v-if="showUserInfo"
      title="用户信息配置"
      :height="userHeight"
      :visible.sync="showUserInfo"
    >
      <slot name="user">
        <userinfo
          v-bind="$attrs"
          :contents="userInfoContents"
          @change="handleUserModel"
          @success="reGetConfig"
        >
          <slot name="userInfo"></slot>
        </userinfo>
      </slot>
    </es-dialog>
    <notice :data="sysMsg" :winopen="winopen" @opened="handleOpened"></notice>
    <es-dialog
      class="es-public-search-dialog"
      :visible.sync="showSearch"
      size="lg"
    >
      <search
        :menus="menus"
        :menuIcon="menuIcon"
        @select="handleOnSearch"
      ></search>
    </es-dialog>
    <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>

    <es-enable-drag
      @click="handlerSetDrawer(_aiConfig, 'ai')"
      v-if="_aiConfig && showAi"
    >
      <div class="es-ai-icon" slot="handler">
        <img class="es-ai-image" :src="_aiConfig.icon" />
      </div>
    </es-enable-drag>
  </div>
</template>
<script>
import userinfo from './userinfo.vue';
import settings from '../public/settings.vue';
import message from './message.vue';
import notice from './notice.vue';
import online from '../public/online.vue';
import search from '../public/search.vue';
import {
  //authCenter,
  wss,
  topic,
  mainConfig,
  updateUserCustomInfo,
  getComplexApplications,
  getComplexApplicationsNew
} 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 log = util.getParams('console');
export default {
  name: 'MainDefault',
  inheritAttrs: false,
  provide() {
    return {
      esMain: this,
      refresh: this.handleRefresh,
      jumpMenu: this.jumpMenu
    };
  },
  components: {
    userinfo,
    settings,
    message,
    notice,
    online,
    search
  },
  props: {
    //im用例编码
    imUseCaseCode: String,
    //ai用例编码
    aiUseCaseCode: String,
    jobScrollbar: Boolean,
    maxHeight: String,
    //菜单导航地址
    menuUrl: String,
    //菜单展开关闭图标
    icons: Object,
    //菜单前置默认图标
    menuIcon: {
      type: String,
      default: 'es-icon-application'
    },
    //子菜单是否显示前置图标
    subIcon: {
      type: Boolean,
      default: true
    },
    //logo
    logo: String,
    //菜单显示类型
    scene: {
      type: String,
      default: 'default'
    },
    //host
    host: {
      type: String,
      default: ''
    },
    param: {
      type: Object,
      default() {
        return {};
      }
    },
    header: {
      type: Boolean,
      default: true
    },
    sideNav: {
      type: Boolean,
      default: true
    },
    //操作栏配置
    handleData: Array,
    //本地导航
    data: Array,
    //头部背景图片
    headerImage: String,
    //默认主题颜色
    theme: {
      type: String,
      default: '#409eff'
    },
    //主题颜色选择颜色集合
    themes: Array,
    //需要隐藏的头部功能
    hides: {
      type: Object,
      default() {
        return {};
      }
    },
    //储存数据
    storage: {
      type: String,
      default() {
        return util.getStorage('storage');
      }
    },
    //是否启用子应用菜单接口
    application: {
      type: Boolean,
      default: false
    },
    //是否显示设置按钮
    set: {
      type: Boolean,
      default: true
    },
    //websocket
    socket: {
      type: Boolean,
      default: true
    },
    //无界微前端属性
    wjProps: Object,
    wjAttrs: Object,
    //socket调试
    console: Boolean,
    //消息办理是否采用window.open的方式打开
    winopen: {
      type: Boolean,
      default: true
    },
    //获取用户信息的接口
    mainConfig: {
      type: String,
      default: mainConfig
    },
    iframeId: {
      type: String,
      default: 'stage'
    },
    routePath: {
      type: String,
      default: '/main'
    },
    setFirstAsDefault: {
      type: Boolean,
      default: true
    },
    pathUrl: {
      type: String,
      default: '/primary'
    },
    keepAlive: Boolean,
    loadWujie: {
      type: Boolean,
      default: true
    },
    downgrade: {
      type: Boolean,
      default: true
    },
    remote: {
      type: Boolean,
      default: true
    },
    isCustomMain: Boolean,
    userHeight: {
      type: String,
      default: '740px'
    },
    history: {
      type: Boolean,
      default: true
    },
    loadHomePage: {
      type: Boolean,
      default: true
    },
    appCode: String,
    //菜单左边距
    navPaddingLeft: Number,
    navBoxWidth: {
      type: String,
      default: '230px'
    },
    navWidth: String,
    showCollapse: {
      type: Boolean,
      default: true
    },
    onlineView: {
      type: [String, Boolean],
      default: true
    },
    newVersion: Boolean,
    contacts: Object
  },
  computed: {
    showHeader() {
      return this.isHeader == 0 ? false : this.header;
    },
    _maxHeight() {
      if (this.maxHeight) {
        return this.maxHeight;
      }
      return String(document.body.clientHeight - 77);
    },
    showSide() {
      return this.isSide !== null ? this.isSide : this.sideNav;
    },
    isHomePage() {
      if (util.getParams('applicationid') || util.getParams('applicationId')) {
        return false;
      }
      if (util.getStorage('mainConfig')) {
        let hash = util.win.location.hash;
        if (
          hash &&
          hash.split('?')[0] !== '#/' &&
          hash.split('?')[0] !== '#/main'
        ) {
          return false;
        }
      }
      return true;
    },
    navsWidth() {
      return this.layout === 'topside' ? this.navBoxWidth : undefined;
    },
    _navWidth() {
      return this.layout === 'side'
        ? this.navBoxWidth
        : this.layout === 'topside'
        ? '0'
        : this.navWidth;
    },
    showNavTitle() {
      return this.layout !== 'topside';
    },
    //tabs菜单
    fourthTabs() {
      return this.tabs.length;
    },
    //菜单接口
    action() {
      if (this.menuUrl) {
        return this.menuUrl;
      }
      if (this.application) {
        return getComplexApplicationsNew;
      }
      return getComplexApplications;
    },
    //是否双列右侧菜单
    biserial() {
      if (
        this.layout === 'subsystem' ||
        this.layout === 'topside' ||
        this.application
      ) {
        return false;
      } else {
        return true;
      }
    },
    //隐藏操作按键
    hide() {
      let topRightToolHide = {};
      if (this.topRightToolHide) {
        topRightToolHide = JSON.parse(
          this.topRightToolHide.replace(
            /(['"])?([a-zA-Z0-9_]+)(['"])?:/g,
            '"$2":'
          )
        );
      }

      let hides = {
        im: this.imConfig
          ? this.imUseCaseCode
            ? this.useCaseCodes.indexOf(this.imUseCaseCode) == -1
            : false
          : true,
        set: !this.showSet,
        index: this.doorIndex ? false : true,
        system: true,
        home: this.homePage ? 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, ...topRightToolHide };
    },
    logoUrl() {
      if (this.mainLogo) {
        return this.mainLogo;
      }
      return this.logo;
    },
    isConsole() {
      return log ? true : this.console;
    },
    onlineUrl() {
      if (this.onlineView) {
        return typeof this.onlineView == 'string' ? this.onlineView : '';
      }
      return false;
    },
    //人工智能配置
    _aiConfig() {
      return this.aiConfig
        ? {
            ...this.aiConfig,
            icon: 'data:image/png;base64, '
          }
        : false;
    },
    showAi() {
      return this.aiUseCaseCode
        ? this.useCaseCodes.indexOf(this.aiUseCaseCode) > -1
        : true;
    }
  },
  watch: {
    data: {
      deep: true,
      handler() {
        !this.remote && this.renderMenu();
      }
    },
    menuTips: {
      immediate: true,
      deep: true,
      handler(val) {
        if (Object.keys(val).length && this.menus.length) {
          this.setTips(this.menus);
        }
      }
    },
    color: {
      immediate: true,
      handler(val) {
        if (this.set) {
          localStorage.setItem('theme', val);
          util.updateTheme(val);
        }
      }
    },
    scene(val) {
      if (val) {
        this.layout = val.toLowerCase();
      }
    }
  },
  data() {
    return {
      isIE: isIE,
      useCaseCodes: util.getStorage('useCaseCodes'),
      showJobs: false,
      layout: this.scene.toLowerCase(),
      themeJSON: {
        logo: { comp: '', data: {} },
        topNav: { comp: '', data: {} },
        leftNav: { comp: '', data: {} },
        copyright: { comp: '', data: {} }
      },
      pageLoading: false,
      wjName: 'singlespa',
      menus: '',
      //头部导航
      navs: [],
      //头部默认选择
      topActive: '',
      //子系统菜单
      subsystem: [],
      //头部子系统子导航默认选中项
      sysId: '',
      //导航默认选择
      active: [],
      //完整导航选中的ID
      actives: [],
      //初始默认选中菜单id
      defaultActive: [],
      //侧边导航
      menu: [],
      //菜单名称
      title: '',
      //菜单提醒气泡
      menuTips: {},
      //面包屑导航
      tabs: [],
      //页签导航默认选中值
      tabsId: '',
      //路由类型
      method: 'router',
      //页面地址
      page: '',
      //选中的地址
      selectPage: '',
      //主页面
      homePage: '',
      isLoadHomePage: this.loadHomePage,
      //header背景
      mainLogo: null,
      headerImg: this.headerImage,
      //在线人数
      online: 1,
      //通知数
      notice: 0,
      //是否显示消息列表框
      showMsg: false,
      //即时消息
      sysMsg: [],
      //搜索
      showSearch: false,
      //定时关闭及时消息对象
      sysMsgOut: null,
      //额外信息数据
      extraData: '',
      //用户信息
      userModel: null,
      //刷新路由
      refresh: true,
      //显示设置面板
      showSets: false,
      //当前设置的主题
      color: util.getStorage('theme') ? util.getStorage('theme') : this.theme,
      //显示用户信息
      showUserInfo: false,
      userInfoContents: undefined,
      //是否展示侧边导航
      showMenu: true,
      props: {},
      menuType: '',
      customMenu: [],
      //是否首次加载
      isDefault: true,
      reset: true,
      isKeepAlive: this.keepAlive,
      routerKey: '',
      defaultwjprops: {},
      isTabs: false,
      isHeader: '',
      isSide: null,
      navIds: null,
      timer: null,
      pid: null,
      showPage: false,
      webSocket: null,
      dialog: {},
      hideSubMenu: false,
      doorIndex: '',
      topRightToolHide: '',
      showSet: this.set,
      contact: this.contacts,
      //公用窗口面板配置
      drawer: {
        visible: false,
        direction: 'ltr',
        ai: {},
        im: {},
        active: ''
      },
      //单点退出地址
      singleLogout: null,
      //人工智能配置
      aiConfig: null,
      //im配置
      imConfig: null,
      //子系统ID
      subSystemId: ''
    };
  },
  created() {
    const layout = localStorage.getItem('layout');
    layout && (this.layout = layout);
    let params = util.getParams() || {};
    if (params.homePage == 0) {
      this.isLoadHomePage = false;
    }
    this.isHeader = params.header;
    this.doorIndex = sessionStorage.getItem('doorIndex');
  },
  mounted() {
    this.handleListener();
    util.win.addEventListener('popstate', this.stateHandle, false);
    // this.
  },
  methods: {
    stateHandle() {
      util.win.location.reload();
    },
    menuSuccess(res) {
      this.menuType = 'custom';
      if (res && res.length) {
        this.customMenu = res;
        this.setMenu(res);
      }
    },
    // 将chalk写入到页面中
    handleColorToPage(globalThalk) {
      const thalk = document.getElementById('chalk-style');
      if (!thalk) {
        let ele = document.createElement('style');
        ele.setAttribute('id', 'chalk-style');
        ele.innerText = globalThalk;
        document.head.appendChild(ele);
      }
      // 如果设置过主题的话
      else {
        thalk.innerText = globalThalk;
      }
    },
    setTitle(id) {
      let node;
      for (let i = 0; i < this.menus.length; i++) {
        let item = this.menus[i];
        if (item.id == id) {
          this.title = item.text;
          node = item;
          break;
        }
      }
      return node;
    },
    renderMenu() {
      if (this.data !== undefined && this.data.length) {
        this.menus = JSON.parse(JSON.stringify(this.data));
        let applicationid =
          util.getParams('applicationid') || util.getParams('applicationId');
        if (applicationid) {
          var ids = this.getId(this.menus, applicationid);
          if (ids) {
            this.defaultActive = ids;
            //this.navIds = ids;
            this.setTitle(ids[0]);
          }
        } else if (sessionStorage.getItem('jump') && this.isHistory) {
          let ids = this.getId(this.menus, sessionStorage.getItem('jump'));
          if (ids) {
            this.defaultActive = ids;
            //this.navIds = ids;
            this.setTitle(ids[0]);
          }
        } else if (util.win.location.hash) {
          let hash = util.win.location.hash;
          if (hash) {
            hash = hash.split('?')[0];
          }
          if (hash !== '#/' && hash !== '#/main') {
            let ids = this.getId(this.menus, util.win.location.hash);
            if (ids) {
              this.defaultActive = ids;
              //this.navIds = ids;
              this.setTitle(ids[0]);
            }
          } else if (sessionStorage.getItem('jump') && this.isHistory) {
            let ids = this.getId(this.menus, sessionStorage.getItem('jump'));
            if (ids) {
              this.defaultActive = ids;
              //this.navIds = ids;
              this.setTitle(ids[0]);
            }
          }
        }
        this.setMenu(this.menus);
      }
    },
    //设置主题颜色
    setTheme(color) {
      if (!color) {
        return;
      }
      util
        .ajax({
          url: updateUserCustomInfo,
          params: { color: escape(color.toLowerCase()) },
          data: { color: escape(color.toLowerCase()) }
        })
        .then((res) => {
          if (res.rCode === 0) {
            this.color = color;
            localStorage.setItem('theme', color);
            let mainConfig = JSON.parse(util.getStorage('mainConfig'));
            mainConfig.userStyle.color = this.color;
            sessionStorage.setItem('mainConfig', JSON.stringify(mainConfig));
            this.$emit('setting', 'theme', this.color);
            this.$message({
              message: res.msg,
              type: 'success',
              duration: 2000
            });
          } else {
            let msg = res.msg || '系统错误，请联系管理员！';
            this.$message.error(msg);
          }
        })
        .catch((err) => {
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    },
    //切换兼职身份
    handleJobChange() {
      if (this.webSocket) {
        this.webSocket.destroy();
      }
    },
    //显示隐藏设置面板
    handleSet() {
      this.showSets = !this.showSets;
    },
    setConfig(results) {
      sessionStorage.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,
          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.results[i] = results[i].split(',');
        }
        if (i === 'indexUrl' && results[i]) {
          this.homePage = results[i];
        }
        if (i === 'doorIndex' && results[i]) {
          window.open(results[i]);
          this.doorIndex = results[i];
        }
        if (i === 'subsystemName' && results[i]) {
          document.title = results[i];
        }
        if (i === 'subSystemId' && results[i]) {
          this.subSystemId = results[i];
          util.setStorage({ key: 'subSystemId', value: 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.color = color;
            }
          }
          if (results[i].indexUrl) {
            this.homePage = results[i].indexUrl;
          }
        }
        if (i === 'subsystemExtend' && results[i]) {
          if (results[i].singleLogout) {
            this.singleLogout = results[i].singleLogout.split(',');
          }
          if (results[i].themeColor) {
            this.color = unescape(results[i].themeColor).toLowerCase();
          }
          if (results[i].userInfoContents) {
            this.userInfoContents = 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].portalPage || results[i].portalpage) {
            this.doorIndex = results[i].portalPage || results[i].portalpage;
          }
          if (results[i].multipleVersion) {
            this.showSet = true;
          }
          if (results[i].topRightToolHide) {
            this.topRightToolHide = results[i].topRightToolHide;
          }
          if (results[i].contact) {
            let contact = JSON.parse(results[i].contact);
            let content = contact.content.split(',');
            this.contact = {
              ...contact,
              content
            };
          }
          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;
            }
            this.$nextTick(() => {
              // util.draggableMove({
              //   container: this.$refs.esMain,
              //   area: this.$refs.aiConfigArea,
              //   box: this.$refs.aiConfigBox
              // });
            });
          }
          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;
            }
          }
        }
        store.set(i, results[i]);
      }
      if (this.isLoadHomePage && this.homePage) {
        let applicationid =
          util.getParams('applicationid') || util.getParams('applicationId');
        let hash = util.win.location.hash;
        if (hash) {
          hash = hash.split('?')[0];
        }
        let jump = sessionStorage.getItem('jump');
        if (
          (!applicationid &&
            !this.appCode &&
            (!jump || !this.isHistory) &&
            (hash === '#/' || hash === '#/main')) ||
          jump == this.homePage
        ) {
          if (this.isHomePage) {
            if (this.menus && this.menus.length) {
              let ids = (ids = this.getId(this.menus, this.homePage));
              if (ids) {
                this.defaultActive = ids;
              } else {
                this.handleJump(this.homePage);
              }
              this.setMenu(this.menus);
            }
          }
        } else if (this.menus && this.menus.length) {
          this.setMenu(this.menus);
        }
      }
      this.userModel = results.userModel;
    },
    //初始用户配置及信息
    init(results, first) {
      this.setConfig(results);
      if (this.remote && first) {
        this.getMenu();
      } else {
        this.renderMenu();
      }
    },
    reGetConfig() {
      this.showUserInfo = false;
      util
        .ajax({ url: this.mainConfig })
        .then((res) => {
          if (res && res.rCode === 0) {
            const results = JSON.parse(JSON.stringify(res.results));
            this.setConfig(results, 1);
          } else {
            let msg = res.msg || '系统错误，请联系管理员！';
            this.$message.error(msg);
          }
        })
        .catch((err) => {
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    },
    /**
     * @desc 跳转菜单
     * @param {Object/String} [res]    - 菜单id（多个用,隔开）或url地址或系统菜单数据对象
     * @param {Boolean} [isUrl] - res是否是url地址
     * @param {Object} [param] - 拼接地址后的参数
     */
    jumpMenu(res, isUrl, param, hide) {
      if (this.showSide === false) {
        this.isSide = true;
      }
      if (hide !== undefined && hide !== null && hide !== '') {
        this.hideSubMenu = hide;
      }
      let option = { url: res, isUrl: isUrl, param: param };
      if (util.isObject(res)) {
        if (res.urlopenmode == 1) {
          util.win.open(res.url);
          return;
        } else if (res.urlopenmode == 2) {
          location.href = res.url;
          return;
        } else {
          option = { ...option, ...res };
        }
      }
      let ids;
      if (typeof option.url === 'string') {
        if (
          option.isUrl ||
          option.url.indexOf('.html') > -1 ||
          option.url.indexOf('.dhtml') > -1 ||
          option.url.indexOf('/#/') > -1 ||
          option.url.indexOf('#/') > -1
        ) {
          option.isUrl = true;
          ids = this.getId(this.menus, option.url);
          if (!ids) {
            if (
              option.url.indexOf('.html') === -1 &&
              option.url.indexOf('#/') === -1
            ) {
              this.method = 'iframe';
              this.refresh = false;
              this.page = option.url;
            } else {
              this.method = 'router';
              const routes = this.$router.options.routes;
              if (routes) {
                let path = this.hasRouter(routes, option.url);
                if (path) {
                  let params = util.getParams({ url: option.url });
                  this.$router.push({
                    path: path,
                    query: params
                  });
                } else {
                  if (this.loadWujie === false || (this.downgrade && isIE)) {
                    this.method = 'iframe';
                    this.refresh = false;
                    this.page = option.url;
                  } else {
                    this.method = 'wujie';
                    this.wjName = 'application' + Date.now();
                    this.page = this.host + option.url;
                  }
                }
              }
            }
            this.$nextTick(() => {
              this.refresh = true;
            });
            return;
          }
        } else {
          ids = option.url.split(',');
          if (ids.length == 1) {
            ids = this.getId(this.menus, option.url);
          }
        }
      } else {
        ids = option.url;
      }
      this.setDefault(this.menus, ids, option.param);
    },
    /**
     * @desc 获取菜单层级id
     * @param {Array} [menus]    - 系统菜单数据对象
     * @param {String} [url] - 菜单id或url地址
     */
    getId(menus, url) {
      if (!url) {
        return false;
      }
      for (let i = 0; i < menus.length; i++) {
        let item = menus[i];
        if (item.id === url || (item.appCode && item.appCode === url)) {
          if (item.url) {
            if (
              Object.prototype.hasOwnProperty.call(item, 'children') &&
              item.children.length
            ) {
              let id = this.getId(item.children, item.url);
              if (id) {
                if (typeof id === 'string') {
                  this.isTabs = false;
                }
                if (item.pid === 'root' || Array.isArray(id)) {
                  return [item.id].concat(id);
                } else if (typeof id === 'string') {
                  return [item.id, id];
                }
                return id;
              }
            } else if (
              Object.prototype.hasOwnProperty.call(item, 'fourthTabs') &&
              item.fourthTabs.length
            ) {
              let id = this.getId(item.fourthTabs, item.url);
              if (id) {
                if (typeof id === 'string') {
                  this.isTabs = true;
                }
                if (item.pid === 'root') {
                  return [item.id].concat(id);
                } else if (typeof id === 'string') {
                  return [item.id, id];
                }
                return id;
              }
            } else {
              return item.id;
            }
          } else {
            console.error(item);
            return false;
          }
        } else if (
          Object.prototype.hasOwnProperty.call(item, 'children') &&
          item.children.length
        ) {
          let id = this.getId(item.children, url);
          if (id) {
            if (typeof id === 'string') {
              this.isTabs = false;
            }
            if (item.pid === 'root' || Array.isArray(id)) {
              return [item.id].concat(id);
            } else if (typeof id === 'string') {
              return [item.id, id];
            }
            return id;
          }
        } else if (
          Object.prototype.hasOwnProperty.call(item, 'fourthTabs') &&
          item.fourthTabs.length
        ) {
          let id = this.getId(item.fourthTabs, url);
          if (id) {
            if (typeof id === 'string') {
              this.isTabs = true;
            }
            if (item.pid === 'root') {
              return [item.id].concat(id);
            } else if (typeof id === 'string') {
              return [item.id, id];
            }
            return id;
          }
        } else if (item.url == url) {
          return item.id;
        } else if (item.url && url.indexOf(item.url) > -1) {
          return item.id;
        } else {
          if (item.url) {
            try {
              let _url = new URL(item.url, window.location.origin);
              if (_url.hash == url) {
                return item.id;
              }
            } catch (error) {
              console.error(error, item);
            }
          }
        }
      }
      return false;
    },
    //获取应用导航菜单
    getMenu() {
      const menuData = store.get('nav');
      if (menuData && menuData.length) {
        this.menus = JSON.parse(JSON.stringify(menuData));
        this.setTips(this.menus);
        this.setMenu(this.menus);
        return;
      }
      let param = this.appCode ? { menuCode: this.appCode } : {};
      let params = { ...this.param, ...param };
      util
        .ajax({ url: this.action, params: params })
        .then((res) => {
          if (this.socket) {
            this.initWebSocket();
          }
          if (res.rCode === 0) {
            if (res.results && res.results.length) {
              this.menus = JSON.parse(JSON.stringify(res.results));
              this.setTips(this.menus);
              store.set('nav', JSON.parse(JSON.stringify(res.results)));
              this.setMenu(this.menus);
            } 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);
          }
        });
    },
    //设置默认左侧导航
    setMenu(res) {
      let applicationid =
        util.getParams('applicationid') || util.getParams('applicationId');
      if (applicationid) {
        let ids = this.getId(this.menus, applicationid);
        if (ids) {
          this.defaultActive = ids;
        }
      } else if (util.win.location.hash) {
        let hash = util.win.location.hash;
        if (hash) {
          hash = hash.split('?')[0];
        }
        if (hash !== '#/' && hash !== '#/main') {
          let ids = this.getId(this.menus, util.win.location.hash);
          if (ids) {
            this.defaultActive = ids;
            //this.navIds = ids;
            this.setTitle(ids[0]);
          }
        }
      } else if (sessionStorage.getItem('jump') && this.isHistory) {
        let ids = this.getId(this.menus, sessionStorage.getItem('jump'));
        if (ids) {
          this.defaultActive = ids;
          //this.navIds = ids;
          this.setTitle(ids[0]);
        }
      }
      if (this.defaultActive && this.defaultActive.length) {
        this.isDefault = false;
        this.setDefault(res, this.defaultActive);
      } else {
        if (this.homePage) {
          this.isDefault = this.isLoadHomePage;
          if (
            this.isLoadHomePage &&
            (!this.defaultActive || !this.defaultActive.length)
          ) {
            let ids = this.getId(this.menus, this.homePage);
            if (ids) {
              this.defaultActive = ids;
              this.isDefault = false;
              this.setDefault(res, this.defaultActive);
              return false;
            } else {
              this.handleJump(this.homePage);
            }
          }
        } else {
          this.isDefault = false;
        }
        if (this.layout === 'subsystem' || this.layout === 'topside') {
          if (this.layout === 'subsystem') {
            this.navs = [];
            if (this.menuType === 'custom') {
              this.subsystem = this.customMenu;
            } else {
              this.subsystem = res;
            }
          } else if (this.layout === 'topside') {
            this.subsystem = [];
            if (this.menuType === 'custom') {
              this.navs = this.customMenu;
              this.topActive = res[0].id;
            } else {
              this.navs = res;
              this.topActive = res[0].id;
            }
          }
          if (this.application) {
            for (let i = 0; i < res.length; i++) {
              if (res[i].hasPermission) {
                this.menu = res[i].children;
                this.title = res[i].text;
                break;
              }
            }
          } else {
            this.menu = res[0].children;
            this.title = res[0].text;
            this.$emit('getOriginParentMenu', {
              title: res[0].text,
              id: res[0].id
            });
          }
          if (!this.isDefault || (this.isDefault && !this.homePage)) {
            this.active = this.getFirst(this.menu[0]).id;
          }
        } else if (this.layout === 'topnav') {
          if (this.menuType === 'custom') {
            this.navs = this.customMenu;
            this.topActive = this.getFirst(res[0]).id;
          } else {
            this.navs = res;
            this.topActive = this.getFirst(res[0]).id;
          }
        } else {
          this.nav = [];
          this.subsystem = [];
          this.menu = res;
          if (!this.isDefault || (this.isDefault && !this.homePage)) {
            this.active = [this.menu[0].id];
            let id = this.getFirst(this.menu[0]).id;
            if (id && this.menu[0].id !== id) {
              this.active.push(id);
            } else {
              let hash = util.win.location.hash;
              if (hash) {
                hash = hash.split('?')[0];
                if (hash !== '#/' && hash !== '#/main') {
                  this.handleJump(hash);
                  return;
                }
              }
              let jump = sessionStorage.getItem('jump');
              if (jump) {
                this.handleJump(jump);
              } else {
                this.handleJump(
                  this.menu[0].url,
                  this.menu[0].urlopenmode,
                  this.menu[0]
                );
              }
            }
          }
        }
      }
    },
    //获取菜单第一条数据
    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) {
        return this.getFirst(obj.children[openIdex]);
      } else if (obj.fourthTabs && obj.fourthTabs.length) {
        if (this.layout === 'topnav') {
          return this.getFirst(obj.fourthTabs[openIdex]);
        } else {
          this.tabs = obj.fourthTabs;
          if (obj.url) {
            let tab = obj.fourthTabs.filter((item) => {
              return item.url === obj.url;
            })[0];
            if (tab) {
              this.tabsId = tab.id;
              this.handleJump(tab.url, tab.urlopenmode, tab);
            }
          } else if (
            this.tabs[0].urlopenmode !== 1 &&
            this.tabs[0].urlopenmode !== 2
          ) {
            this.tabsId = this.tabs[0].id;
            this.handleJump(
              this.tabs[0].url,
              this.tabs[0].urlopenmode,
              this.tabs[0]
            );
          }
        }
      } else if (obj.urlopenmode !== 1 && obj.urlopenmode !== 2) {
        this.tabs = [];
        this.handleJump(obj.url, obj.urlopenmode, obj);
      }
      return obj;
    },
    //遍历设置菜单气泡提醒
    setTips(obj) {
      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 = false;
        if (obj.children && obj.children.length) {
          obj.children.forEach((item) => {
            if (this.setTips(item)) {
              flag = true;
            }
          });
          if (flag) {
            this.$set(obj, 'tips', true);
            return true;
          }
        } else if (obj.fourthTabs && obj.fourthTabs.length) {
          obj.fourthTabs.forEach((item) => {
            if (this.setTips(item)) {
              flag = true;
            }
          });
          if (flag) {
            this.$set(obj, 'tips', true);
            return true;
          }
        } else {
          let tips = this.menuTips[obj.id] || this.menuTips[obj.appCode];
          if (tips && Number(tips)) {
            this.$set(obj, 'tips', tips);
            return true;
          }
        }
      }
      return false;
    },
    //设置默认导航页面
    setDefault(res, active, param) {
      this.navIds = JSON.parse(JSON.stringify(active));
      this.sysId = '';
      this.tabsId = '';
      this.active = '';
      this.getUrl(res, active[active.length - 1], param);
      if (
        this.layout === 'subsystem' ||
        this.layout === 'subSystem' ||
        this.layout === 'topnav' ||
        this.layout === 'topNav' ||
        this.layout === 'topside' ||
        this.layout === 'topSide'
      ) {
        if (this.layout === 'subsystem' || this.layout === 'subSystem') {
          this.navs = [];
          if (this.menuType === 'custom') {
            this.subsystem = this.customMenu;
            this.sysId = active[0];
          } else {
            this.subsystem = res;
            this.sysId = active[0];
          }
        } else if (
          this.layout === 'topnav' ||
          this.layout === 'topNav' ||
          this.layout === 'topside' ||
          this.layout === 'topSide'
        ) {
          this.subsystem = [];
          if (this.menuType === 'custom') {
            this.navs = this.customMenu;
            this.topActive = active[0];
          } else {
            this.navs = res;
            this.topActive = active[0];
          }
        }
        if (this.tabs.length || this.isTabs) {
          this.tabsId = active[active.length - 1];
          this.active = active.slice(1, active.length - 1);
        } else {
          this.active = active.slice(1);
        }
        for (let i = 0; i < res.length; i++) {
          if (res[i].id === active[0]) {
            this.menu = res[i].children;
            this.title = res[i].text;
            break;
          }
        }
      } else if (active && active.length) {
        this.navs = [];
        this.subsystem = [];
        this.menu = res;
        if (this.biserial) {
          this.active = active.slice(
            0,
            this.tabs && this.tabs.length ? active.length - 1 : active.length
          );
        } else {
          this.active = active.slice(1);
        }
        this.tabsId = active[active.length - 1];
      }
      this.showPage = true;
    },
    //获取页面类型及地址
    getUrl(res, active, param) {
      for (let i = 0; i < res.length; i++) {
        let item = res[i];
        if (item.id === active) {
          if (item.url) {
            this.handleJump(item.url, item.urlopenmode, item, param);
            return item.url;
          } else {
            console.error(item);
          }
        } else {
          if (item.children && item.children.length) {
            let url = this.getUrl(item.children, active, param);
            if (url) {
              this.tabs = '';
            }
          }
          if (item.fourthTabs && item.fourthTabs.length) {
            let url = this.getUrl(item.fourthTabs, active, param);
            if (url) {
              this.$set(this, 'tabs', item.fourthTabs);
            }
          }
        }
      }
      return false;
    },

    setUrl(url, param) {
      let obj = param ? param : {};
      let params = util.getParams({ url: url }, true);
      for (let i in params) {
        if (i != 'model' && i != 'view' && i != '_baseUrl') {
          obj[i] = params[i];
        }
      }
      let _url = params._baseUrl ? params._baseUrl : './primary.html';
      return util.urlJoinParams({ url: _url, param: obj });
    },
    handleVisibleChange(res) {
      this.showJobs = res;
    },
    //应用导航交互
    handleSelect(res, type, open) {
      const { node, fourthTabs } = res;
      if (!open) {
        if (
          node.extendData &&
          node.extendData.businessStatus == 0 &&
          node.extendData.businessWarnMsg
        ) {
          this.$alert(node.extendData.businessWarnMsg, '提示', {
            type: 'warning'
          });
          return;
        }
        this.isDefault = false;
        this.tabsId = '';
      }
      switch (type) {
        case 'nav':
          this.tabs = [];
          //this.active = '';
          if (this.layout === 'topside') {
            if (this.title !== node.text) {
              //this.navIds = [node.id];
              this.menu = node.children;
              this.active = node.id;
              this.title = node.text;
            }
            if (this.setFirstAsDefault) {
              let subNode = this.getFirst(node);
              if (subNode) {
                this.active = subNode.id;
                // this.navIds = [
                //   node.id,
                //   ...this.getId(node.children, subNode.url)
                // ];
              }
            }
          } else {
            //this.navIds = this.getId(this.menus, node.url);
            this.setTitle(this.navIds[0]);
            this.tabsId = fourthTabs ? node.id : '';
          }
          break;
        case 'sys':
          if (Number(node.urlopenmode) !== 1) {
            //this.navIds = [node.id];
            this.tabs = [];
            this.menu = node.children;
            if (this.title !== node.text) {
              this.active = '';
              this.title = node.text;
            }
            if (this.setFirstAsDefault) {
              let subNode = this.getFirst(node);
              if (subNode) {
                this.active = subNode.id;
                // this.navIds = [
                //   node.id,
                //   ...this.getId(node.children, subNode.url)
                // ];
              }
            }
            this.isSide = true;
          }
          break;
        case 'sub':
          this.hideSubMenu = false;
          //this.navIds = [node.id];
          if (node.url) {
            this.tabs = [];
          }
          if (this.title !== node.text) {
            this.active = [node.id];
            this.title = node.text;
          }
          if (this.setFirstAsDefault) {
            let subNode = this.getFirst(node);
            this.active = [node.id];
            if (subNode && node.id !== subNode.id) {
              //this.navIds = this.getId(this.menus, subNode.url);
              this.$set(this.active, 1, subNode.id);
            }
          }
          break;
        case 'menu':
          if (!open) {
            this.tabs = [];
            if (this.biserial) {
              this.$set(this.active, 1, node.id);
            } else {
              this.active = node.id;
            }
            if (node.url) {
              if (node.children && node.children.length) {
                let tab = node.children.filter((item) => {
                  return item.url === node.url;
                })[0];
                if (tab) {
                  if (this.biserial) {
                    this.$set(this.active, 1, tab.id);
                  } else {
                    this.active = tab.id;
                  }
                  //this.navIds = this.getId(this.menus, tab.url);
                }
              } else if (node.fourthTabs && node.fourthTabs.length) {
                this.tabs = [];
                let tab = node.fourthTabs.filter((item) => {
                  return item.url === node.url;
                })[0];
                if (tab) {
                  this.tabsId = tab.id;
                  this.$nextTick(() => {
                    this.tabs = node.fourthTabs;
                  });
                  //this.navIds = this.getId(this.menus, tab.url);
                } else {
                  //this.navIds = this.getId(this.menus, node.url);
                }
              }
            } else {
              if (node.fourthTabs.length) {
                this.tabsId = node.fourthTabs[0].id;
                this.$nextTick(() => {
                  this.tabs = node.fourthTabs;
                  this.handleJump(
                    this.tabs[0].url,
                    this.tabs[0].urlopenmode,
                    this.tabs[0]
                  );
                });
                //this.navIds = this.getId(this.menus, this.tabs[0].url);
              }
            }
          } else {
            if (this.setFirstAsDefault) {
              this.tabs = [];
              let subNode = this.getFirst(node);
              if (subNode) {
                if (this.biserial) {
                  this.$set(this.active, 1, subNode.id);
                } else {
                  this.active = subNode.id;
                }
                //this.navIds = this.getId(this.menus, subNode.url);
              }
            }
          }
          break;
        case 'tabs':
          this.tabsId = node.id;
          //this.navIds = this.getId(this.menus, node.url);
          break;
      }
      if (node.url) {
        this.selectPage = node.url;
        this.refresh = false;
        let type = Number(node.urlopenmode);
        if (type != 1) {
          this.drawer.visible = false;
        }
        this.handleJump(node.url, type, node);
      }
    },
    hasRouter(res, url) {
      if (!url) {
        return false;
      }
      if (Array.isArray(res)) {
        for (let i in res) {
          let path = this.hasRouter(res[i], url);
          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
          .replace(pathname[1], pathname[1].toLowerCase())
          .split('?')[0];
        if (res.path !== '/' && pathname == path) {
          return pathname;
        }
        if (res && Object.prototype.hasOwnProperty.call(res, 'children')) {
          let path = this.hasRouter(res.children, url);
          if (path) {
            return path;
          }
        }
      }
      return false;
    },
    //头部工具交互事件
    handleClick(res) {
      const { type } = res;
      switch (type) {
        //刷新
        case 'refresh':
          this.handleRefresh();
          break;
        case 'home':
          this.reset = false;
          if (this.homePage) {
            this.handleJump(this.homePage);
          }
          this.active = [];
          this.defaultActive = [];
          this.tabs = [];
          if (this.menus && this.menus.length) {
            this.setMenu(this.menus);
          }
          this.$nextTick(() => {
            this.reset = true;
          });
          break;
        case 'index':
          util.win.open(this.doorIndex, '_self');
          break;
        case 'user':
          this.showUserInfo = true;
          break;
        case 'online':
          this.dialog = {
            title: '查看在线人员',
            show: true,
            src: this.onlineUrl
          };
          break;
        case 'notice':
          this.showMsg = !this.showMsg;
          break;
        case 'set':
          this.handleSet();
          break;
        case 'search':
          this.showSearch = true;
          this.showMsg = 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);
    },
    //刷新子页面、子路由
    handleRefresh() {
      if (this.method === 'iframe') {
        this.page = util.handlerUrl(this.page);
      } else {
        this.refresh = false;
        this.$nextTick(() => {
          this.refresh = true;
        });
      }
    },
    //跳转页面
    handleJump(page, type, res, param) {
      this.navIds = this.getId(this.menus, page);
      console.log('handleJump page ', page);
      let prevPage = sessionStorage.getItem('jump');
      sessionStorage.setItem('jump', page);
      if (res) {
        if (res.fourthTabs && res.fourthTabs.length) {
          this.pid = res.id;
        } else {
          this.pid = res.pid;
        }
      }
      if (util.win.location.hash === page && prevPage === page) {
        this.refresh = true;
        return;
      }
      if (type == 1) {
        util.win.open(page);
      } else if (type == 2) {
        location.href = page;
      } else if (
        type == 3 ||
        this.loadWujie === false ||
        (this.downgrade && isIE)
      ) {
        this.method = 'iframe';
        this.refresh = false;
        this.page = util.handlerUrl(page, param);
      } else if (page) {
        let urls = page.split('?');
        if (urls[0].indexOf('.js') > 1) {
          this.method = 'wujie';
          this.wjName = 'singlespa';
          this.page = this.host + page;
          this.$nextTick(() => {
            this.refresh = true;
          });
        } else if (
          urls[0].indexOf('.dhtml') > 0 ||
          (urls[0].indexOf('.html') > 0 && urls[0].indexOf('.html#') === -1)
        ) {
          this.method = 'iframe';
          this.refresh = false;
          this.page = util.handlerUrl(page, param);
        } else {
          if (urls[0].indexOf('.html') === -1 && urls[0].indexOf('#/') === -1) {
            this.method = 'iframe';
            this.refresh = false;
            this.page = util.handlerUrl(page, param);
          } else {
            this.method = 'router';
            const routes = this.$router.options.routes;
            if (routes) {
              let path = this.hasRouter(routes, urls[0]);
              if (path) {
                let params = util.getParams({ url: page });
                if (param) {
                  params = { ...params, ...param };
                }
                if (res) {
                  this.routerKey = res.id;
                  if (Object.prototype.hasOwnProperty.call(res, 'keepAlive')) {
                    this.isKeepAlive = res.keepAlive;
                  }
                }
                this.$router.push({
                  path: path,
                  query: params
                });
                this.$nextTick(() => {
                  this.refresh = true;
                });
              } else {
                let urlopenmode = util.getParams({
                  url: page,
                  name: 'urlopenmode'
                });
                if (
                  this.loadWujie === false ||
                  (this.downgrade && isIE) ||
                  urlopenmode == 3
                ) {
                  this.method = 'iframe';
                  this.refresh = false;
                  this.page = util.handlerUrl(page, param);
                } else {
                  this.method = 'wujie';
                  this.wjName =
                    res && res.appCode ? res.appCode : 'application';
                  this.page = this.host + page;
                  this.$nextTick(() => {
                    this.refresh = true;
                  });
                }
              }
            } else {
              this.method = 'iframe';
              this.refresh = false;
              this.page = util.handlerUrl(page, param);
              this.$nextTick(() => {
                this.refresh = true;
              });
            }
          }
        }
      }
      this.$nextTick(() => {
        this.showPage = true;
      });
    },
    //设置回调
    handleChange(res) {
      const { type, value } = res;
      switch (type) {
        case 'theme':
          this.setTheme(value);
          break;
        case 'ignore':
          this.notice = 0;
          break;
      }
    },
    getFourthTabs(menus, id) {
      if (Array.isArray(menus)) {
        for (let i = 0; i < menus.length; i++) {
          let fourth = this.getFourthTabs(menus[i], id);
          if (fourth) {
            return fourth;
          }
        }
      } else {
        if (menus.fourthTabs && menus.fourthTabs.length && menus.id === id) {
          return menus;
        }
        if (menus.children && menus.children.length) {
          for (let i = 0; i < menus.children.length; i++) {
            let fourth = this.getFourthTabs(menus.children[i], id);
            if (fourth) {
              return fourth;
            }
          }
        }
      }
      return false;
    },
    handleLayout(layout, res, old) {
      this.$emit('chang-layout', layout);
      if (res == old || layout == 'simplicity') {
        return;
      }
      this.layout = res;
      localStorage.setItem('layout', res);
      localStorage.setItem('layoutType', res);
      switch (res) {
        case 'topnav':
          this.navs = this.menus;
          this.tabs = [];
          this.subsystem = [];
          this.topActive =
            this.navIds && this.navIds.length
              ? this.navIds[this.navIds.length - 1]
              : '';
          break;
        case 'subsystem':
          this.subsystem = this.menus;
          this.navs = [];
          this.tabs = [];
          if (this.navIds && this.navIds.length) {
            let node = this.setTitle(this.navIds[0]);
            this.active = JSON.parse(JSON.stringify(this.navIds)).slice(1);
            let tabs = this.getFourthTabs(this.menus, this.pid);
            if (tabs) {
              this.active.pop();
              this.tabs = tabs.fourthTabs;
              this.tabsId = this.navIds[this.navIds.length - 1];
            }
            this.menu = node.children;
            this.title = node.text;
          } else {
            //this.navIds = [this.menus[0].id]
            this.menu = this.menus[0].children;
            this.title = this.menus[0].text;
          }
          break;
        case 'topside':
          this.navs = this.menus;
          this.subsystem = [];
          this.tabs = [];
          if (this.navIds && this.navIds.length) {
            let node = this.setTitle(this.navIds[0]);
            this.active = JSON.parse(JSON.stringify(this.navIds)).slice(1);
            let tabs = this.getFourthTabs(this.menus, this.pid);
            if (tabs) {
              this.active.pop();
              this.tabs = tabs.fourthTabs;
              this.tabsId = this.navIds[this.navIds.length - 1];
            }
            this.topActive = this.navIds[0];
            this.menu = node.children;
          } else {
            this.menu = this.menus[0].children;
            this.topActive = this.menus[0].id;
          }
          break;
        default:
          this.navs = [];
          this.subsystem = [];
          this.menu = this.menus;
          if (this.navIds && this.navIds.length) {
            this.active = JSON.parse(JSON.stringify(this.navIds));
            let tabs = this.getFourthTabs(this.menus, this.pid);
            if (tabs) {
              this.active.pop();
              this.tabs = tabs.fourthTabs;
              this.tabsId = this.navIds[this.navIds.length - 1];
            }
          }
      }
    },
    //监听改变菜单
    handleListener() {
      util.win.addEventListener(
        'message',
        (e) => {
          var msg = e.data;
          if (msg.key == 'jump_Menu') {
            let res = msg.data1;
            if (typeof res === 'string') {
              res = res.split(',');
            }
            this.setDefault(this.menus, res);
          }
        },
        false
      );
    },
    //开启weosocket
    initWebSocket() {
      this.webSocket = util.socket({
        url: wss,
        take: topic,
        success: (res) => {
          let data = res.data || {};
          const subSystemId = data.subSystemId || '';
          for (let i in data) {
            if (data[i] !== null && data[i] !== undefined) {
              if (i === 'onlineUserNums' && data[i] > 0) {
                this.online = this.subSystemId === subSystemId ? data[i] : 1;
              }
              if (i === 'sysMsgNums' && data[i] !== null) {
                this.notice = data[i];
                if (this.showMsg) {
                  this.$refs.message.getMsg(true);
                }
              }
              if (i === 'menuTipsMap' && data[i] !== null) {
                this.menuTips = data[i];
              }
              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);
          }
        }
      });
    },
    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);
      }
    },
    // handleDialog(obj) {
    //   this.dialog = obj;
    // },
    handleUserModel(name, val) {
      this.$set(this.userModel, name, val);
    },
    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);
      }
    },
    //搜索
    handleOnSearch(res, parent) {
      this.showSearch = false;
      if (parent.name === '菜单') {
        this.jumpMenu(res.appCode);
      }
    },
    /**
     * @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 };
    }
  },
  beforeDestroy() {
    this.timer = null;
    if (this.webSocket) {
      this.webSocket.destroy();
    }
    util.win.removeEventListener('popstate', this.tateHandle);
  }
};
</script>
