import React, {useState, useEffect} from 'react';
import { useHistory } from 'react-router-dom';
import {SortableContainer, SortableElement, SortEnd, arrayMove} from 'react-sortable-hoc';
import * as R from 'ramda';
import {YIcon} from '@/icon';
import {message} from 'antd';
import {useSystemContext} from '@/system/system.context';
import {SortableListProps, SortableItemProps, SortableComponentProps} from './desktop.interface';
import { 
  FeatureItemStyle,
  FeatureItemDeleteStyle,
  SortableListStyle,
  AddItemStyle
} from './desktop.styles';
import {useDesktop} from './useDesktop';
import {useModuleList} from '../module/useModuleList';
import {useDesktopStore} from './useDesktopStore';

const colors = ['#1890FF', '#9C7AFF', '#F15A5A', '#FAAD14', '#23CBB7']
const icons = ['ywcloudIcondianhu', 'ywcloudIcondianlang', 'ywcloudIcongongyingshangzhongxin', 'ywcloudIconyingxiaozhongxin', 'ywcloudIcondingdanzhongxin', 'ywcloudIconjiesuanzhongxin', 'ywcloudIconyangpincangguanli', 'ywcloudIconyonghuzhongxin', 'ywcloudIconshangpinzhongxin', 'ywcloudIconfenxiaozhongxin', 'ywcloudIconzhibozhongxin', 'ywcloudIcondianlang-xiao', 'ywcloudIcongongyingshangzhongxin-xiao', 'ywcloudIconfenxiaozhongxin-xiao', 'ywcloudIcontianjia', 'ywcloudIcondingdanzhongxin-xiao', 'ywcloudIcondianhu-xiao', 'ywcloudIconpeizhi', 'ywcloudIconyonghuzhongxin-xiao', 'ywcloudIconshouye', 'ywcloudIconshangpinzhongxin-xiao', 'ywcloudIconjiesuanzhongxin-xiao', 'ywcloudIconyangpincangguanli-xiao', 'ywcloudIconyingyong', 'ywcloudIconyingxiaozhongxin-xiao', 'ywcloudIconzhibozhongxin-xiao']

const SortableItem = SortableElement(({dataSource, edit}: SortableItemProps) => {
  const {delectFunction} = useDesktop();
  const {transformToDesktopMenus, selectModule} = useModuleList();
  const {history} = useSystemContext();
  const historyRouter = useHistory();

  const onDelete = async(e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
    e.stopPropagation();
    e.nativeEvent.stopImmediatePropagation();
    const res = await delectFunction(dataSource.resourceId);
    if(res){
      message.success('删除成功！')
    }
  }

  const onClick = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
    e.stopPropagation();
    e.nativeEvent.stopImmediatePropagation();
    console.log('desktoponClick', dataSource);
    const {moduleId, moduleNameEn, nameEn} = dataSource;
    if(!moduleId || !moduleNameEn){
      message.info('模块已删除！')
    } else {
      const menu = transformToDesktopMenus(dataSource);
      // lockModule(menu);
      selectModule(menu);
      const url = `/${moduleNameEn}/${moduleId}/#${nameEn}`;
      history && history.push(url);
      console.log('click menu', nameEn)
      historyRouter.push(nameEn);
    }
  }

  return (
    <FeatureItemStyle edit={edit} onClick={edit ? () => {} : onClick}>
      <YIcon name={icons[dataSource.index % icons.length]} size="2rem" color={colors[dataSource.index % colors.length]} />
      <p>{dataSource.resourceName}</p>
      {
        edit ? (
        <FeatureItemDeleteStyle onClick={onDelete}>
          <YIcon name="CloseOutlined" size="2" />
        </FeatureItemDeleteStyle>
        ) : null
      }
    </FeatureItemStyle>
  )

});

const SortableList = SortableContainer(({items, edit, onAdd}: SortableListProps) => {
  return (
    <SortableListStyle>
      {
        items.map((item: any, index: number) => (
          <SortableItem 
            dataSource={{...item, index}} 
            key={item.resourceId} 
            index={index}
            edit={edit}
            disabled={!edit}
          />
        ))
      }
      <AddItemStyle edit={edit} onClick={onAdd}>
        <YIcon name="PlusOutlined" />
        <span>添加常用</span>
      </AddItemStyle>
    </SortableListStyle>
  );
});

export const SortableComponent: React.FC<SortableComponentProps> = ({editDisable, onAdd}) => {
  const [state] = useDesktopStore();
  const {initFunctions, dragFunctions} = useDesktop();

  const onSortEnd = ({oldIndex, newIndex}: SortEnd) => {
    const items = arrayMove(state.functions, oldIndex, newIndex);
    const ids = R.pipe(R.map(R.prop('resourceId')))(items) || [];
    dragFunctions(ids as string[], items);
  }

  useEffect(() => {
    initFunctions()
  }, []);

  return (
    <>
      <SortableList 
        edit={!editDisable}
        items={state.functions}
        onAdd={onAdd}
        onSortEnd={onSortEnd}
        axis="xy"
        helperClass="isDraging"
        distance={1}
      />
    </>
  );
}

