import { PageLoading } from '@ant-design/pro-layout';
import { history, useModel } from 'umi';
import { message } from 'antd';
import {
  checkToken,
  reFreshCheckToken,
  getUsersInfo,
} from '@/services/sagacare_service/environment';
// import { projectObj } from '@/config/api.js';
import UserStorage from '@/config/sagacare/sagacare_user';
const loginPath = '/noAuth';

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

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  // settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  fetchUser?: () => Promise<API.CurrentUser | undefined>;
  projectId?: any;
  //loading?: boolean;
  //fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {
  const { location } = history;
  let currentUser = {};
  const checkUser = async () => {
    //获取用户信息 查看权限
    try {
      var userres = await getUsersInfo(); //通过token获取用户信息
    } catch (err) {
      history.push('/login');
      return {};
    }

    if (userres?.result === 'success') {
      var roles = userres.roles || [];
      if (
        roles.find((item: any) => {
          return item.name == '上格云行政端';
        })
      ) {
        //当用户名 密码正确，并且有权限时才跳转
        currentUser = {
          name: userres.username,
          phone: '',
          id: userres.userId,
          projects: userres.projects,
        };
        var userObj = UserStorage.getInstance();
        userObj.setUser(currentUser);
      } else {
        message.error('您没有行政端权限');
        history.push('/login');
        return {};
      }
    } else {
      history.push('/login');
    }
  };
  if (location.pathname !== '/login') {
    //console.log("localStorage.getItem('token')", localStorage.getItem('token'));
    if (!localStorage.getItem('token')) {
      //如何token不存在 则跳到登录页面
      history.push('/login');
      return {};
    } else {
      //如果存在token
      await checkUser();
    }
  } else {
    return {};
  }
  let access_token: any = location.query.access_token;
  let refresh_token: any = location.query.refresh_token;

  //如果有值 存起来
  if (access_token) {
    localStorage.setItem('access_token', access_token);
    console.log("localStorage.getItem('access_token')", localStorage.getItem('access_token'));
  }
  if (refresh_token) {
    localStorage.setItem('refresh_token', refresh_token);
  }

  //如果没有  取缓存
  //   if (!refresh_token) {
  //     refresh_token = localStorage.getItem('refresh_token');
  //   }

  const fetchUser = async () => {
    try {
      access_token = localStorage.getItem('access_token');
      //if (!access_token) return; //随后去掉
      //验证acces_token 获取用户数据
      const res = await checkToken({ token: access_token });

      var resUser = res.data;
    } catch (err) {
      history.push(loginPath);
    }

    if (resUser) {
      //获取用户信息 并储存
      var userObj = UserStorage.getInstance();
      userObj.setUser(resUser);

      return resUser;
    } else {
      history.push(loginPath);
      return undefined;
    }
  };

  var projectId = 'Pj1101080259';
  return {
    currentUser,
    fetchUser,
    projectId,
  };
}

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

// ProLayout 支持的api https://procomponents.ant.design/components/layout
// export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
//   return {
//     rightContentRender: () => <RightContent />,
//     disableContentMargin: false,
//     waterMarkProps: {
//       content: initialState?.currentUser?.name,
//     },
//     footerRender: () => <Footer />,
//     onPageChange: () => {
//       const { location } = history;
//       // 如果没有登录，重定向到 login
//       if (!initialState?.currentUser && location.pathname !== loginPath) {
//         history.push(loginPath);
//       }
//     },
//     links: isDev
//       ? [
//           <Link to="/umi/plugin/openapi" target="_blank">
//             <LinkOutlined />
//             <span>OpenAPI 文档</span>
//           </Link>,
//           <Link to="/~docs">
//             <BookOutlined />
//             <span>业务组件文档</span>
//           </Link>,
//         ]
//       : [],
//     menuHeaderRender: undefined,
//     // 自定义 403 页面
//     // unAccessible: <div>unAccessible</div>,
//     // 增加一个 loading 的状态
//     childrenRender: (children, props) => {
//       // if (initialState?.loading) return <PageLoading />;
//       return (
//         <>
//           {children}
//           {!props.location?.pathname?.includes('/login') && (
//             <SettingDrawer
//               enableDarkTheme
//               settings={initialState?.settings}
//               onSettingChange={(settings) => {
//                 setInitialState((preInitialState) => ({
//                   ...preInitialState,
//                   settings,
//                 }));
//               }}
//             />
//           )}
//         </>
//       );
//     },
//     ...initialState?.settings,
//   };
// };
