"use strict";

exports.__esModule = true;
exports["default"] = void 0;

var _react = _interopRequireWildcard(require("react"));

var _instance = _interopRequireDefault(require("./instance.js"));

var _betterScroll = _interopRequireDefault(require("better-scroll"));

var _instance2 = _interopRequireDefault(require("../Context/instance.js"));

var _excluded = ["insertPageElements", "pictures", "src", "cMapUrl", "params", "zoom", "wrapperAttribute"];

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

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _extends() { _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; }; return _extends.apply(this, arguments); }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } 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 === void 0 ? {} : _ref$params,
      zoom = _ref.zoom,
      _ref$wrapperAttribute = _ref.wrapperAttribute,
      wrapperAttribute = _ref$wrapperAttribute === void 0 ? {} : _ref$wrapperAttribute,
      others = _objectWithoutPropertiesLoose(_ref, _excluded);

  var refEl = (0, _react.useRef)(null);
  (0, _react.useImperativeHandle)(ref, function () {
    return refEl.current;
  }); // context

  var context = (0, _react.useContext)(_instance2["default"]) || {};

  var locale = context.locale || function (remark) {
    return remark || '';
  }; // 总页数


  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 _betterScroll["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 _instance["default"]().getPDF(src, {
        onSuccess: function onSuccess(s, pdf) {
          total = pdf.total;
          setTotal(total);
          instance(total);
        },
        onError: function onError() {
          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 _instance["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, insertPageElements, pageFeatureClass) {
    if (insertPageElements === void 0) {
      insertPageElements = [];
    }

    if (!src && !pictures) {
      return null;
    }

    if (!total) return null;
    var DOM = [];

    for (var i = 1; i <= total; i++) {
      var insertDOM = [];

      for (var _iterator = _createForOfIteratorHelperLoose(insertPageElements), _step; !(_step = _iterator()).done;) {
        var pageEl = _step.value;
        if (pageEl && pageEl.page && Number(pageEl.page) === i && pageEl.element) insertDOM.push(pageEl.element);
      }

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

    return DOM;
  }

  return /*#__PURE__*/_react["default"].createElement("div", _extends({
    ref: refEl
  }, others, {
    className: "pdf-container" + (others.className ? ' ' + others.className : '') + (zoom ? '' : ' scroll')
  }), /*#__PURE__*/_react["default"].createElement("div", _extends({}, wrapperAttribute, {
    className: "pdf-wrapper" + (wrapperAttribute.className ? ' ' + wrapperAttribute.className : '')
  }), getTotalDOM(total, insertPageElements, params.pageFeatureClass)));
});
var _default = PDFView;
exports["default"] = _default;
module.exports = exports.default;