import { RouteRecordRaw } from 'vue-router';
import { defineStore } from 'pinia';
import { constantRoutes } from '@/router';
import { store } from '@/store';
import { listRoutes, getMenuTreeByType } from '@/api/menu';
import { ref } from 'vue';
const modules = import.meta.glob('../../views/**/**.vue');
export const Layout = () => import('@/layout/index.vue');
import { useUserStore} from '@/store/modules/user';

// const hasPermission = (roles: string[], route: RouteRecordRaw) => {
//   if (route.meta && route.meta.roles) {
//     if (roles.includes('ROOT')) {
//       return true;
//     }
//     return roles.some(role => {
//       if (route.meta?.roles !== undefined) {
//         return (route.meta.roles as string[]).includes(role);
//       }
//     });
//   }
//   return false;
// };

const filterAsyncRoutes = (routes: RouteRecordRaw[], roles: string[]) => {
  const res: RouteRecordRaw[] = [];
  routes.forEach(route => {
    const tmp = { ...route } as any;
    // if (hasPermission(roles, tmp)) {
    tmp.path = tmp.opturl;
    if (tmp.type == '0') {
      tmp.component = Layout;
      if (tmp.parentid == '0') {
        tmp.component = Layout;
      }

    } else {
      const component = modules[`../../views${tmp.opturl}.vue`] as any;
      if (component) {
        tmp.component = component;
      } else {
        tmp.component = modules[`../../views/error-page/404.vue`];
      }
    }
    res.push(tmp)
    if (tmp.children) {
      tmp.children = filterAsyncRoutes(tmp.children, roles);
    }
    // }
  });
  return res;
};
const tempRoutes: any = ref([])
const filterNewAsyncRoutes = (routes: RouteRecordRaw[], roles: string[]) => {
  const res: any = [];
  routes.forEach(route => {
    const tmp = { ...route } as any;
    // if (hasPermission(roles, tmp)) {
    tmp.path = tmp.opturl;
    if (tmp.type == '0') {
      // tmp.component = () => import('@/src/views/monitorsystem/index.vue');
    } else {
      const component = modules[`../../views/monitorsystem${tmp.opturl}/index.vue`] as any;
      if (component) {
        tmp.component = component;
      } else {
        tmp.component = modules[`../../views/error-page/404.vue`];
      }
    }
    res.push(tmp)
    if (tmp.children) {
      tmp.children = filterNewAsyncRoutes(tmp.children, roles);
    }
    // }
  });
  if (res != undefined && res[0] != undefined && res[0].opturl != "") {
    tempRoutes.value = tempRoutes.value.concat(res)
  }

  // constantRoutes[3].children = constantRoutes[3].children.concat(res)
  return res;
};
// setup
export const usePermissionStore = defineStore('permission', () => {
  // state
  const routes = ref<RouteRecordRaw[]>([]);
  const addRoutes = ref<RouteRecordRaw[]>([]);

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

  }

  function generateRoutes(roles: string[]) {
    return new Promise<RouteRecordRaw[]>((resolve, reject) => {
      listRoutes()
        .then(response => {
          const asyncRoutes: any = response;
          const userStore:any = useUserStore();
          userStore.menuArr = response;
          const accessedRoutes = filterAsyncRoutes(asyncRoutes, roles);
          setRoutes(accessedRoutes);
          resolve(accessedRoutes);
        })
        .catch(error => {
          reject(error);
        });
    });
  }
  function generatesRoutes(roles: string[]) {
    return new Promise<RouteRecordRaw[]>((resolve, reject) => {
      const params = {
        sysetmCode: '2'
      }
      getMenuTreeByType(params).then(response => {
        const asyncRoutes: any = response;
        const accessedRoutes = filterNewAsyncRoutes(asyncRoutes, roles);
        // setRoutes(tempRoutes.value);

        const accessedRoutesss = [{
          path: '/monitorsystem',
          component: () => import('/src/views/monitorsystem/index.vue'),
          redirect: '/stationboard',
          meta: { hidden: true },
          children: [
            {
              path: '/stationboard',
              component: () => import('/src/views/monitorsystem/stationboard/index.vue'),
              name: '大屏首页',
              meta: { hidden: true },
            }
          ]
        }]
        accessedRoutesss[0].children = accessedRoutesss[0].children.concat(tempRoutes.value)
        // debugger
        resolve(accessedRoutesss);

      })
        .catch(error => {
          reject(error);
        });
    });
  }
  return { routes, setRoutes, generateRoutes, generatesRoutes };
});

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