import Actions from '../../../types/Store/Actions';
import Order, { AllOrderItem } from '../../../types/Order/Order';
import {
  TOGGLE_ORDER_STATE,
  UPDATE_PAY_LIST,
  UPDATE_ALL_LIST,
} from './actions';

export interface StoreState {
  orderState: String;
  payList: Order[];
  allList: AllOrderItem[];
}

const INITIAL_STATE = {
  orderState: 'all',
  payList: [],
  allList: [],
};

export default function OrderList(
  state: StoreState = INITIAL_STATE,
  actions: Actions,
) {
  switch (actions.type) {
    case TOGGLE_ORDER_STATE:
      return {
        ...state,
        orderState: actions.payload,
      };
    case UPDATE_PAY_LIST:
      if (actions.payload.lastOrderId) {
        return {
          ...state,
          payList: [...state.payList, ...actions.payload.list],
        };
      } else {
        return {
          ...state,
          payList: actions.payload.list,
        };
      }
    case UPDATE_ALL_LIST:
      if (actions.payload.lastOrderId) {
        if (actions.payload.list.length) {
          let key = actions.payload.list[0].groupName;
          let index = state.allList.findIndex(item => item.groupName == key);
          if (index > -1) {
            return {
              ...state,
              allList: [
                ...state.allList.slice(0, index),
                {
                  groupName: state.allList[index].groupName,
                  data: [
                    ...state.allList[index].data,
                    ...actions.payload.list[0].data,
                  ],
                },
                ...actions.payload.list.slice(1),
              ],
            };
          }

          return {
            ...state,
            allList: [...state.allList, ...actions.payload.list],
          };
        }
        return state;
      }
      return {
        ...state,
        allList: actions.payload.list,
      };
    default:
      return state;
  }
}
