import { request } from 'utils/fetch';
import { api } from 'constants/config';
import {
  CurPortalBaseInfoType,
  CurPortalNavigationType,
  NavItemType,
  PortalType,
  SpaceShipState,
} from './spaceship.types';
import { actionTypes } from 'constants/action-types';
import message from 'components/message';
import { deepFindOne, parseSearchParams } from 'utils/utils';
import pickBy from 'lodash/pickBy';
import { pathNameIsSpaceShipEdit } from 'utils/spaceship';

export const dispatchUpdateEditPageCurrentTab = (editPageCurrentTab: '0' | '1') => {
  return (dispatch) => {
    dispatch({
      type: actionTypes.UPDATE_EDIT_PAGE_CURRENT_TAB,
      payload: editPageCurrentTab,
    });
  };
};

export const dispatchUpdatePortalBaseInfo = (payload: CurPortalBaseInfoType) => {
  return (dispatch) => {
    dispatch({
      type: actionTypes.UPDATE_PORTAL_BASE_INFO,
      payload,
    });
  };
};

export const dispatchUpdatePortalNavigationInfo = (payload?: CurPortalNavigationType) => {
  return (dispatch) => {
    dispatch({
      type: actionTypes.UPDATE_PORTAL_NAVIGATION_INFO,
      payload: payload || [],
    });
  };
};

export const getSharedPortalById = (id: number, password?: string, isFirstEnter?: boolean) => {
  const token = parseSearchParams()?._easyv_token || null;
  return async (dispatch) => {
    if (isFirstEnter) {
      const res = (await request(
        `${api.getSharedPortalById}/${id}`,
        undefined,
        pickBy({ password, token }),
        undefined,
        {
          message: () => {},
        },
      )) as PortalType | -1 | -2;

      if (res === -1) {
        dispatch({
          type: actionTypes.UPDATE_PORTAL_INFO,
          payload: {
            shareStatus: -1,
            portalId: id,
          },
        });
        return;
      }

      if (res === -2) {
        dispatch({
          type: actionTypes.UPDATE_PORTAL_INFO,
          payload: {
            shareStatus: -2,
            portalId: id,
          },
        });
        message.error('token失效，请登录后再试!');
        return;
      }

      if (res) {
        const { navigation, ...otherInfo } = res;
        dispatch({
          type: actionTypes.UPDATE_PORTAL_INFO,
          payload: {
            curPortalBaseInfo: otherInfo,
            curPortalNavigation: navigation,
            curSelectedKeys: deepFindOne(
              res?.navigation || [],
              (item) => item.quoteType !== 0,
              `children`,
            )?.id,
            shareStatus: 1,
            portalId: id,
          },
        });
        return;
      }

      dispatch({
        type: actionTypes.UPDATE_PORTAL_INFO,
        payload: {
          shareStatus: 0,
          portalId: id,
        },
      });
    }
    const res = (await request(
      `${api.getSharedPortalById}/${id}`,
      undefined,
      pickBy({ password, token }),
      undefined,
    )) as PortalType | -1 | -2;
    if (res === -1) {
      message.error('密码错误');
      return;
    }
    if (res === -2) {
      message.error('token失效，请登录后再试!');
      return;
    }
    if (res) {
      const { navigation, ...otherInfo } = res;
      dispatch({
        type: actionTypes.UPDATE_PORTAL_INFO,
        payload: {
          // curPortalDetail: res,
          curPortalBaseInfo: otherInfo,
          curPortalNavigation: navigation,
          curSelectedKeys: deepFindOne(
            res?.navigation || [],
            (item) => item.quoteType !== 0,
            `children`,
          )?.id,
          shareStatus: 1,
          portalId: id,
        },
      });
    }
  };
};

// 添加门户
export const addPortal = () => {
  return async () => {
    const res = await request(
      api.addPortal,
      undefined,
      undefined,
      JSON.stringify({ title: '未命名门户', name: '未命名门户' }),
    );
    if (res) {
      window.location.href = `${BASENAME}/spaceShipEdit/${res.id}`;
      return;
    }
    message.error('创建失败!');
  };
};

// 删除门户及导航
export const deletePortalById = async (id) => {
  return await request(`${api.deletePortalById}/${id}`, undefined, undefined, undefined);
};

// 复制门户及导航
export const copyPortalById = async (id) => {
  return await request(`${api.copyPortalById}/${id}`, undefined, undefined, undefined);
};

// 更新门户基本信息
export const updatePortalById = async (
  params: NonNullable<Partial<SpaceShipState['curPortalBaseInfo']>>,
) => {
  if (params.name && (params?.name?.length > 30 || params.name?.length < 1)) {
    message.error('门户名称不为空且长度不超过30个字符');
    return;
  }
  const { id, ...otherParams } = params;
  return (await request(
    `${api.updatePortalById}/${id}`,
    undefined,
    undefined,
    JSON.stringify(otherParams),
  )) as PortalType;
};

