/**
 * Program: Router
 * Author: SDL
 * Description: router setting file
 */
import { createRouter, createWebHistory } from 'vue-router';
import _ from 'lodash';
import axios from 'axios';
import store from '@/vuex/store';
import { fetchMenuAll } from '@/service/menuService';
import SDLUtil from '@/utils/SDLUtil';

import { i18n, loadLanguageAsync } from '@/i18n';
// 일반
import LoginPage from '@/components/view/admin/main/LoginPage.vue';
import MainPage from '@/components/view/admin/main/MainPage.vue';
import MainIndexPage from '@/components/view/admin/main/MainIndexPage.vue';
import EmptyPage from '@/components/view/admin/main/EmptyPage.vue';

export const router = createRouter({
  history: createWebHistory(),
  routes: [
    // login
    {
      name: 'login',
      path: `${SDLUtil.WEB_CONTEXT_PATH}/login`,
      component: LoginPage,
    },
    // logout
    {
      name: 'logout',
      path: `${SDLUtil.WEB_CONTEXT_PATH}/logout`,
      component: () => import(/* webpackChunkName: '[request]' */ '@/components/view/admin/main/LoginOut.vue'),
    },
    // system registration
    {
      name: 'systemUserRegister',
      path: `${SDLUtil.WEB_CONTEXT_PATH}/register`,
      component: () => import(/* webpackChunkName: '[request]' */ '@/components/view/admin/main/RegisterPage.vue'),
    },
    // system subscription clause
    {
      name: 'terms',
      path: `${SDLUtil.WEB_CONTEXT_PATH}/terms-conditions`,
      component: () => import(/* webpackChunkName: '[request]' */ '@/components/view/admin/main/TermsAndConditionsPage.vue'),
    },
    // Password initialization
    {
      name: 'initPassword',
      path: `${SDLUtil.WEB_CONTEXT_PATH}/initPassword`,
      component: () => import(/* webpackChunkName: '[request]' */ '@/components/view/admin/main/InitPassword.vue'),
    },
    // sample test
    {
      path: `${SDLUtil.WEB_CONTEXT_PATH}/sample/tree`,
      component: () => import('@/components/view/sample/Tree.vue'),
    },
    {
      path: `${SDLUtil.WEB_CONTEXT_PATH}/sample/fileuploader`,
      component: () => import('@/components/view/sample/FileUploader.vue'),
    },
    {
      path: `${SDLUtil.WEB_CONTEXT_PATH}/sample/excel`,
      component: () => import('@/components/view/sample/Excel.vue'),
    },
    {
      path: `${SDLUtil.WEB_CONTEXT_PATH}/sample/regexinput`,
      component: () => import('@/components/view/sample/RegexInput.vue'),
    },
    // popup
    {
      name: 'noticePopup',
      path: `${SDLUtil.WEB_CONTEXT_PATH}/noticePopup/:boardId/:postId`,
      component: () => import(/* webpackChunkName: '[request]' */ '@/components/view/admin/board/PostPopup.vue'),
    },
    // popup
    {
      name: 'transPopup',
      path: `${SDLUtil.WEB_CONTEXT_PATH}/transPopup`,
      component: () => import('@/components/view/admin/main/TransPopup.vue'),
    },
    // No page registration in menu management => Unconditional 404 processing of user criteria regardless of component registration
    {
      name: 'emptyPage',
      path: `${SDLUtil.WEB_CONTEXT_PATH}/emptypage`,
      component: EmptyPage,
    },
    {
      name: '404',
      path: `${SDLUtil.WEB_CONTEXT_PATH}/404`,
      component: EmptyPage,
    },
    {
      name: 'error',
      path: `${SDLUtil.WEB_CONTEXT_PATH}/error`,
      component: EmptyPage,
    },
    // Page if not authenticated
    {
      path: `${SDLUtil.WEB_CONTEXT_PATH}/noauth`,
      component: () => import(/* webpackChunkName: 'no_auth' */ '@/components/view/admin/main/NoAuthPage.vue'),
    },
    {
      name: 'main',
      path: `${SDLUtil.WEB_CONTEXT_PATH}/`,
      alias: '/',
      component: MainPage,
      children: [
        {
          path: '',
          name: 'mainIndexPage',
          component: MainIndexPage,
        },
      ], // mock
    },
    // otherwise redirect to home
    {
      path: '/:pathMatch(.*)*',
      name: 'not-found',
      redirect: `${SDLUtil.WEB_CONTEXT_PATH}/404`,
    },
  ],
});

