import { Tree, message } from 'antd';
import React, { useEffect, useState, useRef } from 'react';
import * as d3 from 'd3';
import qs from 'qs';

import { HomeOutlined, FolderOutlined } from '@ant-design/icons';

import './index.less';

const DragTree = () => {
  const [gData, setGData] = useState([]);
  const [expandedKeys, setExpandedKeys] = useState([]);

  useEffect(() => {
    d3.json('/api/bs/hrmorganization/orgchart/getMovingTree').then((data) => {
      setGData(data.movingTree);
      setExpandedKeys(data.expandedKeys);
    });
  }, [true]);

  const onDragEnter = (info) => {
    //console.log(info);
    // expandedKeys 需要受控时设置
    // setExpandedKeys(info.expandedKeys)
  };

  const onDrop = (info) => {
    debugger;
    //弹框操作
    const dropKey = info.node.key;
    const dragKey = info.dragNode.key;
    const dropPos = info.node.pos.split('-');
    const dropPosition =
      info.dropPosition - Number(dropPos[dropPos.length - 1]);
    const loop = (data, key, callback) => {
      for (let i = 0; i < data.length; i++) {
        if (data[i].key === key) {
          return callback(data[i], i, data);
        }
        if (data[i].children) {
          loop(data[i].children, key, callback);
        }
      }
    };
    const data = [...gData];

    // Find dragObject
    let dragObj;
    loop(data, dragKey, (item, index, arr) => {
      arr.splice(index, 1);
      dragObj = item;
    });
    if (!info.dropToGap) {
      // Drop on the content
      loop(data, dropKey, (item) => {
        item.children = item.children || [];
        // where to insert 示例添加到头部，可以是随意位置
        item.children.unshift(dragObj);
      });
    } else if (
      (info.node.props.children || []).length > 0 &&
      // Has children
      info.node.props.expanded &&
      // Is expanded
      dropPosition === 1 // On the bottom gap
    ) {
      loop(data, dropKey, (item) => {
        item.children = item.children || [];
        // where to insert 示例添加到头部，可以是随意位置
        item.children.unshift(dragObj);
        // in previous version, we use item.children.push(dragObj) to insert the
        // item to the tail of the children
      });
    } else {
      let ar = [];
      let i;
      loop(data, dropKey, (_item, index, arr) => {
        ar = arr;
        i = index;
      });
      if (dropPosition === -1) {
        ar.splice(i, 0, dragObj);
      } else {
        ar.splice(i + 1, 0, dragObj);
      }
    }
    setGData(data);
  };

  const onDelete = (nodeData) => {
    const extend = nodeData.type == '1' ? 'comp' : 'dept';
    d3.json(`/api/bs/hrmorganization/${extend}/deleteByIds`)
      .header('Content-Type', 'application/json')
      .post(JSON.stringify({ ids: nodeData.id }))
      .then(function (response) {
        message.success('删除成功');
      })
      .catch(function (error) {
        message.error('接口异常,请联系管理员');
      });
  };

  const onTitleRender = (nodeData) => {
    let extend = nodeData.type == '1' ? 'companyExtend' : 'departmentExtend';
    let attr = nodeData.type == '1' ? 'none' : 'inline-block';
    let icon = nodeData.type == '1' ? <HomeOutlined /> : <FolderOutlined />;
    return (
      <div>
        <span>
          {icon}
          <span style={{ marginLeft: '5px' }}>{nodeData.title}</span>
        </span>
        <div id="drag-button-ops">
          <span
            className="drag-button"
            onClick={() =>
              window.open(
                `/spa/organization/static/index.html#/main/organization/${extend}/${nodeData.id}`,
                '_blank',
              )
            }
          >
            查看
          </span>
          <span className="drag-button" onClick={onDelete(nodeData)}>
            删除
          </span>
          <span className="drag-button" onClick={onDelete(nodeData)}>
            封存
          </span>
          <span style={{ display: attr }} className="drag-button">
            合并
          </span>
          <span style={{ display: attr }} className="drag-button">
            复制
          </span>
        </div>
      </div>
    );
  };

  return (
    <Tree
      className="draggable-tree"
      defaultExpandedKeys={expandedKeys}
      draggable
      icon={false}
      blockNode
      onDragEnter={onDragEnter}
      onDrop={onDrop}
      treeData={gData}
      titleRender={onTitleRender}
    />
  );
};
export default DragTree;
