import React, { createContext, Dispatch, SetStateAction, useEffect, useState } from 'react';
import api, { UserInfoResp } from '~/api';

export const UserContext = createContext<{
  testLogin: () => void;
  logout: () => void;
  userInfo: UserInfoResp | null | undefined;
  setUserInfo: Dispatch<SetStateAction<UserInfoResp | null | undefined>>;
  needLogin: Boolean;
  setNeedLogin: Dispatch<SetStateAction<Boolean>>;
}>({
  testLogin() {},
  logout() {},
  userInfo: null,
  setUserInfo() {},
  needLogin: false,
  setNeedLogin() {},
});

type Props = {
  children: React.ReactNode;
};
const UserProvider = ({ children }: Props) => {
  const [userInfo, setUserInfo] = useState<UserInfoResp | null | undefined>(null);
  const [needLogin, setNeedLogin] = useState<Boolean>(false); //用于通知登录modal需要打开

  useEffect(() => {
    try {
      setUserInfo(JSON.parse(window.localStorage.getItem('userInfo') || '') || undefined);

      window.setUserInfo = setUserInfo;
      window.setNeedLogin = setNeedLogin;
      window.logout = logout;
    } catch (e) {}
  }, []);

  useEffect(() => {
    if (userInfo !== null) {
      localStorage.setItem('userInfo', JSON.stringify(userInfo || ''));
    }
  }, [userInfo]);

  //测试登录
  function testLogin() {
    api.testAppletLogin().then((res) => {
      if (res.code == '200') {
        window.localStorage.setItem('token', res.result?.token || '');
        api.userInfo().then((res) => {
          setUserInfo(res.result || undefined);
        });
      }
    });
  }

  //登出
  function logout() {
    localStorage.setItem('token', '');
    setUserInfo(undefined);
  }

  return (
    <UserContext.Provider
      value={{
        userInfo,
        setUserInfo,
        testLogin,
        logout,
        needLogin,
        setNeedLogin,
      }}
    >
      {children}
    </UserContext.Provider>
  );
};

export default UserProvider;
