import React, { PureComponent } from 'react';
import Tooltip from 'antd/lib/Tooltip';
import Button from 'antd/lib/Button';
import Spin from 'antd/lib/Spin';

import { WrapperModal } from '../style'

interface IState {
  pageNumber: number;
  pageNumberInput: number;
  pageNumberFocus: boolean;
  numPages: number;
  pageWidth: number;
  fullscreen: boolean;
  loading: boolean;
}

import { Document, Page, pdfjs } from "react-pdf";
// `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`
// `./public/ThirdPlugins/reactPdf.js`;
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;


import './index.css';

export default class PdfFile extends PureComponent<any, IState> {

  state = {
    pageNumber: 1,
    pageNumberInput: 1,
    pageNumberFocus: false,
    numPages: 1,
    pageWidth: 600,
    fullscreen: false,
    loading: false
  };

  onDocumentLoadSuccess = ({ numPages }: any) => {
    this.setState({ numPages: numPages })
  }

  lastPage = () => {
    if (this.state.pageNumber == 1) {
      return
    }
    this.setState({
      loading: true
    }, () => {
      const page = this.state.pageNumber - 1
      this.setState({ pageNumber: page, pageNumberInput: page, loading: false })
    })

  }
  nextPage = () => {
    if (this.state.pageNumber == this.state.numPages) {
      return
    }
    const page = this.state.pageNumber + 1
    this.setState({ pageNumber: page, pageNumberInput: page })
  }
  onPageNumberFocus = (e: any) => {
    this.setState({ pageNumberFocus: true })
  };
  onPageNumberBlur = (e: any) => {
    this.setState({ pageNumberFocus: false, pageNumberInput: this.state.pageNumber })
  };
  onPageNumberChange = (e: any) => {
    let value = e.target.value
    value = value <= 0 ? 1 : value;
    value = value >= this.state.numPages ? this.state.numPages : value;
    this.setState({ pageNumberInput: value })
  };
  toPage = (e: any) => {
    this.setState({ pageNumber: Number(e.target.value) })
  };

  matchLocalhost = (str: string) => {
    return /localhost\:(\d)+/.test(str)
  }

  pageZoomOut = () => {
    if (this.state.pageWidth <= 600) {
      return
    }
    const pageWidth = this.state.pageWidth * 0.8
    this.setState({ pageWidth: pageWidth })
  }
  pageZoomIn = () => {
    const pageWidth = this.state.pageWidth * 1.2
    this.setState({ pageWidth: pageWidth })
  }

  pageFullscreen = () => {
    if (this.state.fullscreen) {
      this.setState({ fullscreen: false, pageWidth: 600 })
    } else {
      this.setState({ fullscreen: true, pageWidth: window.screen.width - 40 })
    }
  }

  handleCancel = () => {
    this.props.setVisible()
  }

  openDownloadDialog = (url: any, saveName: string) => {
    return new Promise((resolve, reject) => {
      resolve('')
    }).then(res => {
      if (typeof url == 'object' && url instanceof Blob) {
        url = URL.createObjectURL(url); // 创建blob地址
      }
      var aLink = document.createElement('a');
      aLink.href = url;
      aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
      var event;
      if (window.MouseEvent) event = new MouseEvent('click');
      else {
        event = document.createEvent('MouseEvents');
        event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
      }
      aLink.dispatchEvent(event);
    })
  }

