import { Tree, message, Modal, Popconfirm, Spin } from 'antd';
import React, { useEffect, useState, useRef } from 'react';
import * as d3 from 'd3';
import qs from 'qs';
import MergeDialog from '../components/dialog/mergeDialog';
import CopyDialog from '../components/dialog/copyDialog';

import {
  HomeOutlined,
  FolderOutlined,
  ClusterOutlined,
  ApartmentOutlined,
} from '@ant-design/icons';
import './index.less';

const DragTree = () => {
  const [gData, setGData] = useState([]);
  const [expandedKeys, setExpandedKeys] = useState([undefined]);
  const childRef = useRef(null);
  const [tip, setTip] = useState('正在加载...');
  const [loading, setLoading] = useState(false);
  const [showCanceled, setShowCanceled] = useState(0);

  const [open, setOpen] = useState(false);
  const [mergeId, setMergeId] = useState(null);
  const [copyopen, setCopyOpen] = useState(false);
  const [copyId, setCopyId] = useState(null);

  useEffect(() => {
    getMoveTree(0);
  }, [true]);

  const getMoveTree = (showCanceled) => {
    setLoading(true);
    d3.json(
      `/api/bs/hrmorganization/orgchart/getMovingTree?showCanceled=${showCanceled}`,
    ).then((data) => {
      setGData(data.movingTree);
      setExpandedKeys(data.expandedKeys);
      setLoading(false);
    });
  };

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

  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 onDrop = (info) => {
    setLoading(true);
    setTip('正在转移，请稍候...');
    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]);
    fetch('/api/bs/hrmorganization/dept/dragDepartment', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        sourcekey: dragKey,
        targetkey: dropKey,
        dropPosition: dropPosition,
      }),
    })
      .then((response) => response.json())
      .then((res) => {
        if (res.code == 200) {
          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);
        } else {
          message.warning(res.msg, 2);
        }
        setLoading(false);
      })
      .catch((error) => {
        message.error('接口异常,请联系管理员');
      });

    setTimeout(function () {}, 1000);
  };

  /**
   * 删除
   * @param {*} nodeData
   */
  const onDelete = (nodeData) => {
    const extend = nodeData.type == '1' ? 'comp' : 'dept';
    fetch(`/api/bs/hrmorganization/${extend}/deleteByIds`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ ids: nodeData.id }),
    })
      .then((response) => response.json())
      .then((res) => {
        if (res.code == 200) {
          if (res.data.status == '1') {
            const data = [...gData];
            loop(data, nodeData.key, (item, index, arr) => {
              arr.splice(index, 1);
            });
            setGData(data);
            message.success('删除成功', 2);
          } else {
            message.warning(res.data.message, 2);
          }
        }
      })
      .catch((error) => {
        message.error('接口异常,请联系管理员');
      });
  };

  /**
   * 封存
   * @param {*} nodeData
   */
  const onCancel = (nodeData) => {
    const extend = nodeData.type == '1' ? 'comp' : 'dept';
    fetch(`/api/bs/hrmorganization/${extend}/updateForbiddenTagById`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        id: nodeData.id,
        canceled: nodeData.canceled != '0',
      }),
    })
      .then((response) => response.json())
      .then((res) => {
        if (res.code == 200) {
          const data = [...gData];
          loop(data, nodeData.key, (item, index, arr) => {
            arr.splice(index, 1);
          });
          setGData(data);
          message.success('封存成功', 2);
        } else {
          message.warning(res.msg, 2);
        }
      })
      .catch((error) => {
        message.error('接口异常,请联系管理员');
      });
  };

  /**
   * 合并
   * @param {*} nodeData
   */
  const onMerge = (nodeData) => {
    if (childRef.current) {
      childRef.current.getTreeData();
    }
    setMergeId(nodeData.id);
    setOpen(true);
  };

  const onMergeCreate = (values) => {
    let params = {
      department: values.department.substring(1),
      mergeName: values.mergeName,
      id: mergeId.substring(1),
    };
    fetch('/api/bs/hrmorganization/dept/mergeDepartment', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(params),
    })
      .then((response) => response.json())
      .then((res) => {
        if (res.code == 200) {
          message.success('合并成功', 2);
        } else {
          message.warning(res.msg, 2);
        }
        setOpen(false);
      })
      .catch((error) => {
        message.error('接口异常,请联系管理员');
      });
  };

  /**
   * 复制
   * @param {*} nodeData
   */
  const onCopy = (nodeData) => {
    setCopyOpen(true);
    setCopyId(nodeData.id);
  };

  const onCopyCreate = (values) => {
    fetch(`/api/bs/hrmorganization/dept/copyDepartment`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ ...values, ids: copyId }),
    })
      .then((response) => response.json())
      .then((res) => {
        if (res.code == 200) {
          setCopyOpen(false);
          message.success('复制成功', 2);
        } else {
          message.warning(res.msg, 2);
        }
      })
      .catch((error) => {
        message.error('接口异常,请联系管理员');
      });
  };

  const onTitleRender = (nodeData) => {
    let extend = nodeData.type == '1' ? 'companyExtend' : 'departmentExtend';
    let attr =
      nodeData.type == '1' || nodeData.canceled == '1'
        ? 'none'
        : 'inline-block';
    let icon = nodeData.type == '1' ? <HomeOutlined /> : <FolderOutlined />;
    return (
      <>
        {nodeData.type == 0 ? (
          <span>
            {' '}
            <ClusterOutlined />
            <span style={{ marginLeft: '5px' }}>{nodeData.title}</span>
          </span>
        ) : (
          <>
            <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>
              <Popconfirm
                title={`确认要删除 [${nodeData.title}] 吗?`}
                onConfirm={() => onDelete(nodeData)}
                okText="确认"
                cancelText="取消"
              >
                <span className="drag-button">删除</span>
              </Popconfirm>
              <Popconfirm
                title={`确认要封存或恢复 [${nodeData.title}] 吗?`}
                onConfirm={() => onCancel(nodeData)}
                okText="确认"
                cancelText="取消"
              >
                <span className="drag-button">
                  {nodeData.canceled == '0' ? '封存' : '恢复'}
                </span>
              </Popconfirm>
              <span
                style={{ display: attr }}
                className="drag-button"
                onClick={() => onMerge(nodeData)}
              >
                合并
              </span>
              <span
                style={{ display: attr }}
                className="drag-button"
                onClick={() => onCopy(nodeData)}
              >
                复制
              </span>
            </div>
          </>
        )}
      </>
    );
  };

  return (
    <>
      <ApartmentOutlined
        style={{ color: showCanceled == 0 ? '#1890ff' : '#eb2f96' }}
        onClick={() => {
          const value = showCanceled == 0 ? 1 : 0;
          setShowCanceled(value);
          getMoveTree(value);
        }}
      />
      <Spin tip={tip} spinning={loading}>
        <Tree
          className="draggable-tree"
          defaultExpandedKeys={expandedKeys}
          draggable
          icon={false}
          blockNode
          onDragEnter={onDragEnter}
          onDrop={onDrop}
          treeData={gData}
          titleRender={onTitleRender}
        />
        <MergeDialog
          ref={childRef}
          open={open}
          onCreate={onMergeCreate}
          onCancel={() => {
            setOpen(false);
          }}
        />
        {/* <CopyDialog  open={copyopen}
        onCreate={onCopyCreate}
        onCancel={() => {
          setCopyOpen(false);
        }}/> */}
      </Spin>
    </>
  );
};
export default DragTree;
