import { PageLoading } from '@ant-design/pro-layout';
import { history, useModel } from 'umi';
import UserStorage from '@/config/sagacare/sagacare_user';

/** 获取用户信息比较慢的时候会展示一个 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;
  fetchUser?: () => Promise<API.CurrentUser | undefined>;
  //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;
  }

  if (projectId == 'Pj3301100002') {
    //之江项目 验证token
    // currentUser = await fetchUser();
  } else {
    //非之江项目
    let tempUser = {
      name: '行政测试',
      phone: '17611228068',
      id: '9a1ecfbacb6b4f249bf2dd3ec7793ead',
    };

    var userObj = UserStorage.getInstance();
    userObj.setUser(tempUser);
  }

  return {
    projectId,
    currentUser,
  };
}

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