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 copyChildRef = 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, expandedKeys = '') => {
    setLoading(true);
    d3.json(
      `/api/bs/hrmorganization/orgchart/getMovingTree?showCanceled=${showCanceled}&expandedKeys=${expandedKeys}`,
    ).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);
          message.success('转移成功', 2);
        } 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.substring(1) }),
    })
      .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.substring(1),
        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) {
          getMoveTree(0, values.department);
          message.success('合并成功', 2);
        } else {
          message.warning(res.msg, 2);
        }
        setOpen(false);
      })
      .catch((error) => {
        message.error('接口异常,请联系管理员');
      });
  };

  /**
   * 复制
   * @param {*} nodeData
   */
  const onCopy = (nodeData) => {
    if (copyChildRef.current) {
      copyChildRef.current.getTreeData();
    }
    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.substring(1) }),
    })
      .then((response) => response.json())
      .then((res) => {
        if (res.code == 200) {
          setCopyOpen(false);
          getMoveTree(0, values.company);
          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}
                {nodeData.canceled == '1' ? (
                  <span style={{ color: 'red', marginLeft: '5px' }}>
                    (已封存)
                  </span>
                ) : (
                  ''
                )}
              </span>
            </span>
            <div id="drag-button-ops">
              <span
                className="drag-button"
                onClick={() =>
                  window.open(
                    `/spa/organization/static/index.html#/main/organization/${extend}/${nodeData.id.substring(
                      1,
                    )}`,
                    '_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>
          </>
        )}
      </>
    );
  };

  const onExpand = (info) => {
    setExpandedKeys(info);
  };

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