import type { Router, RouteRecordRaw } from 'vue-router';

import { usePermissionStoreWithOut } from '@/store/modules/permission';

import { PageEnum } from '@/enums/pageEnum';
import { useUserStoreWithOut } from '@/store/modules/user';

import { PAGE_NOT_FOUND_ROUTE } from '@/router/routes/basic';

import { RootRoute } from '@/router/routes';
import { getsdt } from '@/api/sys/user';
import axios from 'axios';
import { getAppEnvConfig } from '@/utils/env';

const LOGIN_PATH = PageEnum.BASE_LOGIN;

const ROOT_PATH = RootRoute.path;

const whitePathList: PageEnum[] = [LOGIN_PATH];
const { VITE_GLOB_SHANDONG_URL } = getAppEnvConfig();

async function getPhone() {
  let phone;

  // 获取access_token
  // 根据access_token和code获取用户userid
  // 根据access_token和userid获取用户phone
  axios
    .get(
      VITE_GLOB_SHANDONG_URL +
        '/cgi-bin/gettoken?corpid=wwafa1a3005a15a672&corpsecret=ZZGcQsuKYNBb7fOcIzniq6DiKWZDFaAcXPDKIg1XoWI',
    )
    .then((res) => {
      console.log(res);
      const access_token = res.data.access_token;
      axios
        .get(
          VITE_GLOB_SHANDONG_URL +
            '/cgi-bin/user/getuserinfo?access_token=' +
            access_token +
            '&code=',
        )
        .then((resdata) => {
          console.log(resdata);
          const userid = resdata.data.UserId;
          axios
            .get(
              VITE_GLOB_SHANDONG_URL +
                '/cgi-bin/user/get?access_token=' +
                access_token +
                '&userid=' +
                userid,
            )
            .then((userdata) => {
              console.log(userdata);
              phone = userdata.data.mobile;
            });
        });
    });
  if (phone) {
    return phone;
  }
}
/**
 * 创建权限守卫函数
 * @param router - Vue Router实例
 */
export async function createPermissionGuard(router: Router) {
  const userStore = useUserStoreWithOut();
  const permissionStore = usePermissionStoreWithOut();
  router.beforeEach(async (to, from, next) => {
    const { query } = to;
    if (query.code) {
      const phone = await getPhone();
      console.log('phone', phone);
      const ajaxData = await getsdt({
        // phone: '17853305028',
        phone: phone,
        // phone: 'System',
      });
      console.log('ajaxData', ajaxData);
      if (ajaxData) {
        console.log('获取用户token成功');
        userStore.setToken(ajaxData.token);
        try {
          await userStore.getUserInfoAction();
          const routes = await permissionStore.buildRoutesAction();
          routes.forEach((route) => {
            router.addRoute(route as unknown as RouteRecordRaw);
          });
          router.addRoute(PAGE_NOT_FOUND_ROUTE as unknown as RouteRecordRaw);
          permissionStore.setDynamicAddedRoute(true);
          if (to.name === PAGE_NOT_FOUND_ROUTE.name) {
            // 动态添加路由后，此处应当重定向到fullPath，否则会加载404页面内容
            next({ path: to.fullPath, replace: true, query: to.query });
          }
          next();
        } catch (err) {
          next();
          return;
        }
        return;
      } else {
        next('/error');
        return;
      }
    }
    if (
      from.path === ROOT_PATH &&
      to.path === PageEnum.BASE_HOME &&
      userStore.getUserInfo.homePath &&
      userStore.getUserInfo.homePath !== PageEnum.BASE_HOME
    ) {
      next(userStore.getUserInfo.homePath);
      return;
    }

    const token = userStore.getToken;

    // Whitelist can be directly entered
    if (whitePathList.includes(to.path as PageEnum)) {
      if (to.path === LOGIN_PATH && token) {
        const isSessionTimeout = userStore.getSessionTimeout;
        try {
          await userStore.afterLoginAction();
          if (!isSessionTimeout) {
            next((to.query?.redirect as string) || '/');
            return;
          }
        } catch {
          //
        }
      }
      next();
      return;
    }
    // token or user does not exist
    if (!token) {
      // You can access without permission. You need to set the routing meta.ignoreAuth to true
      if (to.meta.ignoreAuth) {
        next();
        return;
      }

      // redirect login page
      const redirectData: { path: string; replace: boolean; query?: Recordable<string> } = {
        path: LOGIN_PATH,
        replace: true,
      };
      if (to.path) {
        redirectData.query = {
          ...redirectData.query,
          redirect: to.path,
        };
      }
      next(redirectData);
      return;
    }

    // Jump to the 404 page after processing the login
    if (
      from.path === LOGIN_PATH &&
      to.name === PAGE_NOT_FOUND_ROUTE.name &&
      to.fullPath !== (userStore.getUserInfo.homePath || PageEnum.BASE_HOME)
    ) {
      next(userStore.getUserInfo.homePath || PageEnum.BASE_HOME);
      return;
    }

    // get userinfo while last fetch time is empty
    if (userStore.getLastUpdateTime === 0) {
      try {
        await userStore.getUserInfoAction();
      } catch (err) {
        next();
        return;
      }
    }

    if (permissionStore.getIsDynamicAddedRoute) {
      next();
      return;
    }

    const routes = await permissionStore.buildRoutesAction();

    routes.forEach((route) => {
      router.addRoute(route as unknown as RouteRecordRaw);
    });

    router.addRoute(PAGE_NOT_FOUND_ROUTE as unknown as RouteRecordRaw);

    permissionStore.setDynamicAddedRoute(true);

    if (to.name === PAGE_NOT_FOUND_ROUTE.name) {
      // 动态添加路由后，此处应当重定向到fullPath，否则会加载404页面内容
      next({ path: to.fullPath, replace: true, query: to.query });
    } else {
      const redirectPath = (from.query.redirect || to.path) as string;
      const redirect = decodeURIComponent(redirectPath);
      const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect };
      next(nextData);
    }
  });
}
