// app.js
import React, {useState, useEffect, useCallback} from 'react'
import Box from '@/components/floatbox';
import {Tree, Card, Icon} from '@ttk/component';
import "../style.less";
const {Fragment} = React

let x = 3;
const y = 2;
const z = 2;
let gData = [];

const generateData = (_level, _preKey, _tns) => {
  const preKey = _preKey || '0';
  const tns = _tns || gData;

  const children = [];
  for (let i = 0; i < x; i++) {
    const key = `${preKey}-${i}`;
    tns.push({ title: key, key });
    if (i < y) {
      children.push(key);
    }
  }
  if (_level < 0) {
    return tns;
  }
  const level = _level - 1;
  children.forEach((key, index) => {
    tns[index].children = [];
    return generateData(level, key, tns[index].children);
  });
};
generateData(z);

export default React.memo(Page)
function Page(props) {

  const [treeData, setTreeData] = useState(gData)
  const [expandedKeys, setExpandedKeys] = useState(['0-0-0']); // 展开节点
  const [autoExpandParent, setAutoExpandParent] = useState(true);

  useEffect(() => {
    let data = loopTree(treeData)
    setTreeData(data)
  }, [])

  const onExpand = expandedKeys => {
    setExpandedKeys(expandedKeys);
    setAutoExpandParent(false);
  };

  const loopTree = (data) => {
    if (data && data.length) {
      data = data.map((item) => {
        let title = item.key
        item.title = <div className="tree-item-wrap">
          <span>{title}</span>
          <span className="tree-item-btn">
            <Icon type="plus-square" title="添加子节点"/>
            <Icon type="edit" title="编辑节点"/>
            <Icon type="delete" title="删除节点"/>
          </span>
        </div>
        if (item.children) {
          item.children = loopTree(item.children)
        }
        return item
      })
    }
    return data
  }

  return (
    <Fragment>
      <Card
        title="编辑"
        style={{height: "100%"}}
        className="ttk-card-form"
      >
        <Tree
          className="draggable-tree"
          onExpand={onExpand}
          expandedKeys={expandedKeys}
          autoExpandParent={autoExpandParent}
          blockNode
          treeData={treeData}
        />
      </Card>
    
    </Fragment>
  )
}