import React, { useState, useMemo } from 'react';
import { Popover,Checkbox } from 'antd';
import './index.less';
import SingleTag from '../SingleTag';
import IconFont from '../../../themeComponents/IconFont'

export default function MutipleTag(props) {
  let { onSelect, item, style, selectKeys, isActive, isMultiple = true, disabled } = props;
  const RenderComponent = useMemo(() => (isMultiple ? MutipleGroupTagContent : SingleGroupTagContent), [isMultiple]);
  const [visible, setVisible] = useState(false);
  function visibleChange(flag) {
    setVisible(flag);
  }
  return (
    <Popover
      placement="bottom"
      trigger="click"
      overlayClassName="mutiple-tag-popover-box"
      onVisibleChange={visibleChange}
      content={<RenderComponent onSelect={onSelect} group={item.children} selectKeys={selectKeys} disabled={disabled} />}
    >
      <SingleTag
        item={item}
        style={style}
        isActive={isActive}
        disabled={disabled}
        isGroup={true}
        selectKeys={selectKeys}
        suffix={<IconFont className={`tag-popup-allow ${visible ? 'tag-popup-allow-open' : ''}`} type="icon-S_Arrow_SmallDown"></IconFont>}
      ></SingleTag>
    </Popover>
  );
}

function SingleGroupTagContent({ group = [], onSelect, disabled, selectKeys = [] }) {
  return (
    <ul className="mutiple-tag-group">
      {group.map(v => (
        <li
          key={v.code}
          className={`${disabled ? 'lm-tag-item-disabled' : ''} ${selectKeys.indexOf(v.code) > -1 ? 'tag-group-item-active' : ''}`}
          onClick={e => {
            e.preventDefault();
            e.stopPropagation();
            !disabled && onSelect(v, group);
          }}
        >
          {/* <IconFont type={v.icon}></IconFont> */}
          <span className="lm-c-tag-label">{v.label}</span>
        </li>
      ))}
    </ul>
  );
}

function MutipleGroupTagContent({ group = [], onSelect, disabled, selectKeys = [] }) {
  return (
    <ul className="mutiple-tag-group mutiple-check-tag-group">
      {group.map(v => {
        const isActive = selectKeys.indexOf(v.code) > -1;
        return (
          <li
            key={v.code}
            className={`${disabled ? 'lm-tag-item-disabled' : ''} ${isActive ? 'tag-group-item-active' : ''}`}
            onClick={e => {
              e.preventDefault();
              e.stopPropagation();
              !disabled && onSelect(v);
            }}
          >
            <Checkbox disabled={disabled} checked={isActive}></Checkbox>
            <span className="lm-c-tag-label">{v.label}</span>
          </li>
        );
      })}
    </ul>
  );
}
