import { RoleType, PageUrl } from '@/constants/app';
import { CollectEventName } from '@/constants/event';
import { ANCHOR_TAB_LIST, COMPANY_TAB_LIST } from '@/hooks/use-config';
import http from '@/http';
import { API } from '@/http/api';
import store from '@/store';
import { changeRoleType, changeHomePage } from '@/store/actions';
import { selectRoleType } from '@/store/selector';
import { sleep } from '@/utils/common';
import { collectEvent } from '@/utils/event';
import { switchTab } from '@/utils/route';
import Toast from '@/utils/toast';

const postSwitchRoleType = (appMode: RoleType) => {
  const data = { roleType: appMode };
  return http.post(API.APP_MODE_SWITCH, { data });
};

export const getRoleType = () => selectRoleType(store.getState());

export const isAnchorMode = () => getRoleType() === RoleType.Anchor;

export const isCompanyMode = () => getRoleType() === RoleType.Company;

export const switchDefaultTab = async () => {
  await sleep(1);
  const mode = getRoleType();
  const tabList = mode === RoleType.Anchor ? ANCHOR_TAB_LIST : COMPANY_TAB_LIST;
  const item = tabList[0];
  store.dispatch(changeHomePage(item.type));
  switchTab(item.pagePath as PageUrl);
};

export const switchRoleType = async (appMode?: RoleType) => {
  if (!appMode) {
    const curMode = getRoleType();
    appMode = curMode === RoleType.Anchor ? RoleType.Company : RoleType.Anchor;
  }
  try {
    await postSwitchRoleType(appMode);
    store.dispatch(changeRoleType(appMode));
  } catch (e) {
    collectEvent(CollectEventName.SWITCH_APP_MODE_FAILED);
    Toast.error('切换失败请重试');
  }
};
