import { createSubscriptionHook } from '@ywfe/hook-subscription';
import * as R from 'ramda';
import {YRouterItem} from '@/default.interface';
import {
  ModuleAction,
  ModuleState,
} from './module.interface';

const initialState: ModuleState = {
  menus: (null as unknown) as YRouterItem[],
  defaultSelectedMenus: [],
  defaultOpenMenus: [],
  selectedMenus: [],
  openMenu: [],
  permissions: [],
  pageName: '',
  pageData: {},
  isInit: false,
  moduleId: '',
};

const reducer = (
  state: ModuleState,
  action: ModuleAction,
): ModuleState => {
  switch (action.type) {
    case 'init_menu': {
      return {
        ...state,
        ...action.payload.data,
        isInit: true,
      };
    }
    case 'select_menu': {
      const newSelectedMenus = [...state.selectedMenus];
      const path = action.payload.data;
      const menuIndex = R.findIndex(R.propEq('path', path), state.menus as any);
      const menu = state.menus[menuIndex];
      const index = R.findIndex(R.propEq('path', path), state.selectedMenus as any);
      if(index < 0){
        newSelectedMenus.push(menu);
      }
      return {
        ...state,
        selectedMenus: newSelectedMenus,
        defaultMenu: menu
      }
    }
    case 'close_menu': {
      const {path, selectedMenus} = action.payload.data;
      
      const list = R.filter((item: any) => item.path !== path)(selectedMenus) as YRouterItem[];
      console.log('close_menu', path, list)
      return {
        ...state,
        selectedMenus: list,
        defaultMenu: list[list.length - 1]
      }
    }
    case 'init_selected': {
      return {
        ...state,
        selectedMenus: [],
      }
    }
    case 'update_selected': {
      return {
        ...state,
        selectedMenus: action.payload.data,
      }
    }
    default: {
      return state;
    }
  }
};
export const useModuleStore = createSubscriptionHook(
  reducer,
  initialState,
);
