import Button from '../button';
import Tag from '../tag';
import Typography from '../typography';
import Popover from '../popover';

const { Paragraph } = Typography;

export const customFiltersLabel = props => {
  const { prefixCls, selectedKeysMap = {}, onClose, onClear, columns } = props;
  const columnsIndex = Object.keys(selectedKeysMap);
  const columnsSelectedKeys = Object.values(selectedKeysMap);
  if (
    columnsIndex.length === 0 ||
    !columnsSelectedKeys.some(keys => keys.length > 0)
  )
    return null;

  const getFltText = (value, filters) => {
    const childrens = filters.reduce(
      (prev, current) =>
        current.children ? [...prev, ...current.children] : prev,
      [],
    );
    const fltFind = [...filters, ...childrens].find(f => f.value === value);
    if (fltFind) return fltFind.text;
    return '';
  };

  return (
    <div className={`${prefixCls}-filter-labels-wrap`}>
      <span style={{ marginRight: 12 }}>已选:</span>
      {columnsIndex.map((colIndex, index) => {
        const col = columns.find(col => col.dataIndex === colIndex);
        const { title, filters } = col;
        const selectedKeys = columnsSelectedKeys[index];
        if (selectedKeys.length === 0) return null;

        const keyStr = `${title}: ${selectedKeys
          .map(
            (key, j) =>
              `${getFltText(key, filters)}${
                j < selectedKeys.length - 1 ? '; ' : ''
              }`,
          )
          .join('')}`;

        return (
          <Tag key={title} closable onClose={() => onClose(colIndex)}>
            <div>
              <Popover placement="top" content={keyStr}>
                <Paragraph
                  ellipsis={{ rows: 1, expandable: false, symbol: '...' }}
                >
                  {' '}
                  {keyStr}
                </Paragraph>
              </Popover>
            </div>
          </Tag>
        );
      })}
      <Button size="xsmall" onClick={onClear}>
        清除
      </Button>
    </div>
  );
};
