import React, { useState, useCallback, memo } from 'react';
import { Tooltip } from 'antd';

CopyTool.defaultProps = {
  beforeText: '复制链接',     //浮动过去显示的文字
  afterText: '复制成功',  //点击后显示的文字
  className: '',         //传给svg的class
  inputId: 'copyText',    //要复制的文本的ID
  timeOut:true, //复制后将浮动的文字改为beforeText
};


function CopyTool({ beforeText, afterText, className , inputId , timeOut }) {
  const [title, setTitle] = useState(() => {
    return beforeText;
  });

  // 复制链接
  const copyUrl = useCallback(() => {
    const copyEle = document.querySelector(`#${inputId}`); // 获取要复制的节点
    if (!copyEle) {
      console.error("您的CopyTool未设置正确的inputId");
      return;
    }
    copyEle.select(); // 执行选中元素
    if (document.execCommand('copy')) {
      document.execCommand('copy');
    }
    document.getSelection().removeAllRanges();
    
    setTitle(afterText);
    if(timeOut){
      setTimeout(function(){
        setTitle(beforeText);
      },1500)
    }
  }, []);

  return (
    <Tooltip
      placement="top"
      title={title}
      onVisibleChange={() => { setTitle(beforeText) }}
    >
      <i className={`iconfont icon-fuzhiicon ${className}`} style={{ color: '#466aff' }} onClick={copyUrl}></i>
    </Tooltip>
  );
}


export default memo(CopyTool);