import { useEffect } from 'react';
import * as R from 'ramda';
import {split} from '@ywfe/utils';
import { useGetDesktopResourceModuleList } from '@/generated/api';
import {YRouterItem} from '@/default.interface';
import {
  ModuleConfig,
} from './module.interface';
import { useModuleStore } from './useStore';

interface Permission {
  url: string;
  childMenus?: Permission[];
  resourceId: string;
  name: string;
  resourceType: string;
  [key: string]: any;
}

export const useSidebar = ({
  moduleId,
  moduleName,
}: ModuleConfig) => {
  const {
    getDesktopResourceModuleListData,
    isDesktopResourceModuleListLoading,
    dataDesktopResourceModuleList
  } = useGetDesktopResourceModuleList();

  const [, dispatch] = useModuleStore();

  const initMenu = () => {
    getDesktopResourceModuleListData({ moduleId });
  }

  const getMenu = (pathname: string) => {
    console.log('getMenu 0', pathname)
    const list = dataDesktopResourceModuleList.menuResourceList;
    const otherResourceList = dataDesktopResourceModuleList.otherResourceList;
    const {productUserName, productUserId} = dataDesktopResourceModuleList;
    if (!list) {
      return [];
    }
    let paths: string[];
    if (pathname !== '/' && pathname !== '/undefined' && pathname !== '/null') {
      paths = split('/', pathname);
    } else {
      paths = [];
    }
    console.log('getMenu 1', paths)
    const menus: YRouterItem[] = [];
    let defaultOpenMenus: string[] = [];
    let defaultSelectedMenus: string[] = [];
    let defaultMenu = {};
    list.map((item: any) => {
      const path = item.nameEn.indexOf('/') === 0 ? item.nameEn || '' : `/${item.nameEn}`;
      menus.push({
        path,
        url: `/${moduleName}/${moduleId}/#${path}`,
        name: item.resourceId,
        meta: {
            title: item.name,
        },
        origion_url: item.nameEn,
        disable: !item.isHasResourcce,
        productOwner: {
          id: productUserId,
          name: productUserName
        },
        hidden: item.resourceMenuType === 'HIDE_MENU'
      })
    });
    console.log('getMenu 2', menus, defaultSelectedMenus, defaultOpenMenus)
    const permissions = otherResourceList && otherResourceList.length ? R.pipe(R.map(R.prop('url')))(otherResourceList as any[]) : [];

    if(paths.length && menus.length){
      const res = setPathToDefaultMenu(paths, menus);
      defaultSelectedMenus = res.defaultSelectedMenus;
      defaultOpenMenus = res.defaultOpenMenus;
      defaultMenu = res.defaultMenu as YRouterItem;
    } else if (!defaultSelectedMenus.length || !defaultOpenMenus.length || !defaultMenu) {
      const res = setFistChildToDefaultMenu(menus);
      defaultSelectedMenus = res.defaultSelectedMenus;
      defaultOpenMenus = res.defaultOpenMenus;
      defaultMenu = res.defaultMenu as YRouterItem;
    }
    console.log('getMenu 3', defaultMenu)
    dispatch({
      type: 'init_menu',
      payload: {
        data: {
          moduleId,
          menus,
          permissions,
          defaultSelectedMenus,
          defaultOpenMenus,
          defaultMenu: defaultMenu,
          selectedMenus: R.isEmpty(defaultMenu) ? [] : [defaultMenu]
        },
      },
    });
    return menus;
  };

  const setPathToDefaultMenu = (
    paths: string[],
    menus: YRouterItem[]
  ) => {
    let defaultOpenMenus: string[] = [];
    let defaultSelectedMenus: string[] = [];
    let defaultMenu = {} as YRouterItem;
    const openPath = `/${paths.join('/')}`;
    const openMenus = R.find<YRouterItem>(R.propEq<string>('path', openPath))(menus) as YRouterItem;
    if(openMenus){
      defaultOpenMenus = [openMenus.path];
      if(paths.length > 1 && openMenus.children && openMenus.children.length) {
        const defaultPath = `/${paths[0]}/${paths[1]}`;
        defaultMenu = R.find<YRouterItem>(R.propEq<string>('path', defaultPath))(openMenus.children) as YRouterItem;
      } else {
        defaultMenu = openMenus.children && openMenus.children.length ? openMenus.children[0] : openMenus as YRouterItem;
      }
      defaultSelectedMenus = defaultMenu?.path ? [defaultMenu.path] : [];
    }
  
    return {
      defaultOpenMenus,
      defaultSelectedMenus,
      defaultMenu,
    };
  };
  
  const setFistChildToDefaultMenu = (menus: YRouterItem[]) => {
    let defaultOpenMenus: string[] = [];
    let defaultSelectedMenus: string[] = [];
    let defaultMenu = {} as YRouterItem;
    if (menus[0] && menus[0].children && menus[0].children.length) {
      defaultOpenMenus = [menus[0].path];
      defaultSelectedMenus = [menus[0].children[0].path];
      defaultMenu = menus[0].children[0];
    } else if (menus[0]) {
      defaultOpenMenus = [menus[0]?.path as string];
      defaultSelectedMenus = [menus[0]?.path as string];
      defaultMenu = menus[0];
    }
    return {
      defaultOpenMenus,
      defaultSelectedMenus,
      defaultMenu,
    };
  };

  const selectMenu = (path: string) => {
    dispatch({
      type: 'select_menu',
      payload: {
        data: path
      }
    })
  }
  
  return {
    initMenu,
    selectMenu,
    getMenu,
    isLoading: isDesktopResourceModuleListLoading,
  };
};
