'use strict';

exports.__esModule = true;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _instance = require('./instance.js');

var _instance2 = _interopRequireDefault(_instance);

var _betterScroll = require('better-scroll');

var _betterScroll2 = _interopRequireDefault(_betterScroll);

var _instance3 = require('../Context/instance.js');

var _instance4 = _interopRequireDefault(_instance3);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

var timeout = null;

var PDFView = (0, _react.forwardRef)(function (_ref, ref) {
  var insertPageElements = _ref.insertPageElements,
      pictures = _ref.pictures,
      src = _ref.src,
      cMapUrl = _ref.cMapUrl,
      _ref$params = _ref.params,
      params = _ref$params === undefined ? {} : _ref$params,
      zoom = _ref.zoom,
      _ref$wrapperAttribute = _ref.wrapperAttribute,
      wrapperAttribute = _ref$wrapperAttribute === undefined ? {} : _ref$wrapperAttribute,
      others = _objectWithoutProperties(_ref, ['insertPageElements', 'pictures', 'src', 'cMapUrl', 'params', 'zoom', 'wrapperAttribute']);

  var refEl = (0, _react.useRef)(null);
  (0, _react.useImperativeHandle)(ref, function () {
    return refEl.current;
  });
  // context
  var context = (0, _react.useContext)(_instance4.default) || {};
  var locale = context.locale || function (key) {
    return key || '';
  };
  // 总页数

  var _useState = (0, _react.useState)(0),
      total = _useState[0],
      setTotal = _useState[1];
  // 初始化


  (0, _react.useEffect)(function () {
    init();
  }, []); // eslint-disable-line

  // 更新src或者pictures
  function usePrevious(value) {
    var ref = (0, _react.useRef)();
    (0, _react.useEffect)(function () {
      ref.current = value;
    });
    return ref.current;
  }
  var prevSrc = usePrevious(src);
  var prevPictures = usePrevious(pictures);

  (0, _react.useEffect)(function () {
    // 修改PDF原文件, 刷新整个页面, 从第1页开始重新渲染
    if (refEl.current && refEl.current.instance && (src !== prevSrc || JSON.stringify(pictures) !== JSON.stringify(prevPictures))) {
      init();
    }
  }, [src, pictures]); // eslint-disable-line

  // 一页加载完成后回调
  function _onLoad(s) {
    console.log('全部加载完成');
    if (params.onLoad) params.onLoad(s);
    if (zoom) {
      // 若允许放大, 使用better-scroll
      if (refEl.current.bscroll) {
        console.log('加载完成, bscroll刷新');
        refEl.current.bscroll.finishPullUp();
        refEl.current.bscroll.refresh();
        return;
      }
      refEl.current.bscroll = new _betterScroll2.default('.pdf-container', {
        scrollX: true,
        zoom: {
          start: 1,
          min: 1,
          max: 4
        },
        probeType: 2,
        pullUpLoad: {
          threshold: 10
        }
      });
      // 上拉到底部刷新
      refEl.current.bscroll.on('pullingUp', function () {
        refEl.current.instance.addPages();
      });
    } else {
      // 不允许放大, 则使用原生滚动条
      // 上拉到底部
      if (!s.container.getAttribute('data-scroll')) {
        s.container.addEventListener('scroll', onScroll, false);
        s.container.setAttribute('data-scroll', '1');
      }
    }
  }

  // 初始化PDF
  function init() {
    if (!src && !pictures) {
      console.warn('SeedsUI: PDFView请传入src或者pictures');
      return;
    }
    // 如果设置了插入元素, 则需要通过react Node渲染完成后, 再实例化
    if (insertPageElements && insertPageElements.length && src) {
      new _instance2.default().getPDF(src, {
        success: function success(pdf) {
          total = pdf.total;
          setTotal(total);
          instance(total);
        },
        fail: function fail() {
          instance();
        }
      });
    } else if (insertPageElements && insertPageElements.length && pictures) {
      total = pictures.length;
      setTotal(total);
      instance(total);
    } else {
      instance();
    }
  }
  // 实例化和更新
  function instance(rows) {
    // 更新
    if (refEl.current.instance) {
      // 更新一页的条数和src
      refEl.current.instance.update({
        rows: rows,
        src: src
      });
      return;
    }
    // 实例化
    refEl.current.instance = new _instance2.default(refEl.current, _extends({
      loadHTML: locale['in_loading'] || '加载中',
      errorHTML: locale['hint_file_failed_to_load'] || '文件加载失败',
      nodataHTML: locale['no_data'] || '暂无数据'
    }, params, {
      pictures: pictures,
      src: src,
      cMapUrl: cMapUrl,
      rows: rows || params.rows,
      onLoad: function onLoad(s) {
        _onLoad(s);
      }
    }));
  }
  // 当不允许放大缩小使用原生滚动时, 滚动到底部加载下一页
  function onScroll(e) {
    var target = e.target;
    var clientHeight = target.clientHeight;
    var scrollHeight = target.scrollHeight;
    var scrollTop = target === document.body ? document.documentElement.scrollTop : target.scrollTop;
    if (scrollTop + clientHeight >= scrollHeight - 2) {
      // 刷新
      if (timeout) {
        window.clearTimeout(timeout);
      }
      timeout = setTimeout(function () {
        refEl.current.instance.addPages();
      }, 500);
    }
  }
  // 滚动到页数
  function scrollToPage(pageIndex) {
    if (!pageIndex || isNaN(pageIndex) || Number(pageIndex) < 1) return;
    var pages = refEl.current.querySelectorAll('.pdf-page');
    var page = pages[Number(pageIndex) - 1];
    if (!page) return;
    if (refEl.current.bscroll) {
      refEl.current.bscroll.scrollToElement(page);
    } else {
      refEl.current.scrollTop = page.offsetTop;
    }
  }
  if (refEl.current) {
    refEl.current.scrollToPage = scrollToPage;
  }
  // 设置total则不分页
  function getTotalDOM(total) {
    var insertPageElements = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
    var pageFeatureClass = arguments[2];

    if (!src && !pictures) {
      return null;
    }
    if (!total) return null;
    var DOM = [];
    for (var i = 1; i <= total; i++) {
      var insertDOM = [];
      for (var _iterator = insertPageElements, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
        var _ref2;

        if (_isArray) {
          if (_i >= _iterator.length) break;
          _ref2 = _iterator[_i++];
        } else {
          _i = _iterator.next();
          if (_i.done) break;
          _ref2 = _i.value;
        }

        var pageEl = _ref2;

        if (pageEl && pageEl.page && Number(pageEl.page) === i && pageEl.element) insertDOM.push(pageEl.element);
      }
      DOM.push(_react2.default.createElement(
        'div',
        { key: i, className: 'pdf-page' + (pageFeatureClass ? ' ' + pageFeatureClass : '') },
        _react2.default.createElement(
          'div',
          { className: 'pdf-page-draw' },
          _react2.default.createElement('canvas', { className: 'pdf-page-canvas' }),
          _react2.default.createElement('img', { className: 'pdf-page-img', alt: '' }),
          _react2.default.createElement(
            'div',
            { className: 'pdf-page-elements' },
            insertDOM
          )
        ),
        _react2.default.createElement('img', { alt: '', className: 'pdf-page-img hide' }),
        _react2.default.createElement(
          'div',
          { className: 'pdf-page-load' },
          params.loadHTML !== undefined ? params.loadHTML : locale['in_loading'] || '加载中'
        ),
        _react2.default.createElement(
          'div',
          { className: 'pdf-page-error hide' },
          params.errorHTML !== undefined ? params.errorHTML : locale['hint_file_failed_to_load'] || '文件加载失败'
        ),
        _react2.default.createElement(
          'div',
          { className: 'pdf-page-nodata hide' },
          params.nodataHTML !== undefined ? params.nodataHTML : locale['no_date'] || '暂无数据'
        )
      ));
    }
    return DOM;
  }

  return _react2.default.createElement(
    'div',
    _extends({ ref: refEl }, others, { className: 'pdf-container' + (others.className ? ' ' + others.className : '') + (zoom ? '' : ' scroll') }),
    _react2.default.createElement(
      'div',
      _extends({}, wrapperAttribute, { className: 'pdf-wrapper' + (wrapperAttribute.className ? ' ' + wrapperAttribute.className : '') }),
      getTotalDOM(total, insertPageElements, params.pageFeatureClass)
    )
  );
});

exports.default = PDFView;
module.exports = exports['default'];