import { PageLoading } from '@ant-design/pro-layout';
import { history, useModel } from 'umi';
import { queryTenantData } from '@/services/sagacare_service/member';

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  projectId: String;
  currentUser?: API.CurrentUser;
  companyConfig?: any;
  //fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {
  const { location } = history;
  var token = localStorage.getItem('token');
  // if (location.pathname.indexOf('login') == -1 && !token) {
  //   history.push('/login');
  // }
  if (location.pathname.indexOf('login') > -1 && token) {
    history.push('/home');
  }
  //debugger;
  let currentUser = {
    appId: 'wxda2ef261ac3cca32',
    companyId: '17fe48afcdde4d6797583c6d6270a035', // ff80c708fe72446eb790b764c3a7b66b,
    loginType: 'app',
    manageUserType: 3,
    name: '赵静',
    openId: 'oDcGY5Qq3Vk-7WKTNsn-lLGNT118',
    phone: '13810794283',
    projectId: 'Pj1101080259', //  Pj1101099999
    userId: 'db445a9cd7be4341a14448928014605c',
  };
  let projectId = 'Pj1101080259'; //  Pj1101099999
  if (location.pathname.indexOf('login') == -1 && token) {
    var localUser = localStorage.getItem('user') || '';
    currentUser = JSON.parse(localUser);
    projectId = currentUser?.projectId;
  }
  let companyConfig = {};
  if (currentUser.userId) {
    const res = await queryTenantData(currentUser);
    companyConfig = res.data;
  }

  return {
    projectId,
    currentUser,
    companyConfig,
  };
}

export const request = {
  requestInterceptors: [
    (url: any, options: any) => {
      return {
        url,
        options: {
          ...options,
          interceptors: true,
          headers: {
            ...options.headers,
            'saga-token': localStorage.getItem('token'),
          },
        },
      };
    },
  ],
  responseInterceptors: [
    async (response: any) => {
      return response;
    },
  ],
  errorHandler: (error: any) => {
    const { response } = error;
    if (!response) {
      // message.error('您的网络发生异常，无法连接服务器');
    }
    throw error;
  },
};
