import { getCurrentPermissionList } from "@/api/index";
import lazyLoading from "./lazyLoading.js";

import Cookies from "js-cookie";
let util = {};

util.title = function(title) {
  title = title || "管理后台";
  window.document.title = title;
};
// 判断元素是否存在于数组中
util.oneOf = function(ele, targetArr) {
  if (targetArr.indexOf(ele) >= 0) {
    return true;
  } else {
    return false;
  }
};

// 打开新的页面
util.openNewPage = function(vm, name, argu, query) {
  if (!vm.$store) {
    return;
  }
  let pageOpenedList = vm.$store.state.app.pageOpenedList;
  let openedPageLen = pageOpenedList.length;
  let i = 0;
  let tagHasOpened = false;
  while (i < openedPageLen) {
    if (name == pageOpenedList[i].name) {
      // 页面已经打开
      vm.$store.commit("pageOpenedList", {
        index: i,
        argu: argu,
        query: query
      });
      tagHasOpened = true;
      break;
    }
    i++;
  }
  if (!tagHasOpened) {
    let tag = vm.$store.state.app.tagsList.filter(item => {
      return name == item.name;
    });
    tag = tag[0];
    if (tag) {
      if (argu) {
        tag.argu = argu;
      }
      if (query) {
        tag.query = query;
      }
      vm.$store.commit("increateTag", tag);
    }
  }
};

util.toDefaultPage = function(routers, name, route, next) {
  let len = routers.length;
  let i = 0;
  let notHandle = true;
  while (i < len) {
    if (
      routers[i].name == name &&
      routers[i].children &&
      routers[i].redirect == undefined
    ) {
      route.replace({
        name: routers[i].children[0].name
      });
      notHandle = false;
      next();
      break;
    }
    i++;
  }
  if (notHandle) {
    next();
  }
};

