import { PageLoading } from '@ant-design/pro-layout';
import { history, useModel } from 'umi';
import { checkToken, reFreshCheckToken } from '@/services/sgservice/environment';
import { projectObj } from '@/config/api.js';
import UserStorage from '@/config/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>;
  //loading?: boolean;
  //fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {
  const { location } = history;

  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);
  }
  console.log('getInitialState');
  //如果没有  取缓存
  //   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;
    }
  };

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

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

  const reFreshUser = async () => {
    refresh_token = localStorage.getItem('refresh_token');
    //刷新token 续约token
    const res = await reFreshCheckToken({
      zjfreshtoken: refresh_token,
    });
    if (res.refresh_token) {
      console.log('refresh_token', res.refresh_token);
      localStorage.setItem('refresh_token', res.refresh_token);
      localStorage.setItem('access_token', res.access_token);
    } else {
      //如果刷新token失败
      //history.push(loginPath);
    }
    //1分钟后再执行
    setTimeout(() => {
      // reFreshUser();
    }, 60000);
  };

  //await reFreshUser();

  // || {
  //   companyId: '245e7060643811eb934c0237aedb39a6',
  //   createDate: 1642388952000,
  //   depName: '[["研发算法组","上格云","博锐尚格科技股份有限公司"]]',
  //   firstUseTime: '2020-10-16 18:37:05',
  //   id: '2d2440710d4548f3afa55c4e8244538e',
  //   job: '研发工程师',
  //   manageUserType: 1,
  //   name: '赵小静',
  //   phone: '18801040736',
  //   projectId: 'Pj1101080259',
  //   status: 2,
  //   type: 1,
  //   updateDate: 1642388952000,
  // };

  return {
    currentUser,
    fetchUser,
  };
}

export const request = {
  requestInterceptors: [
    (url: any, options: any) => {
      return {
        url,
        options: {
          ...options,
          interceptors: true,
        },
      };
    },
  ],
  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,
//   };
// };
