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

interface NodeData {
  title: string;
  key: string | number;
  folderId?: string | number;
  selectable?: boolean;
  children?: NodeData[];
}

interface Props {
  scenes: NodeData[];
  sceneId: string;
  scenesEvent?: (event: string, nodeData: NodeData, value?: string) => void;
  sceneSelectId: string[];
  sceneExpandIds: string[];
}

const LargeScreenSceneTree = (props: Props) => {
  const { scenes, sceneId, scenesEvent, sceneSelectId, sceneExpandIds } = props;
  const [expandedKeys, setExpandedKeys] = useState<(string| number)[]>(sceneExpandIds);
  const [selectedKeys, setSelectedKeys] = useState<string[]>(sceneSelectId);
  const [inputValue, setInputValue] = useState<string>(''); //Input的value
  const [inputId, setInputId] = useState<(string| number)>(''); //Input的id

  const inputRef = useRef<any>(null);

  useEffect(() => {
    scenes?.forEach((scene) => {
      if (scene?.children?.length > 0) {
        scene?.children?.forEach((item) => {
          item.folderId = scene?.key;
        });
      }
    });
  }, [scenes]);

  useEffect(() => {
    setSelectedKeys(sceneSelectId);
  }, [sceneSelectId]);

  useEffect(() => {
    setExpandedKeys(sceneExpandIds);
  }, [sceneExpandIds]);

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

  // 切换页面
  const changePage = (nodeData: NodeData) => {
    if (nodeData?.key !== selectedKeys?.[0]) {
      scenesEvent?.('changePage', nodeData);
    }
  };

  // 新增页
  const handleButtonClick = (
    event: React.MouseEvent<HTMLParagraphElement, MouseEvent>,
    nodeData: NodeData
  ) => {
    // 阻止事件冒泡
    event.stopPropagation();
    scenesEvent?.('addPage', nodeData);
  };

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

  // 重命名
  const rename = (value: string, nodeData: NodeData) => {
    if (nodeData?.folderId) {
      scenesEvent?.('renamePage', nodeData, value);
    } else {
      scenesEvent?.('renameScene', nodeData, value);
    }
    setInputId('');
    setInputValue('');
  };

  // 标题渲染
  const handleTitleRender = (nodeData: NodeData) => {
    if (nodeData.children) {
      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-parent"
            onClick={() =>
              expandedKeys.includes(nodeData.key)
                ? setExpandedKeys(
                    expandedKeys.filter((key) => key !== nodeData.key)
                  )
                : setExpandedKeys([...expandedKeys, nodeData.key])
            }
          >
            <p className="zl-lagre-screen-scene-tree-parent-name">
              {expandedKeys.includes(nodeData.key) ? (
                <DownOutlined />
              ) : (
                <RightOutlined />
              )}
              {inputId === nodeData?.key ? (
                <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.title}
                  style={{
                    color: sceneId === nodeData?.key ? '#526cfd' : '#aab3bc'
                  }}
                >
                  {nodeData.title}
                </span>
              )}
            </p>
            <p
              className="zl-lagre-screen-scene-tree-parent-add"
              onClick={(event) => handleButtonClick(event, nodeData)}
            >
              <Icon name={'icon-tianjia1'} />
            </p>
          </div>
        </Dropdown>
      );
    } else {
      return (
        <Dropdown
        overlay={() => content(nodeData)}
          trigger="contextMenu"
          placement="rightTop"
          overlayClassName="zl-lagre-screen-scene-tree-popover zl-lagre-screen-scene-model-popover zl-large-screen-dropmenu"
        >
          <div
            className="zl-lagre-screen-scene-tree-children"
            onClick={() => changePage(nodeData)}
          >
            {inputId === nodeData?.key ? (
              <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?.title}>{nodeData?.title}</span>
            )}
          </div>
        </Dropdown>
      );
    }
    return nodeData.title;
  };

  // 删除页
  const delClick = (
    event: React.MouseEvent<HTMLParagraphElement, MouseEvent>,
    nodeData: NodeData
  ) => {
    // // 阻止事件冒泡
    // event.stopPropagation();
    if (nodeData?.folderId) {
      scenesEvent?.('delPage', nodeData);
    } else {
      scenesEvent?.('delScene', nodeData);
    }
  };

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

  // 复制页
  const copyClick = (
    event: React.MouseEvent<HTMLParagraphElement, MouseEvent>,
    nodeData: NodeData
  ) => {
    // // 阻止事件冒泡
    // event.stopPropagation();
    if (nodeData?.folderId) {
      scenesEvent?.('copyPage', nodeData);
    } else {
      scenesEvent?.('copyScene', nodeData);
    }
  };

  // 右键菜单
  const content = (nodeData: NodeData) => {
    const menus = [
      {
        key: '1',
        label: (
          <div key="rename" onClick={(e) => renameClick?.(e, nodeData)}>
          重命名
        </div>
        ),
      },
      {
        key: '2',
        label: (
          <div key="copy" onClick={(e) => copyClick?.(e, nodeData)}>
          复制
        </div>
        )
      },
      {
        key: '3',
        label: (
          <div key="del" onClick={(e) => delClick?.(e, nodeData)}>
          删除
        </div>
        )
      }
    ];
    return <Menu items={menus} />;
  };

  return (
    <div style={{ height: 'calc(100% - 34px)', overflow: 'hidden' }}>
      <Tree
        defaultExpandAll
        expandedKeys={expandedKeys}
        treeData={scenes}
        titleRender={handleTitleRender}
        selectedKeys={selectedKeys}
        onSelect={(keys) => changeSelect(keys)}
        switcherIcon={<DownOutlined />}
      />
    </div>
  );
};

export default LargeScreenSceneTree;
