/* eslint-disable prefer-destructuring */
/* eslint no-dupe-keys: 0, no-mixed-operators: 0 */
import React from 'react';
import { InputItem, Icon } from 'antd-mobile-v2';
import { Document, Page, pdfjs } from 'react-pdf';
import 'antd-mobile-v2/dist/antd-mobile.css';
import pdfstyles from './printpdf.less';
import * as commonUtils from '../../../utils/utils';

pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.js`;

class CommonPrintPdf extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      pageNumber: 1,
      numPages: 1,
    };
  }

  onDocumentLoadSuccess = ({ numPages }) => {
    this.setState({ numPages });
  };

  onPageNumberChange = (e) => {
    let value = commonUtils.convertStrToNumber(e);
    value = value <= 0 ? 1 : value;
    value = value >= this.state.numPages ? this.state.numPages : value;
    this.setState({ pageNumber: value });
  };
  lastPage = () => {
    if (this.state.pageNumber === 1) {
      return;
    }
    const page = this.state.pageNumber - 1;
    this.setState({ pageNumber: page });
  }
  nextPage = () => {
    if (this.state.pageNumber === this.state.numPages) {
      return;
    }
    const page = this.state.pageNumber + 1;
    this.setState({ pageNumber: page });
  }
  render() {
    const {
      pageNumber, numPages,
    } = this.state;
    const { urlPrint } = this.props;
    console.log('urlPrint:', urlPrint);
    const pageWidth = commonUtils.isNotEmptyNumber(document.body.clientWidth) ? 1000 : 360;
    /* 计算缩放比例(595为浏览器控制台获取到的原pdf的canvas属性的宽度，该属性导致pdf宽度无法适配页面宽度) */
    const scale = (pageWidth / 595).toFixed(2);
    return (
      <div
        className={pdfstyles.view}
      >
        <div className={pdfstyles.pageContainer}>
          <Document
            file={urlPrint}
            onLoadSuccess={this.onDocumentLoadSuccess}
          >
            <Page pageNumber={pageNumber} scale={scale} />
          </Document>
        </div>
        <div className={pdfstyles.pageTool}>
          <div className={pdfstyles.left}>
            <Icon size="md" type="left" onClick={this.lastPage} />
          </div>
          <InputItem
            value={pageNumber}
            onChange={e => this.onPageNumberChange(e)}
            type="number"
          /><div className={pdfstyles.numPages}> / {numPages}</div>
          <div className={pdfstyles.right}>
            <Icon size="md" type="right" onClick={this.nextPage} />
          </div>
        </div>
        {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
        {/* <span className="pdfClose">  <a onClick={() => window.history.back(-1)} > <Icon type="cross-circle-o" /></a>  </span> */}
      </div>
    );
  }
}

export default CommonPrintPdf;
