import { actionTypes } from 'constants/action-types';
import message from 'components/message';
import { api } from 'constants/config';
import { request } from 'utils/fetch';
import { getGroups } from './group';
import { SpaceState, screensMoveState } from './space.types';
import { getScreens } from './screens';
import { actions } from 'containers/interaction-list/models/list';
import { getSources } from 'models/source';

function getTime(t) {
  return t ? new Date(t).getTime() : 0;
}

export function getSpaceUserList() {
  return async (dispatch, getState) => {
    const { space } = getState();
    const { current } = space;
    const id = current;
    if (!id) {
      return;
    }
    const result = await request(api.spaceUserList, { id }, undefined);
    if (result) {
      dispatch({
        type: actionTypes.SPACE_CONSTANT_SET_USER_LIST,
        payload:
          result.users.length > 1
            ? result.users.sort((a, b) => {
                return getTime(b.relatedAt) - getTime(a.relatedAt);
              })
            : result.users
      });
    }
  };
}

export function getAllSpaceUserList() {
  return async (dispatch) => {
    const result = await request(api.spaceAllUser, undefined, undefined);
    dispatch({
      type: actionTypes.SPACE_CONSTANT_SET_ALL_USER_LIST,
      payload: result.sort((a, b) => {
        return getTime(b.relatedAt) - getTime(a.relatedAt);
      })
    });
  };
}

// 切换空间id
export function spacesCut(id: number) {
  return async (dispatch) => {
    if (id) {
      const result = await request(api.spacesCut, undefined, undefined, JSON.stringify({ spaceId: id }));
      if (result) {
        await dispatch({
          type: actionTypes.SPACE_CONSTANT_SET_CURRENT,
          payload: id
        });
        await dispatch(getSpaceCurrent());
      }
      return result;
    }
  };
}

export function deleteSpace(id: number) {
  return async (dispatch) => {
    const hide = message.loading('删除中...', 0);
    const result = await request(api.spaceDelete, { id }, undefined);
    hide();
    if (!result) {
      return false;
    }
    message.success('删除成功');
    await dispatch({
      type: actionTypes.SPACE_CONSTANT_SET_DELETE
    });
    await dispatch(getSpace());
    await dispatch(autoSetCurrent());
  };
}

export function screensMove({ screen, toSpace }: screensMoveState) {
  return async (dispatch) => {
    const hide = message.loading('移动中...', 0);
    const result = await request(
      api.screensMove,
      { id: screen },
      undefined,
      JSON.stringify({
        spaceId: toSpace
      })
    );
    hide();
    if (result) {
      message.success('移动成功');
    }
    if (result) {
      dispatch(getScreens());
    }
    dispatch({
      type: actionTypes.SPACE_CONSTANT_SET_MOVE_SCREEN,
      payload: result
    });
    return result;
  };
}

export function updateSpace(update) {
  return async (dispatch, getState) => {
    const { space } = getState();
    const { current } = space;
    const id = current;
    const result = await request(api.spaceUpdate, { id }, undefined, JSON.stringify(update));
    if (!result && update.name) {
      dispatch({
        type: actionTypes.SPACE_CONSTANT_GET_LIST,
        payload: {
          list: []
        }
      });
    }
    dispatch(getSpace());
    if (!result) {
      return false;
    }

    let _meg = '修改成功';
    if (update?.removeUsers) {
      _meg = '删除成功';
    } else if (update?.addUsers) {
      _meg = '添加成功';
    }
    dispatch(getSpaceUserList());
    message.success(_meg);
    dispatch({
      type: actionTypes.SPACE_CONSTANT_SET_UPDATE,
      payload: result
    });
  };
}

export function addSpace(name: string) {
  return async (dispatch) => {
    const result = await request(api.spaceAdd, undefined, undefined, JSON.stringify({ name, size: 0 }));
    if (!result) {
      return;
    }
    dispatch({
      type: actionTypes.SPACE_CONSTANT_SET_LIST_ITEM,
      payload: result
    });
  };
}

export function updateLoading(loading = false) {
  return async (dispatch) => {
    dispatch({
      type: actionTypes.SPACE_CONSTANT_SET_LOADING,
      payload: loading
    });
  };
}

export function moveSpace({ oldIndex, newIndex }: { oldIndex: number; newIndex: number }) {
  return async (dispatch, getState) => {
    const { space } = getState();
    const list = JSON.parse(JSON.stringify(space.list)).filter((d) => d.type);
    list[newIndex] = list.splice(oldIndex, 1, list[newIndex])[0];
    const newList = [space.list.find((d) => !d.type), ...list];
    const result = await request(
      api.spacePatch,
      undefined,
      undefined,
      JSON.stringify({
        sort: newList.map((d) => d.id)
      })
    );
    dispatch({
      type: actionTypes.SPACE_CONSTANT_GET_LIST,
      payload: {
        list: newList
      }
    });
  };
}

