import message from 'components/message';
import { request } from 'utils/fetch';
import { api } from 'constants/config';
import { actionTypes } from 'constants/action-types';
import { getScreens, changeInfo } from './screens';
import { GroupState } from './group.types';
import { Dispatch } from 'redux';

export function selectGroup(groupId: number | 'trash') {
  return (dispatch: Dispatch) => {
    dispatch({
      type: actionTypes.GROUP_CURRENT_CHANGE,
      payload: {
        current: groupId
      }
    });

    dispatch({
      type: actionTypes.SCREEN_TOP_PAGE
    });
  };
}

export function getGroups(options = {}) {
  return async (dispatch) => {
    const result = await request(api.groupList, undefined, undefined, undefined, { ...options });

    dispatch({
      type: actionTypes.GROUP_GET_LIST_START
    });
    if (result) {
      dispatch({
        type: actionTypes.GROUP_GET_LIST_SUCCESS,
        payload: result
      });
    } else {
      dispatch({
        type: actionTypes.GROUP_GET_LIST_FAILURE
      });
    }
    return result;
  };
}

export function addGroup(name) {
  return async (dispatch) => {
    const result = await request(api.groupAdd, undefined, undefined, JSON.stringify({ name }));

    if (result) {
      dispatch(getGroups());
    }
    return result;
  };
}

export function deleteGroup(groupId) {
  return async (dispatch, getState) => {
    const {
      groups: { current }
    } = getState();

    const result = await request(api.groupDelete, { id: groupId });

    if (result) {
      message.success('删除成功');
      dispatch(getGroups());
      dispatch(getScreens());
      if (current == groupId) {
        // 如果删除的是选中项，则删除后默认选中全部
        dispatch(selectGroup(0));
      }
      return result;
    }
  };
}

export function updateGroup({ groupId, name }) {
  return async (dispatch, getState) => {
    const { groups } = getState();
    const clone = groups.list;
    const list = groups.list.map((d) => {
      if (d.id === groupId) {
        return {
          ...d,
          name
        };
      }
      return d;
    });
    dispatch({
      type: actionTypes.GROUP_GET_LIST_SUCCESS,
      payload: list
    });
    const result = await request(api.groupUpdate, { id: groupId }, undefined, JSON.stringify({ name }));

    if (result) {
      dispatch(getGroups());
    } else {
      dispatch({
        type: actionTypes.GROUP_GET_LIST_SUCCESS,
        payload: clone
      });
    }
    return result;
  };
}

export function moveScreenToGroup({ groupId }) {
  return async (dispatch, getState) => {
    const {
      groups: { list: groupList },
      screens: { list: screenList, dragScreenId: id }
    } = getState();

    const screen = screenList.find((d) => d.screenId === id);

    if (!screen || screen.groupId != groupId) {
      dispatch(
        changeInfo({
          id,
          groupId
        })
      );
    } else {
      const toGroup = groupList.find((o) => o.id === groupId);
      const toGroupName = toGroup ? toGroup.name : '未分组';
      message.error(`该屏已在${toGroupName}组中`);
    }
  };
}

export function moveGroup({ oldIndex, newIndex }) {
  return async (dispatch, getState) => {
    if (oldIndex === newIndex) {
      return;
    }

    const { groups } = getState();
    const list = groups.list;
    const cloneList = list.slice();
    const source = list[oldIndex];
    cloneList.splice(oldIndex, 1);
    cloneList.splice(newIndex, 0, source);

    dispatch({
      type: actionTypes.GROUP_GET_LIST_SUCCESS,
      payload: cloneList
    });

    const result = await request(
      api.groupSort,
      { id: source.id },
      undefined,
      JSON.stringify({ prevId: newIndex === 0 ? 0 : cloneList[newIndex - 1].id })
    );

    if (!result) {
      dispatch({
        type: actionTypes.GROUP_GET_LIST_SUCCESS,
        payload: list
      });
    }
  };
}

const initialState: GroupState = {
  loading: false,
  list: [],
  current: 0
};

export default function groupsReducer(state = initialState, { type, payload }): GroupState {
  switch (type) {
    case actionTypes.GROUP_GET_LIST_START: {
      return { ...state, loading: true };
    }
    case actionTypes.GROUP_GET_LIST_SUCCESS: {
      return { ...state, loading: false, list: payload };
    }
    case actionTypes.GROUP_GET_LIST_FAILURE: {
      return { ...state, loading: false };
    }
    case actionTypes.GROUP_CURRENT_CHANGE: {
      return { ...state, current: payload.current };
    }
    default:
      return state;
  }
}
