/*
 * @Author: your name
 * @Date: 2022-04-11 15:26:48
 * @Description: 图层列表
 * @FilePath: /zl-large-screen/src/components/LargeScreenLayer/index.tsx
 */

import React, { useState, useEffect, useRef } from 'react';
import Icon from '../../Icon/index';
import { DownOutlined, RightOutlined } from '@ant-design/icons';
import { Tree, Dropdown, Input, Menu } from 'antd';
import '../../LargeScreenScene/style.scss';

interface NodeData {
  name?: string;
  description?: string;
  type?: string | number;
  key?: string | number;
  reportComponentId?: string | number;
  data?: NodeData[];
  visible?: boolean;
  selected?: boolean;
}

interface Props {
  content: NodeData[];
  contextMenus: IContextMenus[];
  layerListEvent?: Function;
  sceneSelectId?: string[];
  layerExpandIds?: string[];
}

interface IContextMenus {
  label?: string | React.ReactNode;
  key?: string | number;
  icon?: string;
  type?: string;
  disabled?: string[] | string;
  hidden?: string[] | string;
  children?: IContextMenus[];
  visible?: boolean;
}

const LargeScreen3DList = (props: Props) => {
  const { content: scenes, contextMenus, layerListEvent, layerExpandIds } = props;
  const [expandedKeys, setExpandedKeys] = useState<(string | number)[]>([]);
  const [layers, setLayers] = useState<NodeData[]>([]);
  const [inputValue, setInputValue] = useState(''); //Input的value
  const [inputId, setInputId] = useState<string | number>(''); //Input的id

  const inputRef = useRef<any>(null);

  useEffect(() => {
    const layer = [];
    scenes?.forEach((scene) => {
      if (scene?.key !== 'cityModel') {
        layer.push({
          ...scene,
          data: scene?.data?.map((item) => {
            item?.key === item?.reportComponentId;
            return item;
          })
        });
      }
    });
    setLayers(layer);
  }, [scenes]);

  useEffect(() => {
    inputRef?.current?.focus({
      cursor: 'end'
    });
  }, [inputId]);
  
  useEffect(() => {
    setExpandedKeys(layerExpandIds);
  }, [layerExpandIds]);

  // 切换文件夹
  const clickFolder = (nodeData: NodeData) => {
    // 打开文件夹
    // 传递事件
    layerListEvent?.(null, nodeData?.key, nodeData, 'click3DFolder');
  };

  // 切换3D元件
  const change3DComponent = (key, nodeData: NodeData) => {
    // if (nodeData?.key !== selectedKeys?.[0]) {
      // 传递事件
      layerListEvent?.(null, key, nodeData, 'change3DComponent');
    // }
  };

  // // 点击切换页
  // const changeSelect = (keys: string[]) => {
  //   keys?.[0] && setSelectedKeys(keys);
  // };

  // 标题渲染
  const handleTitleRender = (nodeData: NodeData) => {
    // 如果是场景，不显示树形结构
    if (nodeData?.data) {
      return (
        // <Popover
        //   content={() => content(nodeData)}
        //   trigger="contextMenu"
        //   placement="rightTop"
        //   overlayClassName="zl-lagre-screen-scene-tree-popover"
        // >
        <div
          className="zl-lagre-screen-scene-tree-parent"
          onClick={() => {
            expandedKeys.includes(nodeData.key)
              ? setExpandedKeys(
                  expandedKeys.filter((key) => key !== nodeData.key)
                )
              : setExpandedKeys([...expandedKeys, nodeData.key]);
            clickFolder(nodeData);
          }}
        >
          <p className="zl-lagre-screen-scene-tree-parent-name">
            {expandedKeys.includes(nodeData.key) ? (
              <DownOutlined />
            ) : (
              <RightOutlined />
            )}
              <span
                title={nodeData.name}
              >
                {nodeData.name}
              </span>
          </p>
        </div>
        // </Popover>
      );
    } else if (nodeData?.type !== 'cityModel') {
      return (
        <Dropdown
        overlay={() => content(nodeData)}
          trigger="contextMenu"
          placement="rightTop"
          overlayClassName="zl-lagre-screen-scene-tree-popover zl-lagre-screen-scene-model-popover"
        >
          <div
            className="zl-lagre-screen-scene-tree-children"
            onClick={() => change3DComponent(nodeData?.name, nodeData)}
            onDoubleClick={(e) => {
              change3DComponent(nodeData?.name, nodeData)
              renameClick?.(e, nodeData)}
            }
            style={{backgroundColor: nodeData?.selected ? '#3d4657' : ''}}
          >
            {inputId === (nodeData?.key || nodeData?.reportComponentId) ? (
              <Input
                value={inputValue}
                ref={inputRef}
                maxLength={20}
                onChange={(e) => setInputValue(e.target.value)}
                onBlur={(e) => rename(e.target.value, nodeData)}
                onPressEnter={() => {
                  inputRef?.current?.blur();
                }}
              />
            ) : (
              <>
                <span title={nodeData?.name}>
                  {nodeData?.name}
                </span>
                {!nodeData?.visible ? (
                  <span className="zl-lagre-screen-scene-tree-children-hidden-icon" onClick={(e) => hidden3DLayer?.(e, nodeData)}>
                    <Icon name={'icon-yanjingyincangguanbi'} />
                  </span>
                ) : (
                  <></>
                )}
              </>
            )}
          </div>
        </Dropdown>
      );
    }
  };

  // 删除图层
  const delClick = (
    event: React.MouseEvent<HTMLParagraphElement, MouseEvent>,
    nodeData: NodeData
  ) => {
    // // 阻止事件冒泡
    // event.stopPropagation();
    layerListEvent?.(null, nodeData, null, 'delete3DLayer');
  };

  // 右键菜单
  const content = (nodeData: NodeData) => {
    const menus = [
      {
        key: '1',
        label: (
          <div key="rename" onClick={(e) => renameClick?.(e, nodeData)}>
          重命名
        </div>
        ),
      },
      {
        key: '2',
        label: (
          nodeData?.visible ? (
            <div key="hidden" onClick={(e) => hidden3DLayer?.(e, nodeData)}>
              隐藏
            </div>
          ) : (
            <div key="display" onClick={(e) => hidden3DLayer?.(e, nodeData)}>
              取消隐藏
            </div>
          )
        )
      },
      {
        key: '3',
        label: (
          <div key="del" onClick={(e) => delClick?.(e, nodeData)}>
          删除
        </div>
        )
      }
    ];
    return <Menu items={menus} />;
  };

  // 重命名
  const rename = (value: string, nodeData: NodeData) => {
    layerListEvent?.(null, nodeData, value, 'rename3DLayer');
    setInputId('');
    setInputValue('');
  };

  // 隐藏和显示
  const hidden3DLayer = (
    event: React.MouseEvent<any, MouseEvent>,
    nodeData: NodeData
  ) => {
    // // 阻止事件冒泡
    // event && event.stopPropagation();
    layerListEvent?.(null, nodeData?.reportComponentId, nodeData, 'hidden3DLayer');
  };

  // 重命名
  const renameClick = (
    event: React.MouseEvent<HTMLParagraphElement, MouseEvent>,
    nodeData: NodeData
  ) => {
    // // 阻止事件冒泡
    // event.stopPropagation();
    setInputValue(nodeData?.name);
    setInputId(nodeData?.reportComponentId);
    layerListEvent?.(null, null, nodeData, 'rename3DLayerBegin');
  };

  return (
    <div
      className="zl-lagre-screen-scene"
      style={{ height: 'calc(100% - 50px)', overflow: 'hidden' }}
    >
      {scenes?.[0]?.data?.length > 0 ? (
        <div
          className="zl-lagre-screen-3D-scene"
          onClick={() => {
            layerListEvent?.(
              null,
              scenes?.[0]?.data?.[0]?.name,
              scenes?.[0]?.data,
              'selectedScene'
            );
          }}
        >
          <span>场景</span>
          <p>
            <span title={scenes?.[0]?.data?.[0]?.description}>
              {scenes?.[0]?.data?.[0]?.description}
            </span>
            <span className="zl-lagre-screen-layer-tree-parent-name-use">
              使用
            </span>
          </p>
        </div>
      ) : (
        <div
          className="zl-lagre-screen-3D-scene"
          onClick={() => {
            clickFolder(scenes?.[0]?.data?.[0]);
          }}
        >
          <span>场景</span>
          <p>无</p>
        </div>
      )}
      <div className="zl-lagre-screen-scene-tree zl-lagre-screen-scene-tree-3d">
        <Tree
          fieldNames={{ key: 'key', title: 'name', children: 'data' }}
          expandedKeys={expandedKeys}
          treeData={layers}
          titleRender={handleTitleRender}
          selectable={false}
          switcherIcon={<DownOutlined />}
        />
      </div>
    </div>
  );
};

export default LargeScreen3DList;