export function autoSetCurrent() {
  return async (dispatch, getState) => {
    const { space, current: spaceId } = getState();
    const { list } = space;
    if (list.length) {
      const i = spaceId ? list.findIndex((d) => d.id == spaceId) : null;
      const spacedefault = list.find((e) => e.type === 0);
      const current = i && i > -1 ? parseInt(spaceId) : spacedefault.id;
      await dispatch({
        type: actionTypes.SPACE_CONSTANT_SET_CURRENT,
        payload: current
      });
      await dispatch(getSpaceCurrent());
    }
  };
}

export function setCurrent(current: number) {
  return async (dispatch) => {
    const result = await request(api.spacesCut, undefined, undefined, JSON.stringify({ spaceId: current }));
    if (result) {
      dispatch(updateApi(current));
      dispatch({
        type: actionTypes.SPACE_CONSTANT_SET_CURRENT,
        payload: current
      });
      dispatch(getSpaceCurrent());
      if (/\/app/.test(window.location.pathname)) {
        // 终端
        dispatch(actions.getList());
      } else if (/\/source/.test(window.location.pathname)) {
        // 我的数据
        dispatch(getSources());
      }
    }
  };
}

export function updateApi(current) {
  return async (dispatch, getState) => {
    const { space } = getState();
    const { current: oldCurrent } = space;

    if (current !== oldCurrent) {
      await dispatch(getGroups({ hideError: true })); //更新分组
      await dispatch(getScreens()); //更新大屏
    }
  };
}

export function getSpaceCurrent() {
  return async (dispatch, getState) => {
    const { space } = getState();
    const { list, current } = space;
    const item = list.find((e) => e.id === current);
    dispatch({
      type: actionTypes.SPACE_CONSTANT_SET_ACTIVE,
      payload: item
    });
  };
}

export function getSpace(code?: string) {
  return async (dispatch, getState) => {
    const { space } = getState();
    dispatch(updateLoading(true));
    const result = (await request(api.spaceList)) || [];
    dispatch(updateLoading());
    if (result) {
      const item = result.find((d) => d.isUsing);
      if (code && code === 'update' && item.id !== space.current) {
        await dispatch(getGroups({ hideError: true })); //更新分组
        await dispatch(getScreens()); //更新大屏
      }
      if (item) {
        await dispatch({
          type: actionTypes.SPACE_CONSTANT_SET_CURRENT,
          payload: item.id
        });
      }
      dispatch({
        type: actionTypes.SPACE_CONSTANT_GET_LIST,
        payload: {
          list: result
        }
      });
      await dispatch(getSpaceCurrent());
    }

    return result;
  };
}

export function getSpaceData() {
  return async (dispatch, getState) => {
    const { space } = getState();
    return space;
  };
}

const initialState: SpaceState = {
  list: [],
  loading: true,
  current: 0,
  active: null,
  userList: [],
  spaceAllUserList: []
};
export default function reducer(state = initialState, { type, payload }) {
  switch (type) {
    case actionTypes.SPACE_CONSTANT_GET_LIST: {
      return { ...state, ...payload };
    }
    case actionTypes.SPACE_CONSTANT_SET_LIST_ITEM: {
      const _list = JSON.parse(JSON.stringify(state.list));
      _list.splice(1, 0, payload);
      return { ...state, list: _list };
    }
    case actionTypes.SPACE_CONSTANT_SET_ACTIVE: {
      return {
        ...state,
        active: payload
      };
    }
    case actionTypes.SPACE_CONSTANT_SET_USER_LIST: {
      return {
        ...state,
        userList: payload
      };
    }
    case actionTypes.SPACE_CONSTANT_SET_UPDATE: {
      const i = state.list.findIndex((d) => d.id === payload.id);
      const list = state.list;
      if (i === -1) {
        // 不存在
        list.unshift(payload);
      } else {
        list.splice(i, 1, payload);
      }
      return {
        ...state,
        list
      };
    }
    case actionTypes.SPACE_CONSTANT_SET_LOADING: {
      return {
        ...state,
        loading: payload
      };
    }
    case actionTypes.SPACE_CONSTANT_SET_ALL_USER_LIST: {
      return {
        ...state,
        spaceAllUserList: payload
      };
    }
    case actionTypes.SPACE_CONSTANT_SET_CURRENT: {
      sessionStorage.setItem('spaceId', payload + '');
      return {
        ...state,
        current: payload
      };
    }
    default:
      return state;
  }
}
