import * as React from 'react';
import copy from 'copy-to-clipboard';
import classnames from 'classnames';
import { labelProps } from 'src/types/op-label';
import './index.scss';

/**
 * 高亮部分文本
 * label:"11111 2222"
 *
 * <OPLabel label="12321321"  >
 */

export default function OPLabel(props: labelProps) {
  const {
    copyText = '点击复制',
    copySuccessText = '复制成功',
    label = '',
    highlightLength = -4,
    fontSize = undefined,
    color = undefined,
    maxLength = undefined,
    copyable = true,
  } = props;
  const [copyText1, setCopyText] = React.useState(copyText);
  const onCopy = React.useCallback(
    function () {
      if (label) {
        try {
          copy(label);
          setCopyText(copySuccessText);
        } catch (e) {
          console.warn('copy error', e);
        }
        setTimeout(function () {
          setCopyText(copyText);
        }, 3000);
      }
    },
    [label],
  );

  const text = React.useMemo(
    function () {
      let text = String(label);
      if (maxLength && text.length > maxLength) {
        text = '...' + text.slice(text.length - maxLength);
      }
      return text;
    },
    [label],
  );
  return (
    <div
      data-hottag='cn-op.label'
      className={classnames('op-label-text', {
        copyable,
      })}
      style={{ fontSize, color }}
      title={label}
      onClick={onCopy}
    >
      <span className='op-label-text1'>{text.slice(0, highlightLength)}</span>
      <span className='op-label-text2'>{text.slice(highlightLength)}</span>
      <span className='op-label-copyed'>{copyText1}</span>
    </div>
  );
}