// 获取门户列表
export const getPortalList = async () => {
  return await request(api.getPortalList, undefined, undefined, undefined);
};

// 根据ID获取门户，包含导航菜单
export const getPortalDetailById = (id: number, curSelectedKeys?: number) => {
  return async (dispatch) => {
    const res: PortalType = await request(
      `${api.getPortalDetailById}/${id}`,
      undefined,
      undefined,
      undefined,
    );
    if (res) {
      const { navigation, ...portalBaseInfo } = res;
      dispatch({
        type: actionTypes.UPDATE_PORTAL_INFO,
        payload: {
          curPortalBaseInfo: portalBaseInfo,
          curPortalNavigation: navigation,
          curSelectedKeys: curSelectedKeys
            ? curSelectedKeys
            : pathNameIsSpaceShipEdit()
            ? res?.navigation?.[0].id
            : deepFindOne(res?.navigation || [], (item) => item.quoteType !== 0, `children`)?.id,
          portalId: id,
        },
      });
      return;
    }
    message.error('门户详情获取失败!');
  };
};
// 根据ID更新驾驶舱导航详情
export const updateNavigationById = (
  params: Partial<
    Pick<
      NavItemType,
      'name' | 'openWay' | 'parentId' | 'quoteType' | 'quotelink' | 'rank' | 'screenId'
    >
  > &
    Pick<NavItemType, 'id' | 'portalId'>,
) => {
  const { id, ...otherParams } = params;
  return async (dispatch) => {
    const res = await request(
      `${api.updateNavigationById}/${id}`,
      undefined,
      undefined,
      JSON.stringify({ ...otherParams }),
    );
    if (res) {
      dispatch(getPortalDetailById(params.portalId, params.id));
      return;
    }
    message.error('门户详情获取失败!');
  };
};
// 创建导航
export const addNavigation = async (
  navigation: Omit<NavItemType, 'id' | 'children' | 'createdAt' | 'level' | 'updatedAt'>,
) => {
  return await request(
    `${api.addNavigation}`,
    undefined,
    undefined,
    JSON.stringify({ ...navigation }),
  );
};

// 根据导航ID删除导航
export const deleteNavigationById = (navId, portalId) => {
  return async (dispatch) => {
    const res = await request(
      `${api.deleteNavigationById}/${navId}`,
      undefined,
      undefined,
      undefined,
    );
    if (res) {
      dispatch(getPortalDetailById(portalId, undefined));
      return;
    }
    message.error('菜单新建失败!');
  };
};

// 更新当前选中的项
export const updateCurSelectedKeys = (key?: number) => {
  return (dispatch) => {
    dispatch({
      type: actionTypes.UPDATE_CUR_SELECTED_KEY,
      payload: key,
    });
  };
};

export const updateCurExpandedNavKeys = (keys: (string | number)[]) => {
  return (dispatch) => {
    dispatch({
      type: actionTypes.UPDATE_CUR_EXPANDED_NAV_KEYS,
      payload: keys,
    });
  };
};

const initialState: SpaceShipState = {
  editPageCurrentTab: '0',
  curPortalBaseInfo: undefined,
  curPortalNavigation: undefined,
  curSelectedKeys: undefined,
  curExpandedNavKeys: [],
  shareStatus: undefined,
};

export default function spaceShipReducer(state = initialState, { type, payload }) {
  switch (type) {
    case actionTypes.UPDATE_EDIT_PAGE_CURRENT_TAB: {
      return {
        ...state,
        editPageCurrentTab: payload,
      };
    }
    case actionTypes.UPDATE_PORTAL_BASE_INFO: {
      return {
        ...state,
        curPortalBaseInfo: payload,
      };
    }
    case actionTypes.UPDATE_PORTAL_NAVIGATION_INFO: {
      return {
        ...state,
        curPortalNavigation: payload,
      };
    }
    case actionTypes.UPDATE_CUR_EXPANDED_NAV_KEYS: {
      return {
        ...state,
        curExpandedNavKeys: payload,
      };
    }
    case actionTypes.UPDATE_CUR_SELECTED_KEY: {
      return {
        ...state,
        curSelectedKeys: payload,
      };
    }

    case actionTypes.UPDATE_PORTAL_INFO: {
      const {
        curSelectedKeys,
        shareStatus = -1,
        curPortalBaseInfo = {},
        curPortalNavigation = {},
      } = payload;
      return {
        ...state,
        curPortalBaseInfo,
        curPortalNavigation,
        curSelectedKeys: curSelectedKeys ? curSelectedKeys : undefined,
        shareStatus,
      };
    }
    default:
      return state;
  }
}
