<template>
  <div style="height: 100%">
    <!-- <div style="width:100%"><img v-show="show==1" :src="topUrl" alt="" style="width:100%;margin:0;padding:0;display:block"></div> -->
    <Layout style="height: 100%" class="main">
      <Sider
        hide-trigger
        collapsible
        :width="171"
        :collapsed-width="64"
        v-model="collapsed"
        class="left-sider"
        :style="{ overflow: 'hidden' }"
      >
        <side-menu
          accordion
          ref="sideMenu"
          :active-name="$route.name"
          :collapsed="collapsed"
          @on-select="turnToPage"
          :menu-list="menuList"
        >
          <!-- 需要放在菜单上面的内容，如Logo，写在side-menu标签内部，如下 -->
          <div class="logo-con">
            <img v-show="!collapsed" :src="maxLogo" key="max-logo" />
            <img v-show="collapsed" :src="minLogo" key="min-logo" />
          </div>
        </side-menu>
      </Sider>
      <Layout>
        <Header class="header-con">
          <header-bar
            :collapsed="collapsed"
            @on-coll-change="handleCollapsedChange"
          >
            <Badge
              :dot="!!this.$root.UNReadMsgNum"
              style="top: 13px; left: 0px"
            >
            </Badge>
            <span
              v-text="this.$t('99200002') + '(' + this.$root.UNReadMsgNum + ')'"
              style="color: #2d8cf0; margin-left: 10px; cursor: pointer"
              @click="go_message"
            ></span>
            <span v-text="user_name" style="color: #2d8cf0"></span>
            <user
              :message-unread-count="unreadCount"
              :user-avatar="userAvatar"
            />
            <language
              v-if="$config.useI18n"
              @on-lang-change="setLocal"
              style="margin-right: 10px"
              :lang="local"
            />
            <!-- <error-store v-if="$config.plugin['error-store'] && $config.plugin['error-store'].showInHeader" :has-read="hasReadErrorPage" :count="errorCount"></error-store> -->
            <fullscreen v-model="isFullscreen" style="margin-right: 10px" />
            <allpage style="margin-right: 10px"></allpage>
            <!-- <blocklist style="margin-right: 100px;"></blocklist> -->
          </header-bar>
        </Header>
        <Content class="main-content-con">
          <Layout class="main-layout-con">
            <div class="tag-nav-wrapper">
              <tags-nav
                :value="$route"
                @input="handleClick"
                :list="tagNavList"
                @on-close="handleCloseTag"
              />
            </div>
            <Content class="content-wrapper">
              <keep-alive :include="cacheList">
                <router-view />
              </keep-alive>
              <ABackTop
                :height="100"
                :bottom="80"
                :right="50"
                container=".content-wrapper"
              ></ABackTop>
            </Content>
          </Layout>
        </Content>
      </Layout>
    </Layout>
  </div>
</template>
<script>
import SideMenu from "./components/side-menu";
import HeaderBar from "./components/header-bar";
import TagsNav from "./components/tags-nav";
import User from "./components/user";
import ABackTop from "./components/a-back-top";
import Allpage from "./components/allpage";
import Fullscreen from "./components/fullscreen";
import Language from "./components/language";
import ErrorStore from "./components/error-store";
import { mapMutations, mapActions, mapGetters } from "vuex";
import { getNewTagList, routeEqual } from "@/libs/util";
import routers from "@/router/routers";
import minLogo from "@/assets/images/logo-min.jpg";
import maxLogo from "@/assets/images/logo.jpg";
import "./main.less";
import { setInterval } from "timers";

