<template>
  <Layout style="height: 100%" class="main">
    <Header class="header-con" v-show="!$customs.flag">
      <div class="logo-con">
        <img :src="logo" />
      </div>
      <Menu mode="horizontal" theme="dark" :active-name="activeName" @on-select="selectMenu">
        <div class="layout-logo"></div>
        <div class="layout-nav">
          <MenuItem :name="item.name" v-for="item in menuList">
                      <!-- <Icon :type="item.icon"></Icon> -->
            {{item.title}}
            <div class="line-border"></div>
          </MenuItem>
        </div>
                      <!-- <div style="float: right;height: auto;padding-right: 20px;line-height: 64px;">
                        <p style="float:left;color:white">{{currentUser}}</p> 
                        <user  style="float:left;margin-left:10px" :message-unread-count="unreadCount" :user-avatar="userAvatar"></user> 
                      </div> -->
      </Menu>
      <div class="head-right">
        <p style="float:left;color:white">{{currentUser}}</p>
        <user
          style="float:left;margin-left:8px"
          :message-unread-count="unreadCount"
        ></user>
                      <!-- :user-avatar="userAvatar" -->
      </div>
    </Header>
    <Layout>
      <Sider
        hide-trigger
        collapsible
        :width="256"
        :collapsed-width="64"
        class="left-sider"
        :style="{overflow: 'hidden'}"
        v-show="leftMenuList.length>0 && !$customs.flag"
      >
        <side-menu
          accordion
          ref="sideMenu"
          @on-select="turnToPage"
          :menu-list="leftMenuList"
          v-if="leftMenuList.length>0"
        ></side-menu>
      </Sider>
      <Content class="main-content-con">
        <div class="main-div">
          <!-- <div class="bread-crumb-div">{{breadTitle}}</div> -->
          <div class="bread-crumb-div" v-if="$route.name!='index'" v-show="!$customs.flag">
            <Breadcrumb separator="<b class='breadcrumb-separator'>></b>">
              <BreadcrumbItem  :to="item.index" v-for="item in nowRouters">
                <Icon :type="item.icon"></Icon>
                {{item.name}}
              </BreadcrumbItem>
            </Breadcrumb>
          </div>
          <router-view />
        </div>
        <div class="right-div" v-if="$route.name=='index'&&false" ></div>
        <!-- <div class="side-div">
              <h2>核心运维系统对接管理</h2>
        </div> -->
      </Content>
    </Layout>
    <div id="tip"></div>
  </Layout>
</template>

<script lang="ts">
import { Component, Vue, Watch } from "vue-property-decorator";
import { State, Mutation, Getter } from "vuex-class";
import avatar from "../../assets/images/avatar.png";
import { getNewTagList, routeEqual, getMenuByRouter } from "../../libs/util";
import routers from "../../routers";
import DeviceInstanceForm from "../dynamic-environment/device-instance-form.vue";

@Component
export default class Main extends Vue {
  userAvatar: any = avatar;
  logo: any = "";
  activeName: string = "";
  currentUser: string = "";
  menuList: Array<any> = [];
  breadTitle: string = "Octopus自动化运维管理";
  orignalOptions: Array<any> = [];
  nowRouters: Array<any> = [];
  tree: Array<any> = [];
  side: Array<any> = [];
  parentMenu: any = {};
  unreadCount: number = 0;
  leftMenuList: Array<any> = [];
  @Mutation("setMenuList") private setMenuList!: any;
  @Mutation("setUserInfo") private setUserInfo!: any;

  isEmpty(obj) {
    return typeof obj === "undefined" || obj === null || obj === "";
  }

  // rescureData(data){
  //   data.forEach(element => {
  //       element.path=element.url;
  //       element.title=element.name;
  //       element.name=this.handleName(element.url);
  //       if(element.children&&element.children.length>0){
  //         this.rescureData(element.children)
  //       }
  //   });
  // }
  assembleMenuList(tree) {
    //顶级菜单
    tree.forEach(element => {
      if (!element.parentId) {
        var menu = { path: "", title: "", name: "", children: {} };
        menu.path = element.url;
        menu.title = element.name;
        menu.name = this.handleName(element.url);
        menu.children = this.rescurData(tree, element);
        this.menuList.push(menu);
      }
    });
  }
  rescurData(tree, curMenu) {
    var curChildren: Array<any> = [];
    tree.forEach(element => {
      if (curMenu.id == element.parentId) {
        var menu = { path: "", title: "", name: "", children: {} };
        menu.path = element.url;
        menu.title = element.name;
        menu.name = this.handleName(element.url);
        menu.children = this.rescurData(tree, element);
        curChildren.push(menu);
      }
    });
    return curChildren;
  }
  getAllTree() {
    this.getApiData(
      "post",
      this.$msPrefix.base + "/api/v1/data/list/menu?size=1000&page=0",
      {},
      res => {
        this.tree = res.data.content;
        this.getCurrentRoute(this.$route);
      },
      err => {}
    );
  }

