import { OrgData } from '@ibiz-template/core';
import { ModelUtil } from '@ibiz-template/model';
import { UnauthorizedHandler } from '../unauthorized-handler/unauthorized-handler';

/**
 * 初始化模型
 *
 * @author chitanda
 * @date 2022-07-20 20:07:58
 * @return {*}  {Promise<void>}
 */
async function loadModel(): Promise<void> {
  await ModelUtil.create(async modelPath => {
    const url = `${ibiz.env.remoteModelUrl}${modelPath}`;
    const res = await ibiz.net.get(url);
    if (res.ok) {
      return res.data as IModel;
    }
    return {};
  });
}

/**
 * 加载应用数据
 *
 * @author chitanda
 * @date 2022-07-20 20:07:50
 * @return {*}  {Promise<void>}
 */
async function loadAppData(): Promise<void> {
  const res = await ibiz.net.get('/appdata');
  if (res.ok) {
    ibiz.appData = res.data;
  }
}

/**
 * 加载组织数据
 *
 * @author chitanda
 * @date 2022-07-20 20:07:44
 * @return {*}  {Promise<void>}
 */
async function loadOrgData(): Promise<void> {
  const res = await ibiz.net.get(`/uaa/getbydcsystem/${ibiz.env.dcSystem}`);
  if (res.ok) {
    const orgDataItems = res.data as OrgData[];
    if (orgDataItems) {
      const [data] = orgDataItems;
      ibiz.orgData = data;
    }
  }
}

/**
 * 应用参数初始化
 *
 * @author chitanda
 * @date 2022-07-20 19:07:54
 * @return {*}  {Promise<void>}
 */
async function appInit(): Promise<void> {
  try {
    await loadOrgData();
    await loadAppData();
    await loadModel();
    // 设置权限服务需要的appData里的数据
    await ibiz.authority.init();
  } catch (error) {
    const { response, message } = error as IData;
    if (response?.status === 401) {
      await UnauthorizedHandler.handle();
    }
    console.log(`应用参数初始化失败：${message}`);
  }
}

export async function AuthGuard(): Promise<boolean> {
  await appInit();
  return true;
}
