import { RouteRecordRaw } from "vue-router";
import { defineStore } from "pinia";
import { getSubSystemRouter,generateDynamicRouter } from "@/framework/router/dynamicRouter";

import  pinia from "@/framework/store";
import { listRoutes,getBusinessDomain } from "@/framework/api/acas";
import { Menu } from "@element-plus/icons-vue";
import { useSettingsStore } from "@/framework/store/modules/settings";
import { setCurrentBusinessDomain,getCurrentBusinessDomain } from "@/framework/store/modules/user";

interface Menu {
  id: string;
  name: string;
  url: string;
  modules: Menu[];
}

/**
 * 匹配一级菜单路由
 * @param menu 一级菜单
 * @param menuRouter 一级菜单路由
 * @returns 
 */
const matchMenu = (menu:Menu,menuRouter: RouteRecordRaw[]) => {
  const url = menu.url
  let temp = null
  for (const route of menuRouter) {
    if (url === route.path) {
      temp = route
      temp.meta.title = menu.name
      break
    }
  }
  return temp
}

/**
 * 匹配二级菜单路由
 * @param module 二级菜单
 * @param moduleRouter 二级菜单路由
 * @returns 
 */
const matchModule = (module:Menu,moduleRouter: RouteRecordRaw[]) => {
  let temp=null;
  for (const children of moduleRouter) {
    if (module.url === children.path) {
      children.meta.id = module.id
      children.meta.title = module.name
      temp=children;
      break
    }
  }
  return temp;
}

/**
 * 创建一级菜单路由
 * @param params 
 */
const createMenuRouter = (menu:Menu) => {
  if(undefined===menu.modules||menu.modules.length==0)
    return null
  let menuRouter= {
    path: '/'+menu.id,
    name: menu.id,
    // redirect: '/document/dataDictionary',
    meta: {title: menu.name},
  }
  let children=[]
  menu.modules.forEach(m => {
    let externalOldERP=false
    if('html'===m.url.substring(m.url.length-4,m.url.length))
      externalOldERP=true
    children.push({
      path: m.id,
      name: m.id,
      meta: {
        title: m.name,
        external: true, //是否引入外部应用，默认false
        externalOldERP: externalOldERP, //外部应用是否是老ERP页面，默认false
        externalOldERPIndex: publicData.externalOldERPIndex, //老ERP页面主页面，用于提前加载框架js、css等等
        externalUrl: m.url, //外部应用地址，如果是老ERP页面，地址会是：externalOldERPIndex+externalUrl
      }
    })
  });
  menuRouter.children=children
  menuRouter.redirect=menuRouter.path+'/'+menuRouter.children[0].path
  return generateDynamicRouter(menuRouter)
}


/**
 * 递归过滤有权限的异步(动态)路由
 *
 * @param routes 接口返回的异步(动态)路由
 * @param roles 用户角色集合
 * @returns 返回用户有权限的异步(动态)路由
 */
const filterAsyncRoutes = (menus: Menu[], dynamicRouter: RouteRecordRaw[]) => {
  const asyncRoutes: RouteRecordRaw[] = [];
  menus.forEach(item => {
    let cmenu = matchMenu(item,dynamicRouter)
    if (cmenu) {
      const children = []
      for (const module of item.modules) {
        let cmodule=matchModule(module,cmenu.children)
        if(cmodule){
          children.push(cmodule)
        }
      }
      cmenu.children = children
      if (cmenu.children.length>0) {
        cmenu.redirect = cmenu.path+'/'+children[0].path
        asyncRoutes.push(cmenu)
      }
    }else{
      let newmenu=createMenuRouter(item)
      if(null!=newmenu)
        asyncRoutes.push(newmenu)
    }
  })
  const route = dynamicRouter.filter(val => val.path==='/')[0]
  route.redirect = asyncRoutes[0] ? asyncRoutes[0].redirect : '/404'
  asyncRoutes.unshift(route);
  return asyncRoutes;
};

// setup
export const usePermissionStore = defineStore("permission", () => {
  // state
  const routes = ref<RouteRecordRaw[]>([]);

  // actions
  function setRoutes(newRoutes: RouteRecordRaw[]) {
    routes.value = getSubSystemRouter().concat(newRoutes);
  }

  /**
   * 获取并设置当前业务域
   * @returns
   */
  function setAndGetBusinessDomain() {
    return new Promise((resolve, reject) => {
      getBusinessDomain().then((data: any) => {
        if(data.length>0){
          let cbd=getCurrentBusinessDomain();
            for (const bd of data) {
                if(bd.defstatus&&1===bd.defstatus&&!cbd.id)
                    setCurrentBusinessDomain(bd)
            }
        }
        resolve(data);
      }).catch((error) => {
        reject(error);
      });
    });
  }
  
  /**
   * 生成动态路由
   *
   * @param roles 用户角色集合
   * @returns
   */
  function generateRoutes(dynamicRouter: RouteRecordRaw[]) {
    return new Promise<RouteRecordRaw[]>((resolve, reject) => {
      //使用外部本地菜单配置
      if(publicData.extLocalRouter&&publicData.extLocalRouter.length>0){
        const accessedRoutes = filterAsyncRoutes(publicData.extLocalRouter, dynamicRouter);
        setRoutes(accessedRoutes);
        resolve(accessedRoutes);
      }else{ //接口获取授权路由
        let params={subsystem:publicData.currentSubsystem}
        const settingsStore = useSettingsStore(pinia);
        if(settingsStore.backendServices[publicData.currentSubsystem])
          params.subsystem=settingsStore.backendServices[publicData.currentSubsystem]
        listRoutes(params).then(data => {
          const menus  = data.filter((item: Menu) => item.modules.length>0)
          // 根据角色获取有访问权限的路由
          const accessedRoutes = filterAsyncRoutes(menus, dynamicRouter);
          setRoutes(accessedRoutes);
          resolve(accessedRoutes);
        }).catch((error) => {
          reject(error);
        });
      }
    });
  }
  routes.value = getSubSystemRouter()
  return { routes, setRoutes, generateRoutes,setAndGetBusinessDomain };
});

// 非setup
export function usePermissionStoreHook() {
  return usePermissionStore(pinia);
}
