import "core-js/modules/es.array.iterator.js";
import "core-js/modules/web.dom-collections.iterator.js";
import React, { useContext, useEffect, useRef } from 'react';
import { SettingOutlined, VerticalAlignMiddleOutlined, VerticalAlignTopOutlined, VerticalAlignBottomOutlined } from '@ant-design/icons';
import classNames from 'classnames';
import Checkbox from '../checkbox';
import Tree from '../tree';
import Popover from '../popover';
import Tooltip from '../tooltip';
import ConfigProvider from '../config-provider';
import Button from '../button';
import Container from './container';
import { useIntl } from '../wau-provider';
import DragIcon from './DragIcon';
import { genColumnKey } from './utils';
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
import { Fragment as _Fragment } from "react/jsx-runtime";
const ToolTipIcon = ({
  title,
  show,
  children,
  columnKey,
  fixed
}) => {
  // eslint-disable-next-line
  const {
    columnsMap,
    setColumnsMap
  } = Container.useContainer();
  if (!show) {
    return null;
  }
  return /*#__PURE__*/_jsx(Tooltip, {
    title: title,
    children: /*#__PURE__*/_jsx("span", {
      onClick: e => {
        e.stopPropagation();
        e.preventDefault();
        const config = columnsMap[columnKey] || {};
        const columnKeyMap = {
          ...columnsMap,
          [columnKey]: {
            ...config,
            fixed
          }
        };
        setColumnsMap(columnKeyMap);
      },
      children: children
    })
  });
};
const CheckboxListItem = ({
  columnKey,
  title,
  className,
  fixed
}) => {
  const intl = useIntl();
  return /*#__PURE__*/_jsxs("span", {
    className: `${className}-list-item`,
    children: [/*#__PURE__*/_jsx("div", {
      className: `${className}-list-item-title`,
      children: title
    }), /*#__PURE__*/_jsxs("span", {
      className: `${className}-list-item-option`,
      children: [/*#__PURE__*/_jsx(ToolTipIcon, {
        columnKey: columnKey,
        fixed: "left",
        title: intl.getMessage('tableToolBar.leftPin', '固定在列首'),
        show: fixed !== 'left',
        children: /*#__PURE__*/_jsx(VerticalAlignTopOutlined, {})
      }), /*#__PURE__*/_jsx(ToolTipIcon, {
        columnKey: columnKey,
        fixed: undefined,
        title: intl.getMessage('tableToolBar.noPin', '不固定'),
        show: !!fixed,
        children: /*#__PURE__*/_jsx(VerticalAlignMiddleOutlined, {})
      }), /*#__PURE__*/_jsx(ToolTipIcon, {
        columnKey: columnKey,
        fixed: "right",
        title: intl.getMessage('tableToolBar.rightPin', '固定在列尾'),
        show: fixed !== 'right',
        children: /*#__PURE__*/_jsx(VerticalAlignBottomOutlined, {})
      })]
    })]
  }, columnKey);
};
const CheckboxList = ({
  list,
  draggable,
  checkable,
  className,
  showTitle = true,
  title: listTitle
}) => {
  const {
    columnsMap,
    setColumnsMap,
    sortKeyColumns,
    setSortKeyColumns
    // eslint-disable-next-line
  } = Container.useContainer();
  const show = list && list.length > 0;
  if (!show) {
    return null;
  }
  const move = (id, targetId, dropPosition) => {
    const newMap = {
      ...columnsMap
    };
    const newColumns = [...sortKeyColumns.current];
    const findIndex = newColumns.findIndex(columnKey => columnKey === id);
    const targetIndex = newColumns.findIndex(columnKey => columnKey === targetId);
    const isDownWord = dropPosition > findIndex;
    if (findIndex < 0) {
      return;
    }
    const targetItem = newColumns[findIndex];
    newColumns.splice(findIndex, 1);
    if (dropPosition === 0) {
      newColumns.unshift(targetItem);
    } else {
      newColumns.splice(isDownWord ? targetIndex : targetIndex + 1, 0, targetItem);
    }
    // 重新生成排序数组
    newColumns.forEach((key, order) => {
      newMap[key] = {
        ...(newMap[key] || {}),
        order
      };
    });
    // 更新数组
    setColumnsMap(newMap);
    setSortKeyColumns(newColumns);
  };
  const checkedKeys = [];
  const treeData = list.map(({
    key,
    ...rest
  }) => {
    const columnKey = genColumnKey(key, rest.index);
    const config = columnsMap[columnKey || 'null'] || {
      show: true
    };
    if (config.show !== false) {
      checkedKeys.push(columnKey);
    }
    return {
      key: columnKey,
      ...rest,
      selectable: false,
      switcherIcon: /*#__PURE__*/_jsx(DragIcon, {})
    };
  });
  const listDom = /*#__PURE__*/_jsx(Tree, {
    itemHeight: 24,
    draggable: draggable ? {
      icon: false
    } : false,
    checkable: checkable,
    onDrop: info => {
      const dropKey = info.node.key;
      const dragKey = info.dragNode.key;
      const {
        dropPosition,
        dropToGap
      } = info;
      const position = dropPosition === -1 || !dropToGap ? dropPosition + 1 : dropPosition;
      move(dragKey, dropKey, position);
    },
    blockNode: true,
    onCheck: (_, e) => {
      const columnKey = e.node.key;
      const tempConfig = columnsMap[columnKey] || {};
      const newSetting = {
        ...tempConfig
      };
      if (e.checked) {
        delete newSetting.show;
      } else {
        newSetting.show = false;
      }
      const columnKeyMap = {
        ...columnsMap,
        [columnKey]: newSetting
      };
      // 如果没有值了，直接干掉他
      if (Object.keys(newSetting).length === 0) {
        delete columnKeyMap[columnKey];
      }
      setColumnsMap(columnKeyMap);
    },
    checkedKeys: checkedKeys,
    showLine: false,
    titleRender: node => {
      return /*#__PURE__*/_jsx(CheckboxListItem, {
        className: className,
        ...node,
        title: typeof node.title === 'function' ? node.title(node) : node.title,
        columnKey: node.key
      });
    },
    height: 280,
    treeData: treeData
  });
  return /*#__PURE__*/_jsxs(_Fragment, {
    children: [showTitle && /*#__PURE__*/_jsx("span", {
      className: `${className}-list-title`,
      children: listTitle
    }), listDom]
  });
};
const GroupCheckboxList = ({
  localColumns,
  className,
  draggable,
  checkable
}) => {
  const rightList = [];
  const leftList = [];
  const list = [];
  const intl = useIntl();
  localColumns.forEach(item => {
    const {
      fixed
    } = item;
    /** 不在 setting 中展示的 */
    if (item.hideInSetting) {
      return;
    }
    if (fixed === 'left') {
      leftList.push(item);
      return;
    }
    if (fixed === 'right') {
      rightList.push(item);
      return;
    }
    list.push(item);
  });
  const showRight = rightList && rightList.length > 0;
  const showLeft = leftList && leftList.length > 0;
  return /*#__PURE__*/_jsxs("div", {
    className: classNames(`${className}-list`, {
      [`${className}-list-group`]: showRight || showLeft
    }),
    children: [/*#__PURE__*/_jsx(CheckboxList, {
      title: intl.getMessage('tableToolBar.leftFixedTitle', '固定在左侧'),
      list: leftList,
      draggable: draggable,
      checkable: checkable,
      className: className
    }), /*#__PURE__*/_jsx(CheckboxList, {
      list: list,
      draggable: draggable,
      checkable: checkable,
      title: intl.getMessage('tableToolBar.noFixedTitle', '不固定'),
      showTitle: showLeft || showRight,
      className: className
    }), /*#__PURE__*/_jsx(CheckboxList, {
      title: intl.getMessage('tableToolBar.rightFixedTitle', '固定在右侧'),
      list: rightList,
      draggable: draggable,
      checkable: checkable,
      className: className
    })]
  });
};
function ColumnSetting(props) {
  var _props$checkable, _props$draggable;
  const columnRef = useRef({});
  // eslint-disable-next-line
  const counter = Container.useContainer();
  const localColumns = props.columns;
  const {
    columnsMap,
    setColumnsMap
  } = counter;
  useEffect(() => {
    if (columnsMap) {
      columnRef.current = JSON.parse(JSON.stringify(columnsMap));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  /**
   * 设置全部选中，或全部未选中
   *
   * @param show
   */
  const setAllSelectAction = (show = true) => {
    const columnKeyMap = {};
    localColumns.forEach(({
      key,
      fixed,
      index
    }) => {
      const columnKey = genColumnKey(key, index);
      if (columnKey) {
        columnKeyMap[columnKey] = {
          show,
          fixed
        };
      }
    });
    setColumnsMap(columnKeyMap);
  };

  // 选中的 key 列表
  const selectedKeys = Object.values(columnsMap).filter(value => !value || value.show === false);

  // 是否已经选中
  const indeterminate = selectedKeys.length > 0 && selectedKeys.length !== localColumns.length;
  const intl = useIntl();
  const {
    getPrefixCls
  } = useContext(ConfigProvider.ConfigContext);
  const className = getPrefixCls('pro-table-column-setting');
  return /*#__PURE__*/_jsx(Popover, {
    arrowPointAtCenter: true,
    title: /*#__PURE__*/_jsxs("div", {
      className: `${className}-title`,
      children: [/*#__PURE__*/_jsx(Checkbox, {
        indeterminate: indeterminate,
        checked: selectedKeys.length === 0 && selectedKeys.length !== localColumns.length,
        onChange: e => {
          if (e.target.checked) {
            setAllSelectAction();
          } else {
            setAllSelectAction(false);
          }
        },
        children: intl.getMessage('tableToolBar.columnDisplay', '列展示')
      }), /*#__PURE__*/_jsx("a", {
        onClick: () => {
          setColumnsMap(columnRef.current);
        },
        children: intl.getMessage('tableToolBar.reset', '重置')
      })]
    }),
    overlayClassName: `${className}-overlay`,
    trigger: "click",
    placement: "bottomRight",
    content: /*#__PURE__*/_jsx(GroupCheckboxList, {
      checkable: (_props$checkable = props.checkable) !== null && _props$checkable !== void 0 ? _props$checkable : true,
      draggable: (_props$draggable = props.draggable) !== null && _props$draggable !== void 0 ? _props$draggable : true,
      className: className,
      localColumns: localColumns
    }),
    children: /*#__PURE__*/_jsx(Tooltip, {
      title: intl.getMessage('tableToolBar.columnSetting', '列设置'),
      children: /*#__PURE__*/_jsx(Button, {
        icon: /*#__PURE__*/_jsx(SettingOutlined, {})
      })
    })
  });
}
export default ColumnSetting;