<template>
  <div id="main" class="main" :class="{'main-hide-text': hideMenuText}">
    <!-- 左侧导航 -->
    <div class="sidebar-menu-con" :class="[hideMenuText ? 'sidebar-menu-hidden': 'sidebar-menu-display']">
      <div class="sidebar-wrapper">
        <div class="navicon-con">
          <Button style="padding:0;" :style="{color:'#aaa',transform: 'rotateZ(' + (this.hideMenuText ? '-90' : '0') + 'deg)'}" type="text" @click="toggleClick">
            <Icon type="md-menu" size="28"></Icon>
          </Button>
        </div>
        <sidebar-menu :isLight="hideMenuText" :data="menuList" :iconSize="14" />
      </div>
    </div>
    <!-- 头部 -->
    <div class="main-header-con" :style="{paddingLeft: hideMenuText?'0px':'0px'}">
      <!-- 横向导航add：“show-Hnav-main” -->
      <div class="main-header">
        <!-- logo -->
        <div class="logo-con">
          <div class="show-logo">
            <img src="../asset/images/logo.gif">
          </div>
          <span class="logo-txt">EHS管理系统</span>
        </div>
        <div class="header-avator-con">
          <div class="user-dropdown-menu-con">
            <Row justify="end" align="middle" class="user-dropdown-innercon">
              <Avatar :src="avatorPath" style="background: #619fe7;"></Avatar>
              <!--<Dropdown trigger="click" @on-click="handleClickUserDropdown">
                <a href="javascript:void(0)">
                  <span class="main-user-name" style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis;width:60px" :title="user.userName">{{ user.userName }}</span>
                  <Icon type="md-arrow-dropdown"/>
                </a>
                <DropdownMenu slot="list">
                  <DropdownItem name="ownSpace">{{$t('module.main.personalCenter')}}</DropdownItem>
                </DropdownMenu>
              </Dropdown>-->
              <span style="color: #F99C34">{{ user.userName }}</span>
              <Button type="text" icon="md-power" size="large" class="button-logout"
                      @click="handleClickUserDropdown('loginout')"></Button>
            </Row>
          </div>
        </div>
      </div>
    </div>
  
    <!-- tags -->
    <div class="tags-con" :class="[hideMenuText ? 'single-page-menu-hidden': 'single-page-menu-display']">
      <div class="main-tags">
        <Button class="left carousel-arrow" icon="ios-arrow-back" size="small" @click.native="tagsPageSlide(0)"></Button>
        <tags-page-opened ref="tagsPageOpened"></tags-page-opened>
        <Button class="right carousel-arrow" icon="ios-arrow-forward" size="small" @click.native="tagsPageSlide(1)"></Button>
      </div>
    </div>
    <div class="main-div-box"></div>
    <div class="single-page-con" :class="[hideMenuText ? 'single-page-menu-hidden': 'single-page-menu-display']">
      <div class="single-page">
        <!-- <div class="single-wrapper"> -->
        <ActionBar></ActionBar>
        <keep-alive :include="cachePage">
          <transition name="translation">
            <router-view class="single-wrapper" :key="routerViewKey"></router-view>
          </transition>
        </keep-alive>
        <!-- </div> -->
      </div>
    </div>
    <!-- 版权信息 -->
    <div class="copyright">{{$t('module.main.copyright')}}</div>
  </div>
</template>
<style lang="less">
@import "../styles/index.less";
@import "./main.less";
</style>

<script>
import Vue from "vue";
import tagsPageOpened from "../components/tagsPageOpened.vue";
import breadcrumbNav from "../components/breadcrumbNav.vue";
import themeDropdownMenu from "../components/themeDropdownMenu.vue";
import Cookies from "js-cookie";
import util from "../tools/util.js";
import ActionBar from "../components/ActionBar.vue";
import { setLang } from "../langProcess.js";
// import { mapState } from "vuex";
export default {
  components: {
    ActionBar,
    tagsPageOpened,
    breadcrumbNav,
    themeDropdownMenu
  },
  data() {
    return {
      theme1: "dark",
      spanLeft: 4,
      spanRight: 20,
      // currentPageName: "",
      hideMenuText: false,
      userName: "",
      showFullScreenBtn: window.navigator.userAgent.indexOf("MSIE") < 0,
      isFullScreen: false,
      // messageCount: 0,
      lockScreenSize: 0,
      roleList: [],
      languageList: [],
      lang: "",
      roleModel: ""
    };
  },
  computed: {
    logoMain() {
      return this.$App.logoMain;
    },
    logo() {
      return this.$App.logo;
    },
    menuList() {
      return this.$store.state.userMenuTree;
    },
    tagsList() {
      return this.$store.state.tagsList; // 所有页面的页面对象
    },
    cachePage() {
      return this.$store.state.cachePage;
    },
    // ...mapState({
    //   pageTagsList: "pageOpenedList"
    // }),
    // currentPath() {
    //   return this.$store.state.currentPath; // 当前面包屑数组
    // },
    menuIconColor() {
      return this.$store.state.menuTheme === "dark" ? "white" : "#495060";
    },
    avatorPath() {
      return this.$store.state.avatar;
    },
    user() {
      return this.$store.state.userInfo;
    },
    routerViewKey() {
      return this.$route.fullPath;
    }
  },
  methods: {
    setCurrentPageNameByRouter(router) {
      this.$store.commit("setCurrentPageName", util.routerToActionUrl(router));
    },
    langChange() {
      this.$nextTick(() => {
        $store.dispatch("ChangeLang", { language: this.lang }).then(response => {
          // window.location.reload();
          this.onRoleChange(this.roleModel).then(this.proceessBreadcrumb);
        });
      });
    },
    proceessBreadcrumb(route = this.$route) {
      this.setCurrentPageNameByRouter(route);
      util.setCurrentPath(this, route);
      // let pathArr = util.setCurrentPath(this, route);
      // if (pathArr && pathArr.length >= 2) {
      //   this.$store.commit("addOpenSubmenu", pathArr[1].name);
      // }
      // let messageCount = 3;
      // this.messageCount = messageCount.toString();
    },
    toggleClick() {
      this.hideMenuText = !this.hideMenuText;
      $channel.$emit("ToggleSidebarMenu");
    },
    feedback() {
      util.openPage(this, "feedback", this.$t("module.main.feedback"));
    },
    handleClickUserDropdown(name) {
      switch (name) {
        case "ownSpace":
          util.openPage(this, "ownspace_index", this.$t("module.main.personalCenter"));
          break;
        case "loginout":
          this.loginout();
          break;
        case "feedback":
          util.openPage(this, "feedback", this.$t("module.main.feedback"));
          break;
      }
    },
    loginout() {
      this.$Spin.show({
        render: h => {
          return h("div", [
            h("Icon", {
              class: "demo-spin-icon-load",
              props: {
                type: "load-c",
                size: 18
              }
            }),
            h("div", this.$t("module.main.islogout"))
          ]);
        }
      });
      this.$store.dispatch("Logout").then(() => {
        //登出清除组织树
        window.localStorage.businessHeadquarters = '';
        //登出清除用户信息
        window.localStorage.userInfo = "";
        //登出时清除localStorage中语言值
        window.localStorage.language = "";
        this.$Spin.hide();
        this.$store.commit("clearOpenedSubmenu");
        //退出登陆跳单点
        if (!!process.env.API.sso) {
          //window.location.href = `${process.env.API.sso_logout_jump_url}?end_url=${window.location.origin}`;
          window.location.href = `${process.env.API.sso_logout_jump_url}?end_url=${process.env.API.endUrl}`;
          return;
        }

        this.$router.push({
          name: "login",
          query: { path: this.$route.path }
        });
      });
    },
    handleFullScreen() {
      let main = document.getElementById("main");
      if (this.isFullScreen) {
        if (document.exitFullscreen) {
          document.exitFullscreen();
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen();
        } else if (document.webkitCancelFullScreen) {
          document.webkitCancelFullScreen();
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen();
        }
      } else {
        if (main.requestFullscreen) {
          main.requestFullscreen();
        } else if (main.mozRequestFullScreen) {
          main.mozRequestFullScreen();
        } else if (main.webkitRequestFullScreen) {
          main.webkitRequestFullScreen();
        } else if (main.msRequestFullscreen) {
          main.msRequestFullscreen();
        }
      }
    },
    lockScreen() {
      let lockScreenBack = document.getElementById("lock_screen_back");
      lockScreenBack.style.transition = "all 3s";
      lockScreenBack.style.zIndex = 10000;
      lockScreenBack.style.boxShadow = "0 0 0 " + this.lockScreenSize + "px #667aa6 inset";
      this.showUnlock = true;
      this.$store.commit("lock");
      Cookies.set("last_page_name", this.$route.name); // 本地存储锁屏之前打开的页面以便解锁后打开
      setTimeout(() => {
        lockScreenBack.style.transition = "all 0s";
        this.$router.push({
          name: "locking"
        });
      }, 800);
    },
    getUrl(list, data) {
      list.push(data);
      if (!!data.children && data.children.length > 0) {
        for (let c of data.children) {
          this.getUrl(list, c);
        }
      }
    },
    tagsPageSlide(type) {
      this.$refs["tagsPageOpened"].tagsPageSlide(type == 0 ? 120 : -120);
    },
    showUserRoleMenus(data) {
      if (!data) return;
      $store.commit("setUserInfo", data.userInfo);
      $store.commit("setUserMenuTree", data.userMenuList);
      let menus = [];
      let actionUrl = [];
      if (!data.userMenuList) {
        this.$Message.error("菜单数据有异常!");
        return;
      }

      for (let m of data.userMenuList) {
        this.getUrl(menus, m);
      }
      for (let u of menus) {
        if (u.actionUrl != null && u.actionUrl != " ") actionUrl.push(u.actionUrl);
      }
      $store.commit("setScopeUrl", actionUrl.join(","));
      $store.commit("setUserMenu", menus);
      $store.commit("setOpenedList");
      // 用户操作权限
      $store.commit("setOptionRight", data.rightBtnList);
      // 维度操作类型
      $store.commit("setDimensionOperationType", data.dimensionObjectType);
      $store.commit("changeTagsLang", data.userMenuList);
    },
    onRoleChange(roleId) {
      return $store.dispatch("ChangeRole", { roleId: roleId }).then(response => {
        if (response.statusCode == "0") {
          // 展现用户当前角色的功能
          this.showUserRoleMenus(response.dataResult);
          // 关闭当前功能
          // localStorage.removeItem('pageOpenedList');
          // $store.commit("setOpenedList");
          // $store.commit("clearCachePage");
          //全局通知角色切换
          $store.commit("setRoleModule", roleId);
          // this.$router.push({
          //   name: $store.getters.homePage.name
          // });
        }
      });
    },
    closeOpenedPage() {
      // 关闭当前功能
      localStorage.removeItem("pageOpenedList");
      $store.commit("setOpenedList");
      $store.commit("clearCachePage");
      this.$router.push({
        name: $store.getters.homePage.name
      });
    }
  },
  watch: {
    $route(to) {
      this.proceessBreadcrumb(to);
    },
    roleModel(newVal, oldVal) {
      if (!!oldVal) {
        this.closeOpenedPage();
      }
    }
  },
  mounted() {
    this.proceessBreadcrumb();
    // 全屏相关
    document.addEventListener("fullscreenchange", () => {
      this.isFullScreen = !this.isFullScreen;
    });
    document.addEventListener("mozfullscreenchange", () => {
      this.isFullScreen = !this.isFullScreen;
    });
    document.addEventListener("webkitfullscreenchange", () => {
      this.isFullScreen = !this.isFullScreen;
    });

    // IE监听全屏事件的事件名称需要大写
    document.addEventListener("MSFullscreenChange", () => {
      this.isFullScreen = !this.isFullScreen;
    });
    // 锁屏相关
    let lockScreenBack = document.getElementById("lock_screen_back");
    let x = document.body.clientWidth;
    let y = document.body.clientHeight;
    let r = Math.sqrt(x * x + y * y);
    let size = parseInt(r);
    this.lockScreenSize = size;
    window.addEventListener("resize", () => {
      let x = document.body.clientWidth;
      let y = document.body.clientHeight;
      let r = Math.sqrt(x * x + y * y);
      let size = parseInt(r);
      this.lockScreenSize = size;
      lockScreenBack.style.transition = "all 0s";
      lockScreenBack.style.width = lockScreenBack.style.height = size + "px";
    });
    lockScreenBack.style.width = lockScreenBack.style.height = size + "px";
  },
  created() {
    $store.dispatch("GetUserMenus").then(res => {
      if (res) {
        // 展现用户当前角色的功能
        this.showUserRoleMenus(res);
        // 加载用户角色列表
        this.lang = res.userLocale;
        setLang(this.lang);
        for (const key in res.userRoleList) {
          if (res.userRoleList.hasOwnProperty(key)) {
            const value = res.userRoleList[key];
            this.roleList.push({ roleId: key, roleName: value });
          }
        }
        this.roleModel = res.userRoleCurrent;
        $store.commit("setRoleModule", this.roleModel);
      }
    });
    //用户信息
    if (localStorage.userInfo) {
      $store.commit("setUserInfo",JSON.parse(localStorage.userInfo));
    }else {
      $store.dispatch('QueryCurrentUserInfo',{}).then();
    }
    //用户偏好值在登录时设置到主页
    if (window.localStorage.language) {
      this.lang = window.localStorage.language;
    } else {
      this.lang = "zh-CN";
    }

    $store.dispatch("QueryLanguages", "").then(response => {
      //加载语言列表
      for (const i in response) {
        if (response[i].langCode != "zh-TW") {
          //（暂时不支持繁体中文）
          this.languageList.push({
            langDesc: response[i].langDesc,
            langCode: response[i].langCode
          });
        }
      }
    });
    //$store.dispatch("GetAvatar");
    $channel.$on("LoginOutEvent", () => {
      this.$Modal.warning({
        title: '提示',
        content: '当前登录已超时，系统将跳转登录页面',
        onOk: () => {
          this.$store.commit("clearOpenedSubmenu");
          if (!!process.env.API.sso) {
            window.location.href = `${process.env.API.sso_logout_jump_url}?end_url=${process.env.API.endUrl}`;
            return;
          }
          this.$router.push({
            name: "login"
          });
        }
      });
    });
  }
};
</script>
<style scoped>
.main-header {
  height: 48px;
  overflow: visible;
}
.translation-enter-active {
  transition: transform .6s ease;
}
.translation-enter{
  transform: translateX(10px);
  opacity: .3;
}
</style>

