/*
 * @Author: Chengliang 1546584672@qq.com
 * @Date: 2022-08-04 10:22:55
 * @LastEditors: Chengliang 1546584672@qq.com
 * @LastEditTime: 2022-11-01 15:01:23
 * @FilePath: /org-chart-frant/src/components/orgChart/index.jsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React, { useLayoutEffect, useRef, useEffect, memo } from 'react';
import { OrgChart } from '../../d3-org-chart.js';
import * as d3 from 'd3';
import { message } from 'antd';
import moment from 'moment';

export const OrgChartComponent = memo((props, ref) => {
  const d3Container = useRef(null);
  const chartBackup = useRef(null);
  let chart = null;
  const { data = [{}] } = props;
  const {
    requestRes = {
      date: moment(new Date()).format('YYYY-MM-DD'),
      fclass: '0',
      root: '0',
      level: '3',
      fisvitual: '0',
    },
  } = props;
  const { level = '3' } = requestRes;
  function addNode(node) {
    chart.addNode(node);
  }

  props.setClick(addNode);

  // We need to manipulate DOM
  useLayoutEffect(() => {
    if (d3Container.current) {
      if (!chart) {
        chart = new OrgChart({ expandLevel: +level == 1 ? 0 : +level });
        window.chart = chart;
      }
      props.setChart(chart);
      try {
        let buttonClick = chart.onButtonClick;

        chart
          .container(d3Container.current)
          .data(data)
          .nodeWidth(props.nodeWidth)
          .nodeHeight(props.nodeHeight)
          .layout('top')
          .linkUpdate(function (d, i, arr) {
            d3.select(this)
              .attr('stroke', '#66BAF5')
              .attr('stroke-width', 1)
              .style('stroke-dasharray', '3, 3');
          })
          .onNodeClick((d, i, arr) => {
            props.onNodeClick(d);
          })

          .buttonContent(props.buttonContent)
          .nodeContent(props.nodeContent)
          .render();
        chart
          .setCentered(chart.getChartState().root.id)
          .expandExpandNodes()
          .render();
        chartBackup.current = chart;
        chart.onButtonClick = (event, d) => {
          buttonClick.bind(chartBackup.current)(event, d);
          props.onButtonClick && props.onButtonClick(event, d);
        };
      } catch (err) {
        message.warning(err);
      }
    }
  }, [data]);

  return (
    <div>
      <div ref={d3Container} />
    </div>
  );
});