  getMenuList() {
    this.getApiData(
      "post",
      this.$msPrefix.base + "/api/v1/user/currentUserInfo",
      "",
      res => {
        this.setUserInfo(res.data.user);
        this.currentUser = res.data.user.name;
        let tree = res.data.menuTree.sort(this.sortByOrder);
        this.assembleMenuList(tree);
        console.log("***", this.menuList);
        // this.rescureData(tree);
        // this.menuList=tree;
        this.updateLeftMenu(true);
        console.error(111111, this.menuList);
        this.setMenuList(this.menuList);
      },
      err => {}
    );
  }

  sortByOrder(a, b) {
    if (a.sort == "" || a.sort == null) {
      return b;
    } else if (b.sort == "" || b.sort == null) {
      return a;
    } else {
      return a.sort - b.sort;
    }
  }

  handleName(obj) {
    if (!this.isEmpty(obj)) {
      var names: Array<any> = [];
      names = obj.split("/");
      return names[names.length - 1];
    } else {
      return obj;
    }
  }

  turnToPage(route: object) {
    let { name, params, query } = { name: "", params: {}, query: "" };
    if (typeof route === "string") name = route;
    else {
      name = (route as any).name;
      params = (route as any).params;
      query = (route as any).query;
    }
    if (name.indexOf("isTurnByHref_") > -1) {
      window.open(name.split("_")[1]);
      return;
    }
    (this.$router as any).push({ name, params, query });
  }

  // @Watch("$route")
  // routeChange(newRoute) {
  //   (this.$refs.sideMenu as any).updateOpenName(newRoute.name);
  // }

  created() {
    let versions:any = this.$versions;
    this.logo=require("../../assets/images/"+versions[versions["name"]].logo);
  }
  getCurrentRoute(route) {
    this.nowRouters = [];
    //首页跳转例外
    var item = { index: "", name: "", icon: "" };
    if (route.path == "/cmdb/index") {
      item.index = "/cmdb/index";
      item.name = "首页";
      item.icon = "ios-home-outline";
      this.nowRouters.push(item);
    } else {
      this.getSideMenuBread(route);
      this.getParentMenuBread(this.side[0]);
      item.name = this.parentMenu.name;
      // item.index = this.parentMenu.url;
      item.index = route.fullPath;
      // item.icon = this.parentMenu.icon;
      item.icon = "ios-home-outline";
      this.parentMenu = {};
      this.nowRouters.unshift(item);
    }
  }

  //获取左侧菜单面包屑
  getSideMenuBread(route) {
    console.log("oooo", route);
    this.side = [];
    //index累计拼起来
    var index = route.fullPath;
    route.matched.forEach(element => {
      // index += '/'+element.name;
      var childItem = { index: "", name: "", icon: "" };
      this.tree.forEach(option => {
        var condition = "/" + element.name;
        if (option.url == condition) {
          childItem.index = index;
          childItem.name = option.name;
          // childItem.icon = option.icon;
          this.side.push(option);
        }
      });
      this.nowRouters.push(childItem);
    });
  }

  //递归获取顶级菜单面包屑
  getParentMenuBread(menu) {
    if (menu.parentId) {
      this.tree.forEach(element => {
        if (element.id == menu.parentId) {
          console.log("res", element);
          this.getParentMenuBread(element);
        }
      });
    } else {
      this.parentMenu = menu;
    }
  }

  getActiveName() {
    let name = this.$route.name;
    let path = this.$route.path;
    try {
      let activeRoute = null;
      let activeItem = this.menuList.find(item => item.name == name);
      if (activeItem && activeItem) {
        this.activeName = activeItem.name;
      } else {
        this.menuList.forEach(item => {
          item.children.forEach(menu => {
            if (menu.children && menu.children.length > 0) {
              menu.children.forEach(child => {
                if (child.name == name && menu.path + child.path == path) {
                  this.activeName = item.name;
                  console.info(item, name);
                  (this.$refs.sideMenu as any).updateOpenName(name);
                  throw new Error("End");
                }
              });
            }
          });
        });
      }
    } catch (e) {
      console.log(e);
    }
  }
  mounted() {
    let theme = localStorage.getItem("theme");
    if (theme && theme) {
      document.body.className = theme;
    }
    this.getAllTree();
    this.getMenuList();
    (this.$Message as any).config({
      top: 50,
      duration: 5
    });
  }
  selectMenu(name) {
    console.error("ddddd", name);
    this.activeName = name;
    (this.$router as any).push({ name: name });
    this.leftMenuList = [];
    this.updateLeftMenu(false);
  }
  @Watch("$route")
  routeChange(newRoute) {
    this.getCurrentRoute(newRoute);
    //this.getActiveName()
    this.updateLeftMenu(true);
  }
  // get leftMenuList(){
  //   let menu=this.menuList.find(item=>item.name==this.activeName);
  //   return menu?menu.children:[];
  // }

  updateLeftMenu(needGetActiveName = false) {
    this.$nextTick(() => {
      if (needGetActiveName) {
        this.getActiveName();
      }
      let menu = this.menuList.find(item => item.name == this.activeName);
      this.leftMenuList = menu ? menu.children : [];
    });
  }
}
</script>