util.initRouter = function(vm) {
  // 初始化路由
  const constRoutes = [];
  const otherRoutes = [];

  // 404路由需要和动态路由一起加载
  const otherRouter = [
    {
      path: "/*",
      name: "error-404",
      meta: {
        title: "404-页面不存在"
      },
      frontRoute: "error-page/404"
    }
  ];
  // 判断用户是否登录
  let userInfo = Cookies.get("userInfoManager");
  if (!userInfo) {
    // 未登录
    return;
  }
  if (!vm.$store.state.app.added) {
    // 第一次加载 读取数据
    // 加载菜单
    let menuData = [
      {
          "id": "1681489990591033345",
          "createBy": "admin",
          "createTime": "2023-07-19 10:23:49",
          "updateBy": "admin",
          "updateTime": "2023-07-19 16:07:55",
          "deleteFlag": false,
          "title": "人员管理",
          "name": "user",
          "path": "/",
          "level": 0,
          "frontRoute": "Main",
          "parentId": "0",
          "sortOrder": 6,
          "permission": "null",
          "icon": "icon-renyuanguanli-normal",
          children: [
              {
                  "id": "1681491736155500545",
                  "createBy": "admin",
                  "createTime": "2023-07-19 10:30:45",
                  "updateBy": null,
                  "updateTime": null,
                  "deleteFlag": false,
                  "title": "用户管理",
                  "name": "user-manage",
                  "path": "user-manage",
                  "level": 1,
                  "frontRoute": "sys/user-manage/userManage",
                  "parentId": "1681489990591033345",
                  "sortOrder": 0,
                  "permission": "",
                  "icon": "icon-yonghuguanli-normal",
                  "children": []
              },
              {
                  "id": "1681491850097963010",
                  "createBy": "admin",
                  "createTime": "2023-07-19 10:31:12",
                  "updateBy": null,
                  "updateTime": null,
                  "deleteFlag": false,
                  "title": "角色权限",
                  "name": "role-manage",
                  "path": "role-manage",
                  "level": 1,
                  "frontRoute": "sys/role-manage/roleManage",
                  "parentId": "1681489990591033345",
                  "sortOrder": 1,
                  "permission": "",
                  "icon": "icon-juesequanxian-normal",
                  "children": []
              },
              {
                  "id": "1681491942414594049",
                  "createBy": "admin",
                  "createTime": "2023-07-19 10:31:34",
                  "updateBy": null,
                  "updateTime": null,
                  "deleteFlag": false,
                  "title": "部门管理",
                  "name": "department-manage",
                  "path": "department-manage",
                  "level": 1,
                  "frontRoute": "sys/department-manage/departmentManage",
                  "parentId": "1681489990591033345",
                  "sortOrder": 2,
                  "permission": "",
                  "icon": "icon-bumenguanli-normal",
                  "children": []
              }
          ]
      },
      {
          "id": "1681490485414047745",
          "createBy": "admin",
          "createTime": "2023-07-19 10:25:47",
          "updateBy": "admin",
          "updateTime": "2023-07-19 16:07:01",
          "deleteFlag": false,
          "title": "基础设置",
          "name": "base",
          "path": "/",
          "level": 0,
          "frontRoute": "Main",
          "parentId": "0",
          "sortOrder": 9,
          "permission": "null",
          "icon": "icon-jichushezhi-normal",
          children: [
              {
                  "id": "1681495881449058306",
                  "createBy": "admin",
                  "createTime": "2023-07-19 10:47:13",
                  "updateBy": null,
                  "updateTime": null,
                  "deleteFlag": false,
                  "title": "菜单管理",
                  "name": "menuManage",
                  "path": "menu-manage",
                  "level": 1,
                  "frontRoute": "sys/menu-manage/menuManage",
                  "parentId": "1681490485414047745",
                  "sortOrder": 1,
                  "permission": "",
                  "icon": "icon-caidanguanli-normal",
                  "children": []
              },
              {
                  "id": "1681496280251871234",
                  "createBy": "admin",
                  "createTime": "2023-07-19 10:48:49",
                  "updateBy": "admin",
                  "updateTime": "2023-07-20 11:23:41",
                  "deleteFlag": false,
                  "title": "平台登录验证码",
                  "name": "slider",
                  "path": "slider",
                  "level": 1,
                  "frontRoute": "sys/slider/slider",
                  "parentId": "1681490485414047745",
                  "sortOrder": 7,
                  "permission": "/manager/verificationSource*",
                  "icon": "icon-yanzhengma-normal",
                  "children": []
              }
          ]
      }
    ]
    for (let i = 0; i < menuData.length; i++) {
      let t = menuData[i].children; //一级路由
      menuData[i].frontRoute = 'Main'
      menuData[i].path = '/'
      let arr = []
      for (let k = 0; k < t.length; k++) { // 二级路由
        let tt = t[k].children;
        if(tt.length === 0) {
          arr.push(t[k])
        }
      }
      menuData[i].children = arr
    }
    if (!menuData) {
      return;
    }
    util.initAllMenuData(constRoutes, menuData);
    util.initRouterNode(otherRoutes, otherRouter);
    // 添加所有主界面路由
    vm.$store.commit(
      "updateAppRouter",
      constRoutes
    );
    // 添加全局路由
    vm.$store.commit("updateDefaultRouter", otherRoutes);
    // 添加菜单路由
    util.initMenuData(vm, menuData);
    // 缓存数据 修改加载标识
    window.localStorage.setItem("menuData", JSON.stringify(menuData));
    vm.$store.commit("setAdded", true);
  } else {
    // 读取缓存数据
    let data = window.localStorage.getItem("menuData");
    if (!data) {
      vm.$store.commit("setAdded", false);
      return;
    }
    let menuData = JSON.parse(data);
    // 添加菜单路由
    util.initMenuData(vm, menuData);
  }
};

// 添加所有顶部导航栏下的菜单路由
util.initAllMenuData = function(constRoutes, data) {
  util.initRouterNode(constRoutes, data);
};

// 生成菜单格式数据
util.initMenuData = function(vm, data) {
  const menuRoutes = [];
  let menuData = data;
  // 顶部菜单
  let navList = [];
  menuData.forEach(e => {
    let nav = {
      id: e.id,
      name: e.name,
      title: e.title,
      icon: e.icon
    };
    navList.push(nav);
  });
  if (navList.length < 1) {
    return;
  }
  // 存入vuex
  vm.$store.commit("setNavList", navList);
  util.initRouterNode(menuRoutes, menuData);
  // 刷新界面菜单
  vm.$store.commit(
    "updateMenulist",
    menuRoutes
  );

  let tagsList = [];
  vm.$store.state.app.routers.map(item => {
    if (item.children.length <= 1) {
    } else {
      tagsList.push(...item.children);
    }
  });
  vm.$store.commit("setTagsList", tagsList);
};

// 生成路由节点
util.initRouterNode = function(routers, data) {
  // data为所有子菜单数据

  for (let item of data) {
    let menu = Object.assign({}, item);

    menu.component = lazyLoading(menu.frontRoute);

    if (item.children && item.children.length > 0) {
      menu.children = [];
      util.initRouterNode(menu.children, item.children);
    }

    let meta = {};
    // 给页面添加标题、父级菜单name（方便左侧菜单选中）
    meta.title = menu.title ? menu.title + " - 运营后台" : null;
    meta.firstRouterName = item.firstRouterName;
    menu.meta = meta;
    routers.push(menu);
  }
};

export default util;