  render() {
    const { visible, current, env } = this.props;
    const baseUrl = env?.axiosInstance?.defaults?.baseURL || env?.ajaxApi;
    const { pageNumber, numPages, pageWidth, fullscreen, loading } = this.state;
    return (
      <>
        {
          current && current?.name && (current?.addr || current?.url) ?
            <WrapperModal
              zIndex={9999}
              maskStyle={{
                zIndex: 9999
              }}
              getContainer={this.props.env?.getModalContainer as any}
              title={current?.name}
              wrapClassName='page-file'
              destroyOnClose={true}
              visible={visible}
              footer={<div className='pageTool' style={{
                display: 'flex',
                width: '100%',
                bottom: '20px',
                padding: '8px 15px',
                borderRadius: '15px'
              }}>
                <Tooltip overlayInnerStyle={{ zIndex: 11000 }} zIndex={11000} title={pageNumber == 1 ? "已是第一页" : "上一页"}>
                  <div className='toolBtn'>
                    <Button icon={<span className="fa fa-arrow-left"></span>} onClick={this.lastPage} ></Button>
                  </div>
                </Tooltip>
                <div className='toolBtn' style={{
                  width: '16vw',
                  display: 'flex',
                  justifyContent: 'space-evenly',
                  alignItems: 'center'
                }}>
                  <span>{pageNumber}</span>
                  <span>&nbsp;/&nbsp;</span>
                  <span>{numPages}</span>
                  {/* <Input value={pageNumberFocus ? pageNumberInput : pageNumber}
                  onFocus={this.onPageNumberFocus}
                  onBlur={this.onPageNumberBlur}
                  onChange={this.onPageNumberChange}
                  onPressEnter={this.toPage} type="number" /> / {numPages} */}
                </div>

                <Tooltip overlayInnerStyle={{ zIndex: 11000 }} zIndex={11000} title={pageNumber == numPages ? "已是最后一页" : "下一页"}>
                  <div className='toolBtn' style={{
                    width: '16vw',
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center'
                  }}>
                    <Button style={{ border: '0px !important' }} icon={<span className="fa fa-arrow-right"></span>} onClick={this.nextPage} ></Button>
                  </div>
                </Tooltip>
                <Tooltip overlayInnerStyle={{ zIndex: 11000 }} zIndex={11000} title="放大">
                  <div className='toolBtn' style={{
                    width: '16vw',
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center'
                  }}>
                    <Button style={{ border: '0px !important' }} icon={<span className="fa fa-plus-circle"></span>} onClick={this.pageZoomIn} ></Button>
                  </div>
                </Tooltip>
                <Tooltip overlayInnerStyle={{ zIndex: 11000 }} zIndex={11000} title="缩小">
                  <div className='toolBtn' style={{
                    width: '16vw',
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center'
                  }}>
                    <Button style={{ border: '0px !important' }} icon={<span className="fa fa-minus-circle"></span>} onClick={this.pageZoomOut} ></Button>
                  </div>
                </Tooltip>
                <Tooltip overlayInnerStyle={{ zIndex: 11000 }} zIndex={11000} title={fullscreen ? "恢复默认" : '适合窗口'}>
                  <div className='toolBtn' style={{
                    width: '16vw',
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center'
                  }}>
                    <Button style={{ border: '0px !important' }} icon={fullscreen ? <span className="fa fa-compress"></span> : <span className="fa fa-expand" ></span>} onClick={this.pageFullscreen}></Button>
                  </div>
                </Tooltip>
                <Tooltip overlayInnerStyle={{ zIndex: 11000 }} zIndex={11000} title={'下载'}>
                  <div className='toolBtn' style={{
                    width: '16vw',
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center'
                  }}>
                    <Button style={{ border: '0px !important' }} onClick={() => { this.openDownloadDialog((!baseUrl ? '' : (this.matchLocalhost(baseUrl) ? '' : baseUrl)) + (current?.addr ? current?.addr : current?.url), current?.name) }}>下载</Button>
                  </div>
                </Tooltip>
              </div>}
              onCancel={this.handleCancel}
              closable
            >
              <div className='view'
                style={{
                  display: 'flex',
                  justifyContent: 'center',
                  height: '400px',
                  /* padding: 50px 0; */
                  overflow: 'auto',
                  /* width: 200px; */
                  margin: 'auto',
                  width: '100%'
                }}
              >{
                  <div className='pageContainer'
                    style={{
                      width: '100vw',
                      maxWidth: '100%'
                    }}>
                    <Document
                      file={(!baseUrl ? '' : (this.matchLocalhost(baseUrl) ? '' : baseUrl)) + (current?.addr ? current?.addr : current?.url)}
                      onLoadSuccess={this.onDocumentLoadSuccess}
                      error='Failed to load PDF file'
                      loading={<Spin style={{
                        margin: 'auto'
                      }} size="large" />}
                    >
                      <Page pageNumber={pageNumber} width={pageWidth} loading={<Spin size="large" />} />
                    </Document>
                  </div>
                }


              </div>
            </WrapperModal> : null}
      </>
    );
  }
}
