import React, { useEffect } from 'react';
import { Input, Tooltip, Menu, Dropdown, Popover, Checkbox, Tree } from 'antd';
import { configItem } from '..';

export interface IProps {
  onSearch: (
    value: any,
    event?:
      | React.ChangeEvent<HTMLInputElement>
      | React.MouseEvent<HTMLElement>
      | React.KeyboardEvent<HTMLInputElement>,
  ) => void;
  toolBarRender?: React.ReactNode[];
  configs?: configItem[];
  tablesize: string;
  handleChangeSize: (item?: object) => void;
  columns?: any;
  plainOptions?: any;
  checkedOptions?: any;
  handleCheckColumns?: (e: any) => void;
  handleNewDrop?: (data: any) => void;
  handleClickToolbar?: (key: string) => void;
}

const TableToolbar: React.FC<IProps> = (props: IProps) => {
  const { Search } = Input;

  const {
    onSearch,
    handleChangeSize,
    handleCheckColumns,
    handleNewDrop,
    handleClickToolbar,
    toolBarRender,
    configs = [],
    tablesize,
    plainOptions,
    checkedOptions,
  } = props;

  const lineHeightMenu = (
    <Menu
      onClick={handleChangeSize}
      selectedKeys={tablesize ? tablesize.split(',') : ['small']}
    >
      <Menu.Item key="small">默认</Menu.Item>
      <Menu.Item key="middle">中等</Menu.Item>
      <Menu.Item key="default">正常</Menu.Item>
    </Menu>
  );

  const onSelectAll = (e: any) => {
    let keys = [];
    if (e.target.checked) {
      keys = plainOptions.map((item: any) => item.key);
    }
    if (handleCheckColumns) handleCheckColumns({ checked: keys });
  };

  const PopoverTitle = (
    <div
      style={{
        width: '100%',
        display: 'flex',
        flexDirection: 'row',
        alignItems: 'center',
        fontWeight: 400,
      }}
    >
      <div style={{ flex: 1, overflow: 'hidden' }}>
        <Checkbox
          disabled={plainOptions.length === 0}
          checked={
            checkedOptions.length > 0 &&
            checkedOptions.length === plainOptions.length
          }
          indeterminate={
            checkedOptions.length > 0 &&
            checkedOptions.length !== plainOptions.length
          }
          onChange={onSelectAll}
        >
          列展示
        </Checkbox>
      </div>
      {/* <a>重置</a> */}
    </div>
  );

  const handleDrop = (info: any) => {
    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: any, key: any, callback: Function) => {
      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 = [...plainOptions];

    let dragObj: any;
    loop(data, dragKey, (item: any, index: any, arr: any) => {
      arr.splice(index, 1);
      dragObj = item;
    });

    if (!info.dropToGap) {
      // Drop on the content
      loop(data, dropKey, (item: { children: any[] }) => {
        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: { children: any[] }) => {
        item.children = item.children || [];
        // where to insert 示例添加到头部，可以是随意位置
        item.children.unshift(dragObj);
      });
    } else {
      let ar: any;
      let i: any;
      loop(data, dropKey, (item: any, index: any, arr: any) => {
        ar = arr;
        i = index;
      });
      if (dropPosition === -1) {
        ar.splice(i, 0, dragObj);
      } else {
        ar.splice(i + 1, 0, dragObj);
      }
    }

    if (handleNewDrop) handleNewDrop(data);
  };

  const newConfigs = configs.map(item => ({
    ...item,
    render: item.render || (node => node),
  }));

  const searchConfig = newConfigs.find(item => item.text == '搜索');
  const refreshConfig = newConfigs.find(item => item.text == '刷新');
  const LineHeightConfig = newConfigs.find(item => item.text == '行高');
  const exportConfig = newConfigs.find(item => item.text == '导出');
  const setUpConfig = newConfigs.find(item => item.text == '设置');

  return (
    <>
      <div className="table-toolbar-container">
        <div className="table-toolbar-left">
          {toolBarRender && toolBarRender?.length > 0 ? (
            toolBarRender.map((item: any, index: number) => {
              return (
                <div
                  className="table-space-item"
                  key={item.key}
                  style={{
                    marginRight:
                      toolBarRender.length === index + 1 ? 0 : '10px',
                  }}
                >
                  {item}
                </div>
              );
            })
          ) : (
            <div className="table-space-item">{toolBarRender}</div>
          )}
        </div>
        <div className="table-toobar-right">
          {searchConfig?.text == '搜索'
            ? searchConfig.render(
                <div
                  className="table-space-item"
                  style={{ marginRight: '16px' }}
                >
                  <Search
                    enterButton={false}
                    onSearch={onSearch}
                    style={{ fontSize: '14px' }}
                  />
                </div>,
              )
            : null}
          {refreshConfig?.text == '刷新'
            ? refreshConfig.render(
                <Tooltip title="刷新">
                  <div
                    className="table-space-item"
                    style={{ marginRight: '16px' }}
                  >
                    <a onClick={handleClickToolbar?.bind(null, 'refresh')}>
                      <i
                        className="iconfont icon-redo"
                        style={{ fontSize: '18px' }}
                      />
                    </a>
                  </div>
                </Tooltip>,
              )
            : null}
          {LineHeightConfig?.text == '行高'
            ? LineHeightConfig.render(
                <Dropdown overlay={lineHeightMenu} trigger={['click']}>
                  <Tooltip title="行高">
                    <div
                      className="table-space-item"
                      style={{ marginRight: '16px' }}
                    >
                      <a>
                        <i
                          className="iconfont icon-colum-height"
                          style={{ fontSize: '18px' }}
                        />
                      </a>
                    </div>
                  </Tooltip>
                </Dropdown>,
              )
            : null}
          {exportConfig?.text == '导出'
            ? exportConfig.render(
                <Tooltip title="导出">
                  <div
                    className="table-space-item"
                    style={{ marginRight: '16px' }}
                  >
                    <a onClick={handleClickToolbar?.bind(null, 'export')}>
                      <i
                        className="iconfont icon-exceldaochu"
                        style={{ fontSize: '18px' }}
                      />
                    </a>
                  </div>
                </Tooltip>,
              )
            : null}
          {setUpConfig?.text == '设置'
            ? setUpConfig.render(
                <Popover
                  placement="bottomRight"
                  title={PopoverTitle}
                  content={
                    <>
                      <Tree
                        className="draggable-tree"
                        checkable
                        blockNode
                        draggable
                        height={233}
                        treeData={plainOptions}
                        switcherIcon={
                          <i
                            className="iconfont icon-Drag"
                            style={{ color: '#999', cursor: 'all-scroll' }}
                          />
                        }
                        checkedKeys={checkedOptions}
                        titleRender={nodeData => {
                          return <>{nodeData.title}</>;
                        }}
                        checkStrictly
                        onDrop={handleDrop}
                        onCheck={handleCheckColumns}
                      />
                    </>
                  }
                  trigger="click"
                >
                  <Tooltip title="设置">
                    <div className="table-space-item">
                      <a>
                        <i
                          className="iconfont icon-setting"
                          style={{ fontSize: '18px' }}
                        />
                      </a>
                    </div>
                  </Tooltip>
                </Popover>,
              )
            : null}
        </div>
      </div>
    </>
  );
};

export default TableToolbar;