export default {
  name: "Main",
  components: {
    SideMenu,
    HeaderBar,
    Language,
    TagsNav,
    Allpage,
    Fullscreen,
    ErrorStore,
    User,
    ABackTop,
  },
  data() {
    return {
      collapsed: false,
      minLogo,
      maxLogo,
      isFullscreen: false,
      websocket: null,
      userName: "",
      message_number: 0,
      timeout: 0,
      topUrl: require("../../assets/images/top.jpg"),
    };
  },
  computed: {
    ...mapGetters(["errorCount"]),
    tagNavList() {
      return this.$store.state.app.tagNavList;
    },
    tagRouter() {
      return this.$store.state.app.tagRouter;
    },
    userAvatar() {
      return this.$store.state.user.avatarImgPath;
    },
    user_name() {
      return this.$store.state.user.userName;
    },
    cacheList() {
      const list = [
        "ParentView",
        ...(this.tagNavList.length
          ? this.tagNavList
              .filter((item) => !(item.meta && item.meta.notCache))
              .map((item) => item.name)
          : []),
      ];
      return list;
    },
    menuList() {
      return this.$store.getters.menuList;
    },
    local() {
      return this.$store.state.app.local;
    },
    hasReadErrorPage() {
      return this.$store.state.app.hasReadErrorPage;
    },
    unreadCount() {
      return this.$store.state.user.unreadCount;
    },
    show() {
      // console.log(this.$store.state.user.showRainbow);
      return this.$store.state.user.showRainbow;
    },
  },
  methods: {
    ...mapMutations([
      "setBreadCrumb",
      "setTagNavList",
      "addTag",
      "setLocal",
      "setHomeRoute",
      "closeTag",
    ]),
    ...mapActions(["handleLogin"]),
    turnToPage(route) {
      let { name, params, query } = {};
      if (typeof route === "string") name = route;
      else {
        name = route.name;
        params = route.params;
        query = route.query;
      }
      if (name.indexOf("isTurnByHref_") > -1) {
        window.open(name.split("_")[1]);
        return;
      }
      this.$router.push({
        name,
        params,
        query,
      });
    },
    handleCollapsedChange(state) {
      this.collapsed = state;
    },
    handleCloseTag(res, type, route) {
      if (type !== "others") {
        if (type === "all") {
          this.turnToPage(this.$config.homeName);
        } else {
          if (routeEqual(this.$route, route)) {
            this.closeTag(route);
          }
        }
      }
      this.setTagNavList(res);
    },
    handleClick(item) {
      this.turnToPage(item);
    },
    inittip(data) {
      if (typeof data !== string) {
        return false;
      }
      var message = data.toString();
      var msg = "";
      if (message.indexOf(",") != -1) {
        var errs = data.split(";");
        errs.forEach((item) => {
          var inf = item.split(",");
          msg +=
            this.$t("1077") + inf[0] + this.$t("1083") + this.$t(inf[1]) + ",";
        });
        msg = msg.slice(0, -1);
        this.prototype.warning({
          title: this.$t("600013"), // 提示
          content: "<p>" + msg + "</p>",
        });
        // return msg
      }
    },
    urlencode(str) {
      str = (str + "").toString();
      return encodeURIComponent(str)
        .replace(/!/g, "%21")
        .replace(/'/g, "%27")
        .replace(/\(/g, "%28")
        .replace(/\)/g, "%29")
        .replace(/\*/g, "%2A")
        .replace(/%20/g, "+");
    },
    info(nodesc) {
      this.$Notice.info({
        title: "Notification title",
        desc: nodesc,
      });
    },
    getmessage_number() {
      this.axios
        .request({
          url: "/qms/CheckMessage/GetMessageCount",
          method: "get",
        })
        .then((res) => {
          if (res.data.ret === 1) {
            // 全局变量
            this.$root.UNReadMsgNum = res.data.data;
            // this.message_number = res.data.data
          }
        });
    },
    go_message() {
      this.$router.push({ name: "message_page" });
    },
  },
  watch: {
    $route(newRoute) {
      const { name, query, params, meta, path } = newRoute;
      this.addTag({
        route: { name, query, params, meta, path },
        type: "push",
      });
      this.setBreadCrumb(newRoute);
      this.setTagNavList(getNewTagList(this.tagNavList, newRoute));
      this.$refs.sideMenu.updateOpenName(newRoute.name);
    },
  },
  mounted() {
    /**
     * @description 初始化设置面包屑导航和标签导航
     */
    this.setTagNavList();
    this.setHomeRoute(routers);
    const { name, params, query, meta, path } = this.$route;
    this.addTag({
      route: { name, params, query, meta, path },
    });
    this.setBreadCrumb(this.$route);
    // 设置初始语言
    this.setLocal(this.$i18n.locale);
    // 如果当前打开页面不在标签栏中，跳到homeName页
    if (!this.tagNavList.find((item) => item.name === this.$route.name)) {
      this.$router.push({
        name: this.$config.homeName,
      });
    }
    // let vm = this;
    // window.onbeforeunload = function() {
    //   // vm.send("closesocket:");
    //   vm.closeWebSocket();
    // };
    if (this.timeout) {
      clearInterval(this.timeout);
    }
  },
  destroyed() {
    window.clearInterval(this.timeout);
  },
};
</script>
