/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2022-07-06 09:31:32
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-08-10 15:21:18
 * @FilePath: /KC-MiddlePlatform/src/pages/platform/components/TreeEditer/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import React, { Key, useEffect, useState } from 'react';
import { Tree, Radio, Divider } from 'antd';
import type { DataNode } from 'antd/lib/tree';
import { getMenuDirectory, MenuItemDataType } from '@/service/menu';
import { TagsOutlined } from '@ant-design/icons';

const { TreeNode } = Tree;

const getTreeNode = (data: MenuItemDataType[]) => {
  if (data && data.length > 0) {
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode key={item.menuId} title={item.name}>
            {getTreeNode(item.children)}
          </TreeNode>
        );
      }
      return (
        <TreeNode
          key={item.menuId}
          title={item.name}
          switcherIcon={<TagsOutlined />} // TreeNode这个Tree的子组件居然存在SwitcherIcon属性.
        />
      );
    });
  }
  return [];
};

export type TreeEditerValueType = { actType: 'COPY' | 'MOVE'; selectedKeysValue: Key[] };

export interface TreeEditerPropsType {
  onChange?: (data: TreeEditerValueType) => void;
}

function TreeEditer(props: TreeEditerPropsType) {
  const { onChange } = props;

  const [treeData, set_treeData] = useState<MenuItemDataType[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [actType, set_actType] = useState<'COPY' | 'MOVE'>('COPY');

  // const onExpand = (expandedKeysValue: React.Key[]) => {
  //     console.log('onExpand', expandedKeysValue);
  //     // if not set autoExpandParent to false, if children expanded, parent can not collapse.
  //     // or, you can remove all expanded children keys.
  //     setExpandedKeys(expandedKeysValue);
  //     setAutoExpandParent(false);
  // };

  // const onCheck = (checkedKeysValue:any) => {
  //     console.log('onCheck', checkedKeysValue);
  //     setCheckedKeys(checkedKeysValue);
  // };

  const onSelect = (selectedKeysValue: React.Key[], info: any) => {
    setSelectedKeys(selectedKeysValue);
    onChange && onChange({ actType, selectedKeysValue });
  };

  const radioOnchange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.value == 'COPY') set_actType('COPY');
    if (e.target.value == 'MOVE') set_actType('MOVE');
  };

  const getTreeData = async () => {
    let expandedKeys: (number | string)[] = [];

    const convertData = (data: Array<any>) => {
      data.forEach((item) => {
        item.title = item.name;
        item.key = item.menuId;
        if (!item.children || item.children.length == 0) {
          expandedKeys.push(item.menuId);
        }
        if (item.children) {
          convertData(item.children);
        }
      });
    };

    const resp = await getMenuDirectory();

    if (resp) {
      let data = resp.list;
      convertData(data);
      setExpandedKeys(Array.from(new Set(expandedKeys)));
      set_treeData(data);
      console.log({ resp });
    }
  };

  useEffect(() => {
    getTreeData();
  }, []);

  return (
    <div>
      <Radio.Group defaultValue={actType} buttonStyle="solid" onChange={(e) => radioOnchange(e as unknown as React.ChangeEvent<HTMLInputElement>)}>
        <Radio.Button value="COPY">复制</Radio.Button>
        <Radio.Button value="MOVE">移动</Radio.Button>
      </Radio.Group>

      <Divider plain>请选择</Divider>

      {expandedKeys.length > 0 && treeData.length > 0 && (
        <Tree
          // checkable
          showLine
          blockNode
          autoExpandParent={true}
          // onCheck={onCheck}
          defaultExpandAll
          // onExpand={onExpand}
          expandedKeys={expandedKeys}
          // autoExpandParent={autoExpandParent}
          // // onCheck={onCheck}
          // checkedKeys={checkedKeys}
          onSelect={onSelect}
          // selectedKeys={selectedKeys}
          treeData={treeData as any}
        >
          {/* {getTreeNode(treeData)} */}
        </Tree>
      )}
    </div>
  );
}

export default TreeEditer;
