import React, { useRef, useState, useEffect } from 'react';

import Icon from '../Icon/index';
import Page from '../Page/index';
import Sortable from 'sortablejs';

import { IMainBackgroundStyle } from '../../type/LargeScreenBoard';
import { Dropdown, Menu } from 'antd';
import './style.scss';

function LargeScreenPage(props: ILargeScreenPage) {
  const {
    pageList: pageList1 = [],
    pageMenu = [],
    pageEvent,
    mainBackgroundStyle,
    backgroundSize,
    pageListEvent
  } = props;

  const [pageList, setPageList] = useState<IPageList[]>(pageList1); //page页的数据
  const pageRef = useRef(null); // 列表容器ref
  const sortableRef = useRef(null); // sortable
  const dragRef = useRef(null); // 拖动开始

  useEffect(() => {
    if (pageList?.length > 0) {
      initSort();
    }
  }, []);

  useEffect(() => {
    // 图层列表变化，需要重新初始化
    if (pageList?.length) {
      sortableRef?.current?.destroy();
      initSort();
    }
  }, [pageList?.length]);
  
  useEffect(() => {
    // 按照index排序
    const list = [...pageList1]?.sort((a, b) => a?.index - b?.index);
    setPageList(list);
  }, [pageList1]);

    // 更新排序
    const updateSort = (fromEle) => {
      const list = [];
      [...fromEle?.children]?.forEach((item) => {
        const layerId = item?.getAttribute('data-layer-layerId');
        if (layerId) {
          list.push(layerId);
        }
      });
      return list;
    };

  // 初始化sortable
  const initSort = () => {
    let sortable;
    // 拖动配置
    const ops = {
      animation: 200, // 动画延迟
      group: 'name',
      className: 'zl-lagre-screen-filter-end',
      multiDrag: false, // 开启多选
      multiDragKey: 'ctrl', // 多选按键
      selectedClass: 'sortable-selected', // 选择的类名
      ghostClass: 'sortable-ghostClass', // 选择的类名
      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;
        pageListEvent(evt, 'dragStart');
      },
      onMove: function (evt) {
        pageListEvent?.(evt, 'dragMove');
      },
      onEnd: function (evt) {
        dragRef.current = false;
        pageListEvent?.(evt, 'dragEnd');
      },
      // 更新
      onUpdate: function (/**Event*/ evt) {
        const { from, newIndex } = evt;
        const list = updateSort(from);
        pageListEvent?.( list, 'sortElementList');
      }
    };
    //初始化
    if(pageRef?.current){
      sortable = Sortable.create(pageRef?.current, ops);
      sortableRef.current = sortable;
    }
  };

  //没有page页的时候菜单的点击事件
  const clickMenu = ({ key }) => {
    pageEvent?.({ menuKey: key }, 'menuClick');
  };
  //渲染没有page页的菜单渲染
  const menu = () => {
    return <Menu items={pageMenu} onClick={clickMenu} />;
  };

  return (
    <div className="zl-large-screen-page">
      {pageList?.length === 0 ? (
        <Dropdown
          overlay={menu}
          trigger={pageList?.length === 0 ? ['contextMenu'] : ''}
          overlayClassName="zl-large-screen-page-item-drop-down"
        >
          <div className="zl-large-screen-pages">
            {pageList?.length > 0 &&
              pageList?.map((item, index) => {
                return (
                  <Page
                    key={item?.key + item?.index}
                    keys={item?.key}
                    {...item}
                    wh={mainBackgroundStyle?.backgroundData}
                    pageMenu={pageMenu}
                    pageEvent={pageEvent}
                    styleConfig={item.config}
                    backgroundSize={backgroundSize}
                  />
                );
              })}
          </div>
        </Dropdown>
      ) : (
        <div className="zl-large-screen-pages"  ref={pageRef}>
          {pageList?.length > 0 &&
            pageList?.map((item, index) => {
              return (
                <Page
                  key={item?.key + item?.index}
                  keys={item?.key}
                  {...item}
                  wh={mainBackgroundStyle?.backgroundData}
                  pageMenu={pageMenu}
                  pageEvent={pageEvent}
                  styleConfig={item?.config}
                  backgroundSize={backgroundSize}
                />
              );
            })}
        </div>
      )}

      <div className="zl-large-screen-btn">
        <span
          className="zl-large-screen-btn-add"
          onClick={() => pageEvent(null, 'aadBtn')}
        >
          <Icon name="icon-tianjia" classname="zl-large-screen-btn-add-icon" />
        </span>
      </div>
    </div>
  );
}
export default LargeScreenPage;

export interface ILargeScreenPage {
  pageList?: IPageList[];
  pageMenu?: IPageMenu[];
  pageEvent?: Function;
  mainBackgroundStyle?: IMainBackgroundStyle;
  backgroundSize?:IBackgroundSize,
  pageListEvent?: Function;
}

export interface IPageList {
  key: string;
  index: number;
  active?: boolean;
  config?: React.CSSProperties;
  componentList?: IComponentList[];
}

export interface IComponentList {
  key: number | string;
  layerIndex: string;
  elementIndex: number;
  type?: string;
  title?: string;
  icon?: string;
  selected?: boolean;
  ratio?: boolean;
  isShow?: boolean;
  isLock?: boolean;
  menuVisible?: boolean;
  boxMenuVisible?: boolean;
  elementInfo: IElement;
}
export interface IElement {
  width: number;
  height: number;
  x: number;
  y: number;
  chartType: string;
  element: React.ReactNode;
  keepRatio: boolean;
  key: number | string;
}

export interface IPageMenu {
  key: string;
  disabled?: boolean;
  label?: string;
}

export interface IBackgroundSize{
  width:number;
  height:number;
}
