import React, { useEffect, useState } from 'react';
import './index.css';
import hljs from 'highlight.js';
import '../../style/atom-one-dark.css';
import copyIcon from '../../assets/copyIcon.svg';
import copyIconActive from '../../assets/copyIconActive.svg';

const copy = (props: any) => {

  const [copyShow, setCopyShow] = useState(false)


  const copyValue = () => {

    let Url = props?.children[0];
    let oInput = document.createElement("textarea");
    oInput.value = Url ?? "";
    document.body.appendChild(oInput);
    oInput.select();
    document.execCommand("Copy");
    oInput.className = "oInput";
    oInput.style.display = "none";
    document.body.removeChild(oInput);
  };

  useEffect(() => {
    const codes = document?.querySelectorAll<HTMLElement>('.copyCode')

    hljs.configure({
      // 忽略警告
      ignoreUnescapedHTML: true
    })
    if (codes && codes.length > 0) {
      codes.forEach(el => {
        // 让每个 code 内容实现代码高亮
        hljs?.highlightElement(el)
      })
      return
    }

    // 直接找到所有的 pre 标签
    const pres = document?.querySelectorAll<HTMLElement>('.copyCode')
    if (pres && pres.length > 0) {
      pres.forEach(el => {
        hljs.highlightElement(el)
      })
    }
  }, [props?.children]);
  return (
    <div id={props?.className ?? ''} data-start={props?.position?.start?.line ?? ''} data-end={props?.position?.end?.line ?? ''} data-page={props?.page ?? 0} className={`scrollIcon copyCodeContain`}>
      <span className='execSpan'>
        <pre className={props?.className}>
          <code className='copyCode'>
            {props?.children[0]}
          </code>
        </pre>
      </span>
      {props?.children[0] &&
        <div className='actionIcon'>
          {copyShow ? <span className="extvalue" onClick={copyValue}
            onMouseEnter={() => setCopyShow(true)}
            onMouseLeave={() => setCopyShow(false)}
          >
            <img className="extvalue1" data-type={'copy'} data-value={props?.children[0]} src={copyIconActive} alt="" />
            <div className='hoverTotip'>
              复制
            </div>
          </span> : <span className="extvalue" onClick={copyValue}
            onMouseEnter={() => setCopyShow(true)}
            onMouseLeave={() => setCopyShow(false)}
          >
            <img src={copyIcon} alt="" />
          </span>}
        </div>
      }
    </div>
  );
};

export default copy;

