import React, { useEffect, useState } from 'react';
import {YCard} from '@/card/card';
import {message} from 'antd';
import { useHistory } from 'react-router-dom';
import {Loading} from '../loading';
import {YEmpty} from '../empty';
import {DesktopCloudListTreeItem} from '@/generated/api';
import {useModuleList} from './useModuleList';
import {
  ModuleListStyle,
  ModuleItemCloudStyle, 
  ModuleItemRowStyle, 
  ModuleItemAPPListStyle, 
  ModuleItemAPPItemStyle
} from './module.styles';

export const YModuleList: React.FC = () => {
  const {selectModule, linkModule, initModuleList, transformToDesktopMenus} = useModuleList();
  const [list, setList] = useState<DesktopCloudListTreeItem[]>(null as unknown as DesktopCloudListTreeItem[]);
  const historyRouter = useHistory();

  const onClick = async(data: any) => {
    const menu = transformToDesktopMenus(data);
    // lockModule(menu);
    selectModule(menu);
    linkModule(menu);
    menu && menu.path && historyRouter.push('/')
  }

  const initData = async () => {
    const res = await initModuleList();
    setList(res);
  }

  const clickModule = (data: any) => {
    if(data.moduleType === 'TRAILER'){
      message.info(data.trailerText)
    } else {
      onClick(data)
    }
  }

  useEffect(() => {
    initData()
  }, []);
  
  if(!list){
    return (
      <Loading.ContainerLoading />
    )
  }

  return (
    <ModuleListStyle>
      {
        list.length ? list.map((item: DesktopCloudListTreeItem, index: number) => (
        <ModuleItemRowStyle key={item.cloudCategoryId}>
          <ModuleItemCloudStyle index={index % 4}>
            <p>
              <span>{item.cloudCategoryName}</span>
            </p>
          </ModuleItemCloudStyle>
          <ModuleItemAPPListStyle>
            {
              item.moduleList && item.moduleList.length && item.moduleList.map((data: any) => (
                <ModuleItemAPPItemStyle key={data.moduleId} >
                  <YCard.EntryCard 
                    icon={data.moduleIcon} 
                    title={data.moduleName} 
                    desc={data.moduleRemark}
                    isNew={data.moduleType === 'ONLINE'}
                    onClick={() => clickModule(data)}
                  />
                </ModuleItemAPPItemStyle>
              ))
            }
          </ModuleItemAPPListStyle>
        </ModuleItemRowStyle>
        )) : <YEmpty stage="no_permission" />
      }
    </ModuleListStyle>
  );
}