import React, { useEffect, useState } from 'react'
import { Document, Page, pdfjs } from "react-pdf";
import './index.scss'
// import 'react-pdf/dist/esm/Page/AnnotationLayer.css';
import Axios from 'axios';
import InputNumber from 'antd/lib/input-number';

import { Spinner } from '../../../../components/Spinner';
import { classNames } from '../../utils/utils'
import Spin from 'antd/lib/Spin';

// pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.js`;
// pdfjs.GlobalWorkerOptions.workerSrc = 'pdf.worker.min.js'
pdfjs.GlobalWorkerOptions.workerSrc = `./public/ThirdPlugins/reactPdf.js`
// pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/legacy/build/pdf.worker.min.js`;

interface IProps {
  src: string;
}

const PdfViewerContent: React.FC<IProps> = (props) => {
  const { src } = props;

  const [errorTip, setErrorTip] = useState<string | null>(null);
  const [fileData, setFileData] = useState<any>(null)

  const [totalPage, setTotalPage] = useState<number>(0);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [scale, setScale] = useState<number>(1);

  const updataPage = (file: any, err: string | null) => {
    setFileData(file)
    setErrorTip(err)
    // 重置页码
    setTotalPage(0)
    setCurrentPage(1)

  }

  // 前端预请求,为了拿到具体的提示信息
  useEffect(() => {
    // 后端说没给预览地址说明该类型不支持预览
    if (src) {
      Axios({
        url: src,
        responseType: 'arraybuffer', //二进制流
        headers: {
          'Content-Type': 'application/json;charset=utf-8'
        }
      }).then((res) => {

        // 可能传递json格式的非文件信息，文件格式一般比较大
        if (res.data.byteLength > 500) {
          updataPage(res, null)
          return
        }

        // 无法转成json格式的直接判断为文件格式
        try {
          const enc = new TextDecoder('utf-8')
          const uint8_msg = new Uint8Array(res.data)
          const json = JSON.parse(enc.decode(uint8_msg))
          updataPage(null, json.msg)
        } catch (e) {
          updataPage(res, null)
        }
      }).catch(e => {
        updataPage(null, '文件地址请求错误')
      })
    } else {
      updataPage(null, '该文件类型不支持预览')
    }
  }, [src])

  // 切换上下页
  const nextOrPre = (type: 'next' | 'pre') => {
    if (type === 'next') setCurrentPage(origin => origin < totalPage ? origin + 1 : origin)
    else setCurrentPage(origin => origin > 1 ? origin - 1 : origin)
  }
  // 放大缩小
  const changeScale = (type: 'add' | 'reduce') => {
    if (type === 'add') setScale(origin => Number((origin < 2 ? origin + 0.2 : origin).toFixed(1)))
    else setScale(origin => Number((origin > 0.5 ? origin - 0.2 : origin).toFixed(1)))
  }

  return <div className={!fileData ? 'pdfLoadingWrapper' : 'pdfViewerWrapper'}>
    {
      fileData
        ? <Document
          className={'pdfDocumentContent'}
          loading={<Spin size="large" />}
          options={{
            // cMapUrl: `//cdn.jsdelivr.net/npm/pdfjs-dist@${pdfjs.version}/cmaps/`,
            cMapUrl: `https://unpkg.com/pdfjs-dist@${pdfjs.version}/cmaps/`,
            cMapPacked: true,
          }}
          onLoadSuccess={({ numPages }) => {
            setTotalPage(numPages)
            setCurrentPage(1)
          }}
          file={fileData}
        >
          <Page
            pageNumber={currentPage}
            scale={scale}
          />
        </Document>
        : (errorTip
          ? <div className='pdfErrorTip'>
            <div>{errorTip}</div>
          </div>
          : <Spin size="large" />
        )

    }
    {
      fileData &&
      <div className={'pdfUtils'}>
        <div className={classNames(
          'iconWrapper',
          currentPage === 1 && 'iconWrapper_disabled'
        )} onClick={() => { nextOrPre('pre') }}>
          <i className="fa fa-chevron-up"></i>
        </div>
        <InputNumber
          value={currentPage}
          onPressEnter={(e) => {
            let currentPage = Number(e.currentTarget.value);
            if (currentPage > totalPage) {
              currentPage = totalPage
              // Modal.toast({ content: `该文件最大 ${totalPage} 页` })
            }
            setCurrentPage(currentPage)
          }}
          className={'pageInput'}
          min={1}
          max={totalPage}
        />
        <div className={classNames(
          'iconWrapper',
          currentPage === totalPage && 'iconWrapper_disabled'
        )} onClick={() => { nextOrPre('next') }}>
          <i className="fa fa-chevron-down"></i>
        </div>
        <div className={classNames(
          'iconWrapper',
          scale >= 2 && 'iconWrapper_disabled'
        )} onClick={() => { changeScale('add') }}>
          <i className="fa fa-search-plus"></i>
        </div>
        <div className={classNames(
          'iconWrapper',
          scale <= 0.5 && 'iconWrapper_disabled'
        )} onClick={() => { changeScale('reduce') }}>
          <i className="fa fa-search-minus"></i>
        </div>
        <div className={classNames(
          'iconWrapper',
          scale === 1 && 'iconWrapper_disabled'
        )} onClick={() => {
          setScale(1)
        }}>
          <i className="fa fa-arrows-alt"></i>
        </div>
      </div>
    }
  </div>
}

export default PdfViewerContent
