import { createFromIconfontCN } from '@ant-design/icons';
import { Input, Tooltip, TreeProps, Empty } from 'antd';
import { Key, useEffect, useState } from 'react';
import DirectoryTree from 'antd/es/tree/DirectoryTree';
import { DataNode } from 'antd/es/tree';

import './style.less';

const IconFont = createFromIconfontCN({
  scriptUrl: '',
});

interface ListItem {
  name: string;
  subText: string;
  [key: string]: any;
}

interface TreeNodeItem {
  [key: string]: any;
}

export interface KCIMLeftListProps {
  dataSource: any[];
  searchKey: string;
  placeholder?: string;
  listType?: 'list' | 'tree';
  icon?: string;
  contentH?: number | string;
  rowKey?: string;
  fieldNames?: { title?: string; key?: string; children?: string };
  defaultSelectType?: 'leaf' | 'node'; // 新增属性
  onChange?: (selectedItem: ListItem) => void;
}

function searchTreeAndKeepHierarchy(
  tree: any[],
  keyword: string,
  searchKey: string,
  children: string,
) {
  function search(node: any) {
    let newNode = { ...node };
    if (node[`${searchKey}`].includes(keyword)) {
      return newNode;
    } else if (node[`${children}`] && node[`${children}`].length > 0) {
      let filteredChildren = node[`${children}`]
        .map(search)
        .filter((child: any) => child !== null);
      if (filteredChildren.length > 0) {
        newNode[`${children}`] = filteredChildren;
        return newNode;
      }
    }
    return null;
  }
  return tree.map(search).filter((node) => node !== null);
}

const findFirstLeafNodeWithParents: any = (node: any, children: string) => {
  const findNode: any = (currentNode: any, parents: any[]) => {
    if (!currentNode[children] || currentNode[children].length === 0) {
      return { leafNode: currentNode, parents };
    }
    parents.push(currentNode);
    return findNode(currentNode[children][0], parents);
  };
  return findNode(node, []);
};

let searchKeyword:string|undefined = undefined;

export const KCIMLeftList = (props: KCIMLeftListProps) => {
  const {
    searchKey,
    placeholder = '请输入',
    onChange,
    listType = 'list',
    dataSource: data = [],
    icon,
    contentH = 500,
    rowKey = 'id',
    fieldNames = { title: 'title', key: 'key', children: 'children' },
    defaultSelectType = 'leaf', // 新增属性，默认选中叶子节点
  } = props;

  const [dataSource, set_dataSource] = useState<ListItem[] | TreeNodeItem[]>([]);
  const [showList, set_showList] = useState<ListItem[] | TreeNodeItem[]>([]);
  const [currentSelected, set_currentSelected] = useState<undefined | any>(
    undefined,
  );
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  const [defaultSelectedKeys, set_defaultSelectedKeys] = useState<Key[]>([]);
 

  const onSelect: TreeProps['onSelect'] = (selectedKeys, info) => {
    const { node } = info;
    if (
      !node[fieldNames.children as keyof typeof node] ||
      (node[fieldNames.children as keyof typeof node] as any[]).length === 0
    ) {
      set_currentSelected(node);
    }
  };

  const onExpand = (newExpandedKeys: React.Key[]) => {
    setExpandedKeys(newExpandedKeys);
    setAutoExpandParent(false);
  };

  const getFirstNodeOrLeaf = (node: any) => {
    if (defaultSelectType === 'leaf') {
      const result = findFirstLeafNodeWithParents(
        node,
        fieldNames.children ? fieldNames.children : 'children',
      );
      return {
        node: result.leafNode,
        expandedKeys: result.parents.map(
          (parent: any) => parent[fieldNames.key as string],
        ),
      };
    }
    return {  
      node: node,
      expandedKeys: [node[`${fieldNames.key}`]],
    };
  };

  useEffect(() => {
    onChange && onChange({...currentSelected,searchKeyword});
  }, [currentSelected]);

  useEffect(() => {
    if (showList.length > 0) {
      if (listType === 'list') {
        set_currentSelected(showList[0]);
      } else if (listType === 'tree') {
        const { node, expandedKeys } = getFirstNodeOrLeaf(showList[0]);
        setExpandedKeys([...expandedKeys]);
        set_currentSelected(node);
        set_defaultSelectedKeys([node[fieldNames.key!]]);
      }
    } else {
      set_currentSelected(undefined);
    }
  }, [showList]);

  useEffect(() => {
    set_dataSource([...data]);
    set_showList([...data]);
  }, [data]);

  return (
    <div className="KCIMLeftList">
      <div className="toolbar">
        <Input
          placeholder={placeholder}
          allowClear
          autoComplete="off"
          suffix={<IconFont style={{ color: '#99A6BF' }} type="iconsousuo" />}
          onChange={(e) => {
            searchKeyword = e.target.value;
            if (listType === 'list') {
              const result = dataSource.filter((item) =>
                item[`${searchKey}`].includes(e.target.value),
              );
              set_showList(result);
            }
            if (listType === 'tree') {
              const result = searchTreeAndKeepHierarchy(
                dataSource,
                e.target.value,
                searchKey,
                fieldNames.children ? fieldNames.children : 'children',
              );
              set_showList(result);
            }
          }}
        />
      </div>
      <div className="wrap" style={{ height: contentH, overflowY: 'scroll' }}>
        {listType === 'list' &&
          showList.map((item, index) => (
            <div
              className={
                currentSelected
                  ? currentSelected[`${rowKey}`] === item[`${rowKey}`]
                    ? 'list on'
                    : 'list'
                  : 'list'
              }
              key={index}
              onClick={() => {
                set_currentSelected(item);
              }}
            >
              <img
                className="icon"
                src={icon ? icon : require('../../../static/departmentIcon.png')}
                alt=""
              />
              <div className="content">
                <Tooltip title={item.subText}>
                  <div className="name">{item.name}</div>
                  <div className="sub">{item.subText}</div>
                </Tooltip>
              </div>
            </div>
          ))}

        {(!showList || showList.length === 0) && (
          <div>
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
          </div>
        )}

        {listType === 'tree' &&
          dataSource.length > 0 &&
          currentSelected &&
          defaultSelectedKeys.length > 0 && (
            <DirectoryTree
              className="KC-DirectoryTree"
              fieldNames={fieldNames}
              rootStyle={{
                height: '100%',
                paddingBottom: 50,
                overflowY: 'scroll',
                overflowX: 'hidden',
              }}
              onSelect={onSelect}
              onExpand={onExpand}
              expandedKeys={expandedKeys}
              autoExpandParent={autoExpandParent}
              selectedKeys={[currentSelected[`${fieldNames.key}`]]}
              blockNode={true}
              expandAction={false} 
              showIcon={false}
              treeData={showList as unknown as DataNode[]}
              switcherIcon={(props: any) => {
                const { expanded } = props;
                return (
                  <IconFont
                    style={{ fontSize: 16, position: 'relative', top: 2 }}
                    type={expanded ? 'icon-shouqi1' : 'icon-zhankai1'}
                  />
                );
              }}
            />
          )}
      </div>
    </div>
  );
};