router.beforeEach((to, from, next) => {
  // redirect to login page if not logged in and trying to access a restricted page
  const publicPages = ['/login', '/logout', '/register', '/initPassword', '/error'].map(page => SDLUtil.WEB_CONTEXT_PATH + page);
  const authRequired = !publicPages.includes(to.path);
  const loggedIn = SDLUtil.isLogin();

  if (authRequired && !loggedIn) {
    if (to.fullPath.indexOf(`${SDLUtil.WEB_CONTEXT_PATH}/404`) > -1 || to.fullPath === `${SDLUtil.WEB_CONTEXT_PATH}/`) {
      return next(`${SDLUtil.WEB_CONTEXT_PATH}/login`);
    }
    if (to.fullPath.indexOf(`${SDLUtil.WEB_CONTEXT_PATH}/noauth`) > -1) {
      return next({ path: `${SDLUtil.WEB_CONTEXT_PATH}/login`, query: { redirect: to.redirectedFrom.fullPath } });
    }
    return next({ path: `${SDLUtil.WEB_CONTEXT_PATH}/login`, query: { redirect: to.fullPath } });
  }
  return next();
});

router.beforeEach((to, from, next) => {
  // Import locale information from logged in user information
  let userPreferLang;
  const userInfo = SDLUtil.getLoginedUserInfo();
  if (userInfo && userInfo.language) {
    userPreferLang = userInfo.language;
  }

  const lang = (userPreferLang || window.navigator.language || SDLUtil.DEFAULT_LANG).replace('-', '_');
  loadLanguageAsync(lang).then(() => next());
});

// Add to menu ID, page ID header when changing router
router.beforeEach((to, from, next) => {
  if (to.meta.menuId) {
    axios.defaults.headers.common['menu-id'] = to.meta.menuId;
  } else {
    delete axios.defaults.headers.common['menu-id'];
  }
  if (to.meta.pageId) {
    axios.defaults.headers.common['page-id'] = to.meta.pageId;
  } else {
    delete axios.defaults.headers.common['page-id'];
  }

  return next();
});

// Language Settings When Changing Router
router.beforeEach((to, from, next) => {
  if (store.getters.getLocale !== '') {
    i18n.locale = store.getters.getLocale;
  }
  return next();
});

// Initialize storing the stored parameter setting value when changing the router
router.beforeEach((to, from, next) => {
  if (history.state.restoreList !== true && to.meta.menuId !== from.meta.menuId) {
    store.commit('PARAMS', {});
  }
  // console.info('파라미터값', store.getters.getParams, to.params.restoreList);
  return next();
});

router.afterEach(to => {
  let title = SDLUtil.getMsgProp('sdl.common.projectName');
  if (to.meta.labelJson && to.meta.labelJson[i18n.locale]) {
    title += ` - ${to.meta.labelJson[i18n.locale]}`;
  } else if (to.meta.label) {
    title += ` - ${to.meta.label}`;
  }
  document.title = title;
  if (to.meta.menuId !== undefined) {
    axios.post(`${SDLUtil.API_URL}/history/menuUseHistory/${to.meta.menuId}`).then();
  }
});

export async function addEntryPoint(routeData = []) {
  const entryChildren = routeData
    .filter(menu => menu.pagePath)
    .map(menu => ({
      name: menu.pageId,
      path: menu.pagePath,
      redirect: `${SDLUtil.WEB_CONTEXT_PATH}/noauth`,
      meta: {
        ...menu,
      },
    }));

  // const existComponents = componentList.map(r => r.path);

  // If you are logged in
  if (SDLUtil.isLogin()) {
    // Import common code
    // await SDLUtil.loadAllCommCodeList();
    // await store.dispatch('getMenus');
    const termsUrl = `${SDLUtil.WEB_CONTEXT_PATH}/terms-conditions`;
    const isTermsPage = window.location.pathname === termsUrl;
    const menuResponse = await fetchMenuAll()
      .then(res => res)
      .catch(err => {
        // We need agreement.
        if (err.data.error.code === 201 && !isTermsPage) {
          console.info('change', err);
          window.location.href = termsUrl;
        }
      });

    // skip the terms and conditions page
    if (isTermsPage) {
      return;
    }

    await Promise.all([SDLUtil.loadAllCommCodeList(), store.dispatch('getMenus'), store.dispatch('getMyMenus')]);

    let authPages = [];
    const globComponents = import.meta.glob('../components/view/**/**.vue');
    menuResponse.data.forEach(menu => {
      const pages = menu.pages.map(page => {
        
        const routeItem = {
          name: page.pageId,
          path: page.pagePath,
          component: EmptyPage,
          meta: {
            ...menu,
            ...page,
            tabMenuObj:menu,
            componentName: page.componentName,
          },
        };
        if (page.componentName !== undefined && page.componentName !== '') {
          routeItem.component = globComponents[`../components/view/${page.componentName}.vue`];
        }
        if(page.pagePath.startsWith('/embo/formula/')){
          console.log(routeItem);
        }
        
        return routeItem;
      });

      authPages = authPages.concat(pages);
    });

    authPages.forEach(page => {
      const idx = _.findIndex(entryChildren, ['path', page.path]);
      if (idx > -1) {
        entryChildren[idx] = page;
      }
    });
  }

  [...entryChildren].forEach(child => {
    router.addRoute('main', child);
    // console.log(child.path);
  });
}

router.onError(error => {
  if (/loading chunk \d* failed./i.test(error.message)) {
    window.location.reload();
  }
});

export default router;
