import React, { forwardRef } from 'react';
import { Checkbox } from 'antd';
import { RightOutlined, DownOutlined, LoadingOutlined } from '@ant-design/icons';
import debounce from 'lodash/debounce';
import styles from './index.less';

const CustomTree = forwardRef(props => {
  const { treeData } = props;

  const onChange = () => {
    props.onChange(treeData.key, !treeData.checked, treeData.level, treeData.children);
  };

  const onVisible = debounce(e => {
    e.persist();
    if (treeData.isLoading) return;
    props.onVisibleChildren(
      treeData.key,
      !treeData.visibleChildren,
      treeData.children,
      treeData.checked,
    );
  }, 100);

  const renderIcon = () => {
    if (treeData.children && treeData.isLoading) {
      return <LoadingOutlined />;
    }
    if (treeData.isLeaf) {
      return (
        <div onClick={onVisible} className={styles.CBIcon}>
          {treeData.visibleChildren ? <DownOutlined /> : <RightOutlined />}
        </div>
      );
    }
    return <span />;
  };
  return (
    <div key={`key${treeData.key}`}>
      <div className={styles['ccheck-box']}>
        <div className={styles['ccheck-box--expand']}>{renderIcon()}</div>
        <Checkbox
          onChange={onChange}
          indeterminate={!treeData.checked && treeData.indeterminate}
          checked={treeData.checked}
        />
        <div className={styles['ccheck-box--label']} onClick={onVisible}>
          {props.label}
          {treeData.isLeaf && treeData.value && treeData.value.length > 0
            ? `(${treeData.value.length})`
            : ''}
        </div>
      </div>
    </div>
  );
});

export default CustomTree;
