import React, { useEffect, useState, useRef } from 'react';
import Icon from '../../Icon/index';
import LargeScreenLayerInput from '../LargeScreenLayerInput/index';
import Sortable from 'sortablejs';
import { IGISChildren } from '../../../type/largeScreenLayer';
import { Dropdown, Menu, Input } from 'antd';

function LargeScreenGISList(props: IProps) {
  const gisChildLayerMenuList = [
    {
      key: 'shangyi',
      label: '上移一层',
      icon: <Icon name="custom-icon-shangyiyiceng" />
    },
    {
      key: 'xiayi',
      label: '下移一层',
      icon: <Icon name="custom-icon-xiayiyiceng" />
    },
    { key: 'del', label: '删除', icon: <Icon name="icon-shanchu" /> },
    {
      key: 'rename',
      label: '重命名',
      icon: <Icon name="icon-icon_zhongmingming" />
    }
  ];
  const { GISChildren, layerListEvent } = props;
  const [isCurrentInput, setIsCurrentInput] = useState(-1);
  const listRef = useRef(null); // 图层列表容器ref
  const sortableRef = useRef(null); // sortable
  const dragRef = useRef(null); // 拖动开始

  useEffect(() => {
    if (GISChildren.length > 0) {
      sortableRef?.current?.destroy();
      initSort();
    }
  }, [GISChildren]);

  const zoomMenu = (item, index) => {
    let menu = [...gisChildLayerMenuList];
    if (item.isHide) {
      menu.push({
        key: 'show',
        label: '显示',
        icon: <Icon name="icon-yanjingxianshi" />
      });
    } else {
      menu.push({
        key: 'hid',
        label: '隐藏',
        icon: <Icon name="icon-yanjingyincangguanbi" />
      });
    }

    return (
      <Menu
        selectable
        items={menu}
        onClick={({ key }) => {
          if (key === 'rename') {
            setIsCurrentInput(index);
          }
          layerListEvent?.(null, key, item, 'GISLaryerMenu');
        }}
      />
    );
  };

  const initSort = () => {
    let sortable;
    // 拖动配置
    const ops = {
      animation: 200, // 动画延迟
      group: 'name-map',
      sort: true,
      scroll: true,
      className: 'zl-lagre-screen-filter-end-map',
      selectedClass: 'sortable-selected-map', // 选择的类名
      ghostClass: 'sortable-ghostClass-map', // 选择的类名
      forceFallback: true,
      fallbackTolerance: 3,
      // selected: true,

      avoidImplicitDeselect: false, // true - if you don't want to deselect items on outside click
      onStart: function (evt) {
        dragRef.current = true;
      },
      onMove: function (evt) {},
      onEnd: function (evt) {
        dragRef.current = false;
      },
      // 更新
      onUpdate: function (/**Event*/ evt) {
        const { from, newIndex } = evt;
        const list = updateSort(from);
        layerListEvent?.(null, null, list, 'GISLaryerUpdate');
      }
    };
    //初始化
    sortable = Sortable.create(listRef?.current, ops);
    sortableRef.current = sortable;
  };

  // 更新排序
  const updateSort = (fromEle) => {
    const list = [];
    [...fromEle?.children]?.forEach((item) => {
      const layerId = item?.getAttribute('data-map-layer-layerId');
      if (layerId) {
        list.push(layerId);
      }
    });
    return list;
  };
  return (
    <div className="zl-lagre-screen-gis-list" ref={listRef}>
      {Array.isArray(GISChildren) &&
        GISChildren?.length > 0 &&
        GISChildren.map((item, index) => {
          return (
            <div data-map-layer-layerId={item?.key} key={item?.key}>
              <Dropdown
                key={index}
                trigger={['contextMenu']}
                overlay={() => zoomMenu(item, index)}
                overlayClassName="zl-lagre-screen-gis-list-menu-dropdown"
              >
                <p
                  className={item?.active ? 'active' : ''}
                  key={item?.key}
                  onClick={(e) => {
                    layerListEvent?.(e, item?.key, item, 'GISLaryerSelect');
                  }}
                  onContextMenu={(e) => {
                    layerListEvent?.(e, item?.key, item, 'GISLaryerSelect');
                  }}
                  onDoubleClick={(e) => {
                    layerListEvent?.(e, item?.key, item, 'GISLaryerSelect');
                    setIsCurrentInput(index);
                  }}
                >
                  <Icon name={item?.icon} />
                  {isCurrentInput !== index ? (
                    <>
                      <span>{item?.title}</span>
                      {item?.gisLayerStateIcon ? (
                        <Icon
                          name={item?.gisLayerStateIcon}
                          style={{ marginRight: 20 }}
                          click={() => {
                            layerListEvent?.(
                              null,
                              item?.gisLayerStateIcon,
                              item,
                              'GISLaryerStateIcon'
                            );
                          }}
                        />
                      ) : (
                        <></>
                      )}
                    </>
                  ) : (
                    <LargeScreenLayerInput
                      value={item?.title}
                      changeValue={(type, value) => {
                        if (type === 'blur') {
                          layerListEvent?.(type, item, value, 'GISLaryerInput');
                          setIsCurrentInput(-1);
                        }
                      }}
                    />
                  )}
                </p>
              </Dropdown>
            </div>
          );
        })}
    </div>
  );
}

export default LargeScreenGISList;

export interface IProps {
  GISChildren: IGISChildren[];
  layerListEvent: Function;
}
