function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure 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 _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import React, { useState, useContext } from 'react';
import { useMount, useUnmount, useUpdateEffect } from 'ahooks';
import { EHR_SERVICE } from "../_util/constants";
import { ConvertStatus } from "./utils/types";
import { download, Ajax } from "./utils/index";
import { CLASS_CLS, PreviewType } from "./type";
import FileContext from "./context/ConfigContext";
import PdfViewer from "./PdfViewer";
import { ConfigContext } from "../config-provider/context";
import "./FilePreview.less";
var TIME_LIMIT = 10000;
var timer;
var FilePreview = function FilePreview(props) {
  var componentContext = useContext(ConfigContext);
  var uiLocale = componentContext.uiLocale;
  var _useContext = useContext(FileContext),
    getPrettyCls = _useContext.getPrettyCls;
  var _props$allowDownload = props.allowDownload,
    allowDownload = _props$allowDownload === void 0 ? true : _props$allowDownload,
    className = props.className,
    _props$convertStatus = props.convertStatus,
    convertStatus = _props$convertStatus === void 0 ? ConvertStatus.PENDING : _props$convertStatus,
    _props$file = props.file,
    file = _props$file === void 0 ? {} : _props$file,
    forwardRef = props.forwardRef,
    locale = props.locale,
    _props$startPage = props.startPage,
    startPage = _props$startPage === void 0 ? 1 : _props$startPage;
  var _useState = useState(convertStatus),
    _useState2 = _slicedToArray(_useState, 2),
    currentStatus = _useState2[0],
    setCurrentStatus = _useState2[1];
  var _useState3 = useState(1),
    _useState4 = _slicedToArray(_useState3, 2),
    pageCount = _useState4[0],
    setPageCount = _useState4[1];

  // @ts-ignore
  var prettyCls = getPrettyCls(CLASS_CLS);
  var id = file.transformId,
    _file$name = file.name,
    name = _file$name === void 0 ? '' : _file$name,
    _file$url = file.url,
    url = _file$url === void 0 ? '' : _file$url;
  var type = name.includes('xls') ? PreviewType.IFRAME : PreviewType.PDF;
  var classCls = prettyCls({}, '', CLASS_CLS);
  var onDownload = function onDownload() {
    download(url, name);
  };
  var onClearTimer = function onClearTimer() {
    if (timer) {
      window.clearInterval(timer);
    }
  };
  var getTotalPage = function getTotalPage(id) {
    Ajax.get(EHR_SERVICE + '/api/office/km/file/convert/status/' + id, function (res) {
      var _ref = res.data || {},
        totalPages = _ref.totalPages,
        status = _ref.status;
      if (totalPages) {
        setPageCount(totalPages);
      }
      if ("".concat(status) !== "".concat(ConvertStatus.PENDING)) {
        onClearTimer();
      }
      if ("".concat(status) === "".concat(ConvertStatus.SUCCESS)) {
        setCurrentStatus(ConvertStatus.SUCCESS);
      } else if ("".concat(status) === "".concat(ConvertStatus.FAIL)) {
        setCurrentStatus(ConvertStatus.FAIL);
      }
    }, function () {
      console.error(uiLocale.Preview.queryError);
    });
  };
  var getConvertStatus = function getConvertStatus() {
    if (id && (currentStatus === ConvertStatus.PENDING || convertStatus === ConvertStatus.PENDING)) {
      getTotalPage(id);
    }
  };
  useMount(function () {
    if (id) {
      if (currentStatus === ConvertStatus.PENDING) {
        getConvertStatus();
      } else if (currentStatus === ConvertStatus.SUCCESS && type === PreviewType.PDF) {
        getTotalPage(id);
      }
    }
    if (forwardRef !== null && forwardRef !== void 0 && forwardRef.current) {
      forwardRef.current.onClearTimer = onClearTimer;
    }
    timer = window.setInterval(getConvertStatus, TIME_LIMIT);
  });
  useUnmount(function () {
    onClearTimer();
  });

  // 切换
  useUpdateEffect(function () {
    setPageCount(0);
    setCurrentStatus(convertStatus);
    onClearTimer();
    if (convertStatus === ConvertStatus.PENDING) {
      getConvertStatus();
      timer = window.setInterval(getConvertStatus, TIME_LIMIT);
    } else if (convertStatus === ConvertStatus.SUCCESS && type === PreviewType.PDF) {
      id && getTotalPage(id);
    }
  }, [id]);
  return /*#__PURE__*/React.createElement("div", {
    className: "".concat(classCls, " ").concat(className || ''),
    ref: forwardRef
  }, currentStatus == ConvertStatus.PENDING && id && /*#__PURE__*/React.createElement("div", {
    className: "".concat(CLASS_CLS, "-tip")
  }, /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("span", null, name, " - ", uiLocale.Preview.convertWaiting))), (currentStatus == ConvertStatus.FAIL || !id) && /*#__PURE__*/React.createElement("div", {
    className: "".concat(CLASS_CLS, "-tip")
  }, /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("span", null, name, " - ", uiLocale.Preview.convertError))), currentStatus === ConvertStatus.SUCCESS && id && /*#__PURE__*/React.createElement("div", {
    className: "".concat(CLASS_CLS, "-container")
  }, type === PreviewType.IFRAME && /*#__PURE__*/React.createElement("div", {
    className: "".concat(CLASS_CLS, "-tip")
  }, /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("span", null, name)), /*#__PURE__*/React.createElement("iframe", {
    frameBorder: "no",
    id: "".concat(id),
    title: name,
    src: file.url
  })), type === PreviewType.PDF && /*#__PURE__*/React.createElement(PdfViewer, {
    allowDownload: allowDownload,
    file: id,
    host: EHR_SERVICE,
    locale: locale,
    pageCount: pageCount,
    startPage: startPage,
    title: name,
    onDownload: onDownload,
    onPageChanged: function onPageChanged(page) {
      return console.log("page changed: ".concat(page));
    },
    onPageLoaded: function onPageLoaded(page) {
      return console.log("page loaded: ".concat(page));
    },
    onToggleControls: function onToggleControls(visible) {
      return console.log("controls visible: ".concat(visible));
    }
  })));
};
export default FilePreview;