'use strict';

exports.__esModule = true;
exports.default = undefined;

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 _class, _temp;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

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

var _instance2 = _interopRequireDefault(_instance);

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

var _betterScroll2 = _interopRequireDefault(_betterScroll);

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; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var PDFView = (_temp = _class = function (_Component) {
  _inherits(PDFView, _Component);

  // 全局配置
  function PDFView(props, context) {
    _classCallCheck(this, PDFView);

    var _this = _possibleConstructorReturn(this, _Component.call(this, props, context));

    _this.onLoad = function (s) {
      var _this$props = _this.props,
          zoom = _this$props.zoom,
          _this$props$params = _this$props.params,
          params = _this$props$params === undefined ? {} : _this$props$params;

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

    _this.init = function () {
      var _this$props2 = _this.props,
          pictures = _this$props2.pictures,
          src = _this$props2.src,
          insertPageElements = _this$props2.insertPageElements;

      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) {
            _this.setState({
              total: pdf.total
            }, function () {
              _this.instance(_this.state.total);
            });
          }
        });
      } else if (insertPageElements && insertPageElements.length && pictures) {
        _this.setState({
          total: pictures.length
        }, function () {
          _this.instance(_this.state.total);
        });
      } else {
        _this.instance();
      }
    };

    _this.instance = function (rows) {
      // 全局配置
      var _this$context$locale = _this.context.locale,
          locale = _this$context$locale === undefined ? {} : _this$context$locale;
      var _this$props3 = _this.props,
          pictures = _this$props3.pictures,
          src = _this$props3.src,
          cMapUrl = _this$props3.cMapUrl,
          _this$props3$params = _this$props3.params,
          params = _this$props3$params === undefined ? {} : _this$props3$params;

      _this.instance = new _instance2.default(_this.$el, _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) {
          _this.onLoad(s);
        }
      }));
    };

    _this.onScroll = function (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 (_this.timeout) {
          window.clearTimeout(_this.timeout);
        }
        _this.timeout = setTimeout(function () {
          _this.instance.addPages();
        }, 500);
      }
    };

    _this.scrollToPage = function (pageIndex) {
      if (!pageIndex || isNaN(pageIndex) || Number(pageIndex) < 1) return;
      var pages = _this.$el.querySelectorAll('.pdf-page');
      var page = pages[Number(pageIndex) - 1];
      if (!page) return;
      if (_this.bscroll) {
        _this.bscroll.scrollToElement(page);
      } else {
        _this.$el.scrollTop = page.offsetTop;
      }
    };

    _this.getTotalDOM = function (total) {
      var insertPageElements = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
      var pageFeatureClass = arguments[2];

      // 全局配置
      var _this$context$locale2 = _this.context.locale,
          locale = _this$context$locale2 === undefined ? {} : _this$context$locale2;
      var _this$props$params2 = _this.props.params,
          params = _this$props$params2 === undefined ? {} : _this$props$params2;

      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 _ref;

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

          var pageEl = _ref;

          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;
    };

    _this.state = {
      total: 0
    };
    return _this;
  }
  // insertPageElements = [{
  //   page: 1,
  //   element: <input/>
  // }]


  PDFView.prototype.componentDidUpdate = function componentDidUpdate(prevProps) {
    var _props = this.props,
        pictures = _props.pictures,
        src = _props.src,
        cMapUrl = _props.cMapUrl,
        _props$params = _props.params,
        params = _props$params === undefined ? {} : _props$params;
    // 修改PDF原文件, 刷新整个页面, 从第1页开始重新渲染

    if (src && src !== prevProps.src || pictures && pictures !== prevProps.pictures) {
      if (!this.instance) {
        this.init();
      } else {
        if (this.instance.update) {
          this.instance.update(_extends({}, params, {
            pictures: pictures,
            src: src,
            cMapUrl: cMapUrl
          }));
        }
      }
    }
    // 如果修改参数的话, 只需要更新参数即可
    if (JSON.stringify(params) !== JSON.stringify(prevProps.params)) {
      if (!this.instance) {
        this.init();
      } else {
        this.instance.updateParams(params);
      }
    }
  };

  PDFView.prototype.componentDidMount = function componentDidMount() {
    this.init();
  };
  // 一页加载完成后回调

  // 实例化

  // 当不允许放大缩小使用原生滚动时, 滚动到底部加载下一页

  // 滚动到页数

  // 设置total则不分页


  PDFView.prototype.render = function render() {
    var _this2 = this;

    var _props2 = this.props,
        insertPageElements = _props2.insertPageElements,
        pictures = _props2.pictures,
        src = _props2.src,
        cMapUrl = _props2.cMapUrl,
        _props2$params = _props2.params,
        params = _props2$params === undefined ? {} : _props2$params,
        zoom = _props2.zoom,
        _props2$wrapperAttrib = _props2.wrapperAttribute,
        wrapperAttribute = _props2$wrapperAttrib === undefined ? {} : _props2$wrapperAttrib,
        others = _objectWithoutProperties(_props2, ['insertPageElements', 'pictures', 'src', 'cMapUrl', 'params', 'zoom', 'wrapperAttribute']);

    if (!src && !pictures) {
      return null;
    }
    return _react2.default.createElement(
      'div',
      _extends({ ref: function ref(el) {
          _this2.$el = el;
        } }, others, { className: 'pdf-container' + (others.className ? ' ' + others.className : '') + (zoom ? '' : ' scroll') }),
      _react2.default.createElement(
        'div',
        _extends({}, wrapperAttribute, { className: 'pdf-wrapper' + (wrapperAttribute.className ? ' ' + wrapperAttribute.className : '') }),
        this.getTotalDOM(this.state.total, insertPageElements, params.pageFeatureClass)
      )
    );
  };

  return PDFView;
}(_react.Component), _class.contextTypes = {
  locale: _propTypes2.default.object,
  portal: _propTypes2.default.object
}, _class.defaultProps = {}, _temp);
exports.default = PDFView;
PDFView.propTypes = process.env.NODE_ENV !== "production" ? {
  insertPageElements: _propTypes2.default.array, // 插入页面元素, 有此属性时将不分页
  pictures: _propTypes2.default.array, // 图片地址
  src: _propTypes2.default.string, // pdf地址或data:application/pdf;base64,开头的base64pdf流文件
  cMapUrl: _propTypes2.default.string, // 设置cMapUrl, 解决中文不显示的问题
  params: _propTypes2.default.object, // 设置实例化参数
  // params: {
  //   rows: 5, // 分页, 一页的条数
  //   errorHTML: '文件加载失败', // 加载错误时显示的信息
  //   loadHTML: '加载中', // 加载时显示的信息
  //   nodataHTML: '暂无数据', // 暂无数据
  //   pdfLib: '//res.waiqin365.com/d/seedsui/pdfview/pdf.js', // pdf.js库
  //   pdfWorkLib: '//res.waiqin365.com/d/seedsui/pdfview/pdf.worker.js' // pdf.work.js库
  // }
  zoom: _propTypes2.default.bool, // 是否允许放大缩小
  wrapperAttribute: _propTypes2.default.object } : {};
module.exports = exports['default'];