import { create } from "@zjxpcyc/react-tiny-store";
import { routes, getAllRoutes } from "@/routes/routes";
import { getMenuItems } from "@/routes/menus";
import { refreshAuthedRoutes } from "@/routes/permissions";
import { currentUser } from "@/service/sysuser";

const getTicket = () => {
  const matches = /ticket=([^?&/#]*)/.exec(window.location.href);
  return matches ? matches[1] : undefined;
}

const useUserModel = create(({ setState }) => {
  const state = {
    isLogin: false,
    user: undefined,
    permissions: [],
  }

  const updateState = key => value => setState(x => ({ ...x, [key]: value }));
  const setUser = updateState('user');

  const getCurrentUser = () =>
    new Promise((resolve, reject) => {

      const params = {
        ticket: getTicket(),
        appid: APPID,
      }


      currentUser(params)
        .then((res) => {
          const permissions = (res.user.menuList || []).map((x) => x.menuCode);

          // 计算授权路由
          refreshAuthedRoutes(permissions);

          setState({
            isLogin: true,
            user: res.user,
            permissions,
          })

          resolve(res);
        })
        .catch(reject);
    });

  return {
    state,
    actions: { getCurrentUser, setUser },
  };
});

export default useUserModel;
