
import React, { useEffect, useState } from 'react';
import { Document, Page, pdfjs } from 'react-pdf'
import './index.css';
import '../../style/atom-one-dark.css';

const link = (props: any) => {
  // const componentRef = useRef<any>();
  pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;
  // 总页数
  const [numPages, setNumPages] = useState<any>();

  // 当前页
  const [nowPage, setNowPage] = useState<any>(1);

  //输入框是否处于编辑态
  // 当前页
  const [nowPageInput, setNowPageInput] = useState<any>(false);

  const leftIcon = '<'

  const rigthIcon = '>'

  // 加载成功
  const onDocumentLoadSuccess = ({ numPages }: any) => {
    setNumPages(numPages);
  }

  // useEffect(() => {
  //   const handleResize = () => {
  //     if (!componentRef?.current?.offsetWidth) return
  //     const width = componentRef?.current?.offsetWidth;
  //     const height = width * (4 / 3); // 假设 PDF 的宽高比为 4:3
  //     componentRef.current.style.height = `${height}px`;
  //   };

  //   window.addEventListener('resize', handleResize);
  //   handleResize(); // 初始化时获取一次组件宽度

  //   return () => {
  //     window.removeEventListener('resize', handleResize);
  //   };
  // }, [componentRef.current]);

  useEffect(() => {
    let inputElement = document.getElementById('input');
    inputElement?.focus();
  }, [document.getElementById('input')])

  return (
    <div data-start={props?.position?.start?.line ?? ''} data-end={props?.position?.end?.line ?? ''} data-page={props?.page ?? 0} className='pdfShow'>

      {
        <Document file={props?.href || ''} onLoadSuccess={onDocumentLoadSuccess} >
          <Page renderTextLayer={false} pageNumber={nowPage} />

        </Document>

      }
      {/* <Pagination simple defaultCurrent={2} total={50} /> */}
      {numPages > 0 &&
        <div className='pagechange'>
          <div className='iconLeft' onClick={() => {
            if (nowPage > 1) {
              setNowPage(nowPage - 1)
            }
          }}>{leftIcon}</div>
          <div className='nowPage' onClick={() => {
            setNowPageInput(true)
          }}>
            {nowPageInput &&
              < input id="input" className='nowPageInput' autoComplete="off" onChange={(e: any) => {

                if (e.target.value > 0 && e.target.value < numPages + 1) {
                  setNowPage(Number(e.target.value))
                }
              }} onBlur={() => {
                setNowPageInput(false)
              }} />
            }
            {!nowPageInput && <span>{nowPage}</span>}
          </div>
          <div>/</div>
          <div style={{ margin: '0 6px' }}>{numPages}</div>
          <div onClick={() => {
            if (nowPage < numPages) {
              setNowPage(nowPage + 1)
            }
          }}>{rigthIcon}</div>
        </div>
      }
    </div>
  );
};
export default link;