import { post } from "../util/http_util"
// import {constantRoute} from "../router/constant"
import infoRoutes from '../router/info'
import My_Websocket from "../util/websocket_util";

const actions = {
  setUserInfo: ({ commit }, userData) => commit('userInfo', userData), /* 用户信息存储 */
  getNavList: ({ commit, state }) => {
    return new Promise((resolve, reject) => {
      post("api/rest/system/menu/queryMenu", { type: "2", id: state.userInfo.role }).
        then(res => {
          let homeRoute = generateHomeRoute(res);
          commit('navList', [homeRoute]);
          resolve(homeRoute);
        })
        .catch(err => {
          console.log(err);
          if (err instanceof Object && (err.code == 9040 || err.code == 9041 || err.code == 9042)) {
            reject(err);
          } else {
            let homeRoute = generateHomeRoute([]);
            commit('navList', [homeRoute]);
            resolve(homeRoute);
          }
        });
    });
  },
  initWebsocket: ({ commit, state }) => {
    state.ws = new My_Websocket("ws://" + window.location.host + "/api/notify/" + state.userInfo.account, res => {
      commit('wsMessages', res);
      console.log(res);
    });
  },
  send: ({ commit, state }, msg) => {
    msg.fromUser = state.userInfo.account;
    msg.toUser = state.userInfo.account;
    let tmp = JSON.stringify(msg);
    state.ws.send(tmp);
  },
}

//生成home菜单路由
function generateHomeRoute(list) {
  //home菜单路由
  let routeHome = {
    path: '/',
    name: "home",
    component: () => import('../view/home.vue'),
    children: []
  };
  //过滤一级目录
  let menu1 = list.filter(e => e.level == 1);
  for (let i = 0; i < menu1.length; i++) {
    let route1 = ({
      icon: menu1[i].icon,
      path: '/' + menu1[i].url,
      name: menu1[i].name,
      component: loadView(menu1[i].url, menu1[i].url),
      children: [],
      meta: menu1[i],
      description:menu1[i].description
    });

    //过滤二级目录
    let route2 = [];
    list.filter(e => e.parentCode == menu1[i].code).forEach((element, index) => {
      route2.push({
        icon: element.icon,
        path: '/' + element.url,
        name: element.name,
        component: loadView(menu1[i].url, element.url),
        meta: element,
        description:element.description
      });
    });
    if (route2.length) {//一级目录有子菜单，此目录才会加入路由
      //额外添加二级的详情页路由
      let info = getInfoRoutes(route1);
      if (info.length) {
        route2 = route2.concat(info);
      }
      //默认路由redirect
      route1.redirect = route2[0].path;
      route1.children = route2;
      routeHome.children.push(route1);
    }
    routeHome.redirect = routeHome.children[0].path;
  }
  return routeHome;
}

// 路由懒加载
function loadView(module, view) {
  return () => import(`../view/${module}/${view}.vue`);
}

function getInfoRoutes(ele) {
  // return infoRoutes.filter(e => e.meta && e.meta.parent_name == ele.name).map(e => {
  //   e.meta.parentCode = ele.meta.code;
  //   return e;
  // });
  let arr = [];
  infoRoutes.forEach((e) => {
    let obj = {
      name : e.name +'_'+ ele.name,
      component: e.component,
      path :e.path + Math.ceil(Math.random()*10000),
      meta:{
        parentCode:ele.meta.code,
        parent_name: ele.name
      }
    };
    arr.push(obj)
  });
  return arr;
}

export default actions