import Vue from 'vue';
import Router from 'vue-router';
import store from './store';
import tokenSvc from '@/common/token-service';

import HubwebLayout from './views/HubwebLayout.vue';

import loginRoutes from './modules/login/router';
import custRoutes from './modules/custMgt/router';
import authRoutes from './modules/sysMgt/router';

import subsList from './modules/custMgt/views/SubsList';
import channelRoutes from './modules/attractMgt/router';
import rejectRoutes from './modules/servMgt/router';
import clacRoutes from './modules/calculate/router';
import templtRoutes from './modules/channelMgt/router';
import profileRoutes from './modules/sendNumMgt/router';
import mntrngRoutes from './modules/mntrng/router';
import riskmgtRoutes from './modules/riskMgt/router';
import monthRoutes from './modules/stats/router';
import homeMgtRoutes from './modules/homeMgt/router';

Vue.use(Router);

const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/',
      component: HubwebLayout,
      children: [
        {
          path: '',
          component: subsList,
        },
        {
          path: '/view/error/404',
          component: () => import('./views/ErrorPage404.vue'),
          meta: { public: false },
        },
        {
          path: '/view/error/500',
          component: () => import('./views/ErrorPage500.vue'),
          meta: { public: true },
        },
        ...loginRoutes,
        ...custRoutes,
        ...authRoutes,
        ...channelRoutes,
        ...rejectRoutes,
        ...clacRoutes,
        ...templtRoutes,
        ...profileRoutes,
        ...mntrngRoutes,
        ...riskmgtRoutes,
        ...monthRoutes,
        ...homeMgtRoutes,
        //{path: '*', name: 'error404'}
      ],
    },
    { path: '*', redirect: '/view/error/404' },
  ],
});

router.beforeEach((to, from, next) => {
  const isPublic = to.matched.some((record) => record.meta.public);
  const loggedIn = !!tokenSvc.getToken();
  if (!isPublic && !loggedIn) {
    return next('/login');
  } else {
    var nextUrl = to.fullPath;
    var fromUrl = from.fullPath;

    var menuUrls = store.getters['login/getMenuUrls'];
    if (menuUrls.length > 0) {
      var moveFlag = false;
      for (var i = 0; i < menuUrls.length; i++) {
        var targetUrl = menuUrls[i];
        if (nextUrl == targetUrl) {
          moveFlag = true;
          if (fromUrl != '/' && fromUrl != '/view/error/404' && fromUrl != '/view/error/500') {
            if (nextUrl == '/view/error/404' || nextUrl == '/view/error/500') {
              store.commit('login/isErrorPage', true);
            } else {
              store.commit('login/isErrorPage', false);
              if (
                nextUrl != '/login' &&
                nextUrl != '/view/login/auth' &&
                nextUrl != '/view/login/resetPassword' &&
                nextUrl != '/view/login/updatePassword'
              ) {
                store.commit('login/isLogin', true);
                store.commit('login/isAuthChk', true);
              }
              store.commit('login/saveBeforeUrl', nextUrl);
            }
          } else if (fromUrl == '/' && loggedIn) {
            store.commit('login/isErrorPage', false);
          }
        }
      }

      if (
        nextUrl == '/custMgt/memberList' ||
        nextUrl == '/custMgt/memberDetail' ||
        nextUrl == '/custMgt/subsDetail' ||
        nextUrl == '/custMgt/memberAdminDetail'
      ) {
        for (var i = 0; i < menuUrls.length; i++) {
          if (menuUrls[i] == '/custMgt/subsList') {
            moveFlag = true;
          }
        }

        // 청약 관리 상세
        if (nextUrl == '/custMgt/subsDetail') {
          var serviceId = store.getters['dataStore/getDataStore'];
          console.log('serviceId : ' + serviceId);
          if (to.params.serviceId == undefined) {
            if (serviceId == '') {
              return next('/custMgt/subsList');
            } else {
              to.params.serviceId = serviceId;
            }
          }
        }

        // 회원관리 사용자/어드민 상세
        if (nextUrl == '/custMgt/memberDetail' || nextUrl == '/custMgt/memberAdminDetail') {
          var serviceId = store.getters['dataStore/getDataStore'];
          if (to.params.serviceId == undefined) {
            if (serviceId == '') {
              return next('/custMgt/memberList');
            } else {
              to.params.serviceId = serviceId;
            }
          }
        }
      }

      // url Check 유치채널
      if (nextUrl == '/attractMgt/channelDetail') {
        for (var i = 0; i < menuUrls.length; i++) {
          if (menuUrls[i] == '/attractMgt/channelList') {
            moveFlag = true;
          }
        }
        var userSeq = store.getters['dataStore/getUserSeq'];
        if (to.params.userSeq == undefined) {
          if (userSeq == '') {
            return next('/attractMgt/channelList');
          } else {
            to.params.userSeq = userSeq;
          }
        }
      }
      // url Check 날짜별 통계
      if (nextUrl == '/stats/dayList') {
        for (var i = 0; i < menuUrls.length; i++) {
          if (menuUrls[i] == '/stats/monthList') {
            moveFlag = true;
          }
        }
      }
      // url Check 사업자별 통계
      if (nextUrl == '/stats/bsnmDayList') {
        for (var i = 0; i < menuUrls.length; i++) {
          if (menuUrls[i] == '/stats/bsnmMonthList') {
            moveFlag = true;
          }
        }
      }
      // url Check 권한 관리
      if (
        nextUrl == '/sysMgt/authAdd' ||
        nextUrl == '/sysMgt/authModify' ||
        nextUrl == '/sysMgt/authModify' ||
        nextUrl.indexOf('/sysMgt/batchDetail') > -1
      ) {
        for (var i = 0; i < menuUrls.length; i++) {
          if (menuUrls[i] == '/sysMgt/authList') {
            moveFlag = true;
          }
        }
      }

      if (!moveFlag) {
        if (
          fromUrl == '/login' ||
          fromUrl == '/view/login/auth' ||
          fromUrl == '/view/login/resetPassword' ||
          fromUrl == '/view/login/updatePassword'
        ) {
          return next('/login');
        }
        // store.commit("login/isErrorPage", true);
        return next('/view/error/404');
      }

      if (
        nextUrl == '/view/login/auth' ||
        nextUrl == '/view/login/resetPassword' ||
        nextUrl == '/view/login/updatePassword'
      ) {
        if (fromUrl != '/login') {
          return next('/login');
        }
      }

      if (nextUrl === '/') {
        const rootUrl = store.getters['login/getRootUrl'];
        if (rootUrl == null) {
          return next('/login');
        }
        return next(rootUrl);
      }

      if (nextUrl == '/login' && loggedIn) {
        const rootUrl = store.getters['login/getRootUrl'];
        if (rootUrl == null) {
          return next('/login');
        }
        return next(rootUrl);
      }
    }
  }

  to.matched.some((record) => {
    if (record.meta.usingSearchCondition) {
      const shareList = record.meta.shareList;
      if (from.name && shareList && shareList.includes(from.name)) {
        // shareList에 포함되어 있는 라우터에서 온 경우 검색 조건을 유지한다.
      } else {
        // 그 외의 경우 검색 조건 초기화
        store.commit('searchcondition/updateSearchCondition', null);
      }
    }
    next();
  });
});

export default router;
