"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _reactNative = require("react-native");
var _reactNativeCloudCa = require("react-native-cloud-ca");
var _styles = _interopRequireDefault(require("./styles"));
var _reactRouterNative = require("react-router-native");
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 (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 _extends() { _extends = Object.assign ? Object.assign.bind() : 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); }
const GetPendingAuthorisationRequestView = props => {
  const {
    headerProps,
    authorisationPendingOptions,
    goBack,
    onDone
  } = props;
  const cloudCAProviderContext = _react.default.useContext(_reactNativeCloudCa.CloudCAProviderContext);
  const {
    themeColor
  } = cloudCAProviderContext;
  const [isLoading, setIsLoading] = (0, _react.useState)(false);
  const [isShowRequest, setIsShowRequest] = (0, _react.useState)(false);
  const [isShowError, setIsShowError] = (0, _react.useState)(false);
  const [isShowSuccess, setIsShowSuccess] = (0, _react.useState)(false);
  const [errorResponse, setErrorResponse] = (0, _react.useState)('');
  const [pendingAuthoriastion, setPendingAuthoriastion] = (0, _react.useState)();
  const [requestType, setRequestType] = (0, _react.useState)('Author');
  const [requestDecoded, setRequestDecoded] = (0, _react.useState)();
  const [authorTimeleft, setAuthorTimeleft] = (0, _react.useState)('');
  const [allResult, setAllResult] = (0, _react.useState)();
  (0, _react.useEffect)(() => {
    fetchPendingAuthorisation();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  const fetchPendingAuthorisation = async () => {
    setIsLoading(true);
    try {
      await (0, _reactNativeCloudCa.validateToken)();
      const result = await (0, _reactNativeCloudCa.getPendingAuthorisationRequest)();
      setPendingAuthoriastion(result);
      setAllResult({
        getPendingAuthorisationRequestResponse: result
      });
      if (result !== null && result !== void 0 && result.request) {
        var _authorRequest$Author, _authorRequest$Author2;
        const authorRequest = await (0, _reactNativeCloudCa.decodeRequestBase64)(result === null || result === void 0 ? void 0 : result.request);
        setRequestDecoded(authorRequest);
        getTimeleft(authorRequest === null || authorRequest === void 0 ? void 0 : (_authorRequest$Author = authorRequest.AuthorisationData) === null || _authorRequest$Author === void 0 ? void 0 : (_authorRequest$Author2 = _authorRequest$Author.ValidityPeriod) === null || _authorRequest$Author2 === void 0 ? void 0 : _authorRequest$Author2.ValidTo);
      }
      setIsLoading(false);
    } catch (error) {
      setIsShowError(true);
      setErrorResponse(`${error === null || error === void 0 ? void 0 : error.code} - ${error === null || error === void 0 ? void 0 : error.message}`);
      setIsLoading(false);
      setAllResult({
        error: error
      });
    }
  };
  const getTimeleft = validTo => {
    const now = new Date().getTime();
    const endtime = new Date(validTo).getTime();
    const secondsLeft = (endtime - now) / 1000;
    if (secondsLeft > 0) {
      const hours = Math.floor(secondsLeft / 3600);
      const minutes = Math.floor(secondsLeft % 3600 / 60);
      const seconds = Math.floor(secondsLeft % 60);
      const hourString = hours < 10 ? '0' + hours : hours;
      const minuteString = minutes < 10 ? '0' + minutes : minutes;
      const secondString = seconds < 10 ? '0' + seconds : seconds;
      const timeLeft = `${hourString}:${minuteString}:${secondString}`;
      setAuthorTimeleft(timeLeft);
    } else {
      setAuthorTimeleft('Đã hết hạn');
    }
  };
  const authorisationRequest = async () => {
    setIsShowRequest(false);
    setIsLoading(true);
    try {
      await (0, _reactNativeCloudCa.validateToken)();
      const params = {
        biometricApiType: authorisationPendingOptions === null || authorisationPendingOptions === void 0 ? void 0 : authorisationPendingOptions.biometricApiType,
        hashAlgorithm: pendingAuthoriastion === null || pendingAuthoriastion === void 0 ? void 0 : pendingAuthoriastion.hash_algorithm,
        localizedReason: authorisationPendingOptions === null || authorisationPendingOptions === void 0 ? void 0 : authorisationPendingOptions.localizedReason,
        request: pendingAuthoriastion === null || pendingAuthoriastion === void 0 ? void 0 : pendingAuthoriastion.request,
        transactionID: pendingAuthoriastion === null || pendingAuthoriastion === void 0 ? void 0 : pendingAuthoriastion.transaction_id
      };
      const result = await (0, _reactNativeCloudCa.authorisationPendingRequest)(params);
      setAllResult({
        authorisationPendingRequestResponse: result
      });
      setIsLoading(false);
      setIsShowSuccess(true);
    } catch (error) {
      setIsShowError(true);
      setErrorResponse(`${error === null || error === void 0 ? void 0 : error.code} - ${error === null || error === void 0 ? void 0 : error.message}`);
      setIsLoading(false);
      setAllResult({
        error: error
      });
    }
  };
  const cancelRequest = async () => {
    setIsShowRequest(false);
    setIsLoading(true);
    try {
      await (0, _reactNativeCloudCa.validateToken)();
      const params = {
        hashAlgorithm: pendingAuthoriastion === null || pendingAuthoriastion === void 0 ? void 0 : pendingAuthoriastion.hash_algorithm,
        request: pendingAuthoriastion === null || pendingAuthoriastion === void 0 ? void 0 : pendingAuthoriastion.request,
        transactionID: pendingAuthoriastion === null || pendingAuthoriastion === void 0 ? void 0 : pendingAuthoriastion.transaction_id
      };
      const result = await (0, _reactNativeCloudCa.cancelPendingRequest)(params);
      setAllResult({
        cancelPendingRequestResponse: result
      });
      setIsLoading(false);
      setIsShowSuccess(true);
    } catch (error) {
      setIsShowError(true);
      setErrorResponse(`${error === null || error === void 0 ? void 0 : error.code} - ${error === null || error === void 0 ? void 0 : error.message}`);
      setIsLoading(false);
      setAllResult({
        error: error
      });
    }
  };
  const handleCancelRequest = () => {
    setRequestType('Cancel');
    setIsShowRequest(true);
  };
  const handleAcceptRequest = () => {
    setRequestType('Author');
    setIsShowRequest(true);
  };
  const onConfirmOnPress = () => {
    if (requestType === 'Author') {
      authorisationRequest();
    } else if (requestType === 'Cancel') {
      cancelRequest();
    }
  };
  const handleDone = () => {
    setIsShowSuccess(false);
    fetchPendingAuthorisation();
    onDone === null || onDone === void 0 ? void 0 : onDone(allResult);
  };
  const handleError = () => {
    setIsShowError(false);
    onDone === null || onDone === void 0 ? void 0 : onDone(allResult);
  };
  const renderDocumentItem = (item, index) => {
    return /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
      numberOfLines: 1,
      key: index,
      style: _styles.default.documentItemText
    }, `${index + 1}. ${item === null || item === void 0 ? void 0 : item.Name}`);
  };
  const renderListDocuments = () => {
    var _requestDecoded$Autho, _requestDecoded$Autho2, _documents$slice;
    const documents = requestDecoded === null || requestDecoded === void 0 ? void 0 : (_requestDecoded$Autho = requestDecoded.AuthorisationData) === null || _requestDecoded$Autho === void 0 ? void 0 : (_requestDecoded$Autho2 = _requestDecoded$Autho.Documents) === null || _requestDecoded$Autho2 === void 0 ? void 0 : _requestDecoded$Autho2.Document;
    return /*#__PURE__*/_react.default.createElement(_reactNative.View, {
      style: _styles.default.listDocumentContainer
    }, /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
      style: _styles.default.totalFileDocuments
    }, `Danh sách tài liệu ký (${documents && (documents === null || documents === void 0 ? void 0 : documents.length)})`), documents === null || documents === void 0 ? void 0 : (_documents$slice = documents.slice(0, 3)) === null || _documents$slice === void 0 ? void 0 : _documents$slice.map((item, index) => renderDocumentItem(item, index)), documents && (documents === null || documents === void 0 ? void 0 : documents.length) > 3 && /*#__PURE__*/_react.default.createElement(_reactRouterNative.Link, {
      to: `/listDocumentView`,
      underlayColor: "rgba(0,0,0,.01)"
    }, /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
      numberOfLines: 1,
      style: _styles.default.viewMoreText
    }, "Xem th\xEAm")));
  };
  const renderDocuments = () => {
    var _requestDecoded$Autho3, _requestDecoded$Autho4, _Name;
    const document = requestDecoded === null || requestDecoded === void 0 ? void 0 : (_requestDecoded$Autho3 = requestDecoded.AuthorisationData) === null || _requestDecoded$Autho3 === void 0 ? void 0 : (_requestDecoded$Autho4 = _requestDecoded$Autho3.Documents) === null || _requestDecoded$Autho4 === void 0 ? void 0 : _requestDecoded$Autho4.Document;
    if (document !== null && document !== void 0 && document.length) {
      return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, renderListDocuments());
    } else if (document !== null && document !== void 0 && (_Name = document.Name) !== null && _Name !== void 0 && _Name.length) {
      const singleDocument = document;
      return /*#__PURE__*/_react.default.createElement(_reactNativeCloudCa.InfoField, {
        title: "T\xEAn t\xE0i li\u1EC7u",
        info: singleDocument === null || singleDocument === void 0 ? void 0 : singleDocument.Name
      });
    } else {
      return /*#__PURE__*/_react.default.createElement(_reactNative.View, null);
    }
  };
  const renderRequestInfo = () => {
    var _requestDecoded$Autho5;
    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_reactNative.View, null, renderDocuments(), /*#__PURE__*/_react.default.createElement(_reactNativeCloudCa.InfoField, {
      title: "Ng\u01B0\u1EDDi chia s\u1EBB",
      info: requestDecoded === null || requestDecoded === void 0 ? void 0 : (_requestDecoded$Autho5 = requestDecoded.AuthorisationData) === null || _requestDecoded$Autho5 === void 0 ? void 0 : _requestDecoded$Autho5.OriginatorID
    }), /*#__PURE__*/_react.default.createElement(_reactNativeCloudCa.InfoField, {
      title: "Th\u1EDDi gian x\xE1c th\u1EF1c k\xFD c\xF2n l\u1EA1i",
      info: authorTimeleft
    })), /*#__PURE__*/_react.default.createElement(_reactNative.View, {
      style: _styles.default.buttonContainer
    }, /*#__PURE__*/_react.default.createElement(_reactNativeCloudCa.OutlineButton, {
      label: "Hu\u1EF7 y\xEAu c\u1EA7u",
      style: _styles.default.cancelButton,
      onPress: handleCancelRequest
    }), /*#__PURE__*/_react.default.createElement(_reactNativeCloudCa.PrimaryButton, {
      label: "U\u1EF7 quy\u1EC1n",
      style: _styles.default.confirmButton,
      onPress: handleAcceptRequest
    })));
  };
  const renderEmptyRequest = () => {
    return /*#__PURE__*/_react.default.createElement(_reactNative.View, {
      style: _styles.default.emptyContainer
    }, /*#__PURE__*/_react.default.createElement(_reactNative.Image, {
      style: _styles.default.emptyImage,
      source: require('../../asset/image/IMG_EMPTY_REQUEST.png')
    }), /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
      style: _styles.default.emptyText
    }, "Kh\xF4ng c\xF3 y\xEAu c\u1EA7u c\u1EA7n k\xFD. "), /*#__PURE__*/_react.default.createElement(_reactNative.TouchableOpacity, {
      onPress: fetchPendingAuthorisation
    }, /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
      style: [_styles.default.reloadRequestText, {
        color: themeColor
      }]
    }, "T\u1EA3i l\u1EA1i y\xEAu c\u1EA7u")));
  };
  const rootViewContainer = () => {
    var _pendingAuthoriastion;
    return /*#__PURE__*/_react.default.createElement(_reactNative.View, {
      style: _styles.default.container
    }, /*#__PURE__*/_react.default.createElement(_reactNativeCloudCa.Header, _extends({}, headerProps, {
      label: "U\u1EF7 quy\u1EC1n x\xE1c th\u1EF1c",
      goBack: goBack
    })), /*#__PURE__*/_react.default.createElement(_reactNative.View, {
      style: _styles.default.contentContainer
    }, pendingAuthoriastion !== null && pendingAuthoriastion !== void 0 && (_pendingAuthoriastion = pendingAuthoriastion.request) !== null && _pendingAuthoriastion !== void 0 && _pendingAuthoriastion.length ? renderRequestInfo() : renderEmptyRequest()), /*#__PURE__*/_react.default.createElement(_reactNativeCloudCa.Dialogue, {
      visible: isShowSuccess,
      onClose: handleDone
    }, /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
      style: _styles.default.contentStyle
    }, requestType === 'Author' ? 'Bạn đã uỷ quyền xác thực thành công.' : 'Bạn đã huỷ yêu cầu xác thực thành công.')), /*#__PURE__*/_react.default.createElement(_reactNativeCloudCa.Dialogue, {
      modalType: "ERROR",
      onClose: handleError,
      visible: isShowError
    }, /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
      style: _styles.default.contentStyle
    }, errorResponse)), /*#__PURE__*/_react.default.createElement(_reactNativeCloudCa.DialogueConfirm, {
      title: requestType === 'Cancel' ? 'Huỷ yêu cầu xác thực' : 'Uỷ quyền xác thực',
      closeOnPress: () => setIsShowRequest(false),
      closeLabel: "B\u1ECF qua",
      confirmOnPress: onConfirmOnPress,
      confirmLabel: "Ti\u1EBFp t\u1EE5c",
      confirmDisable: isLoading,
      visible: isShowRequest
    }, /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
      style: _styles.default.contentStyle
    }, requestType === 'Cancel' ? 'Bạn có chắc chắn muốn huỷ yêu cầu xác thực không?' : 'Bạn có chắc chắn muốn uỷ quyền xác thực cho yêu cầu này không?')), isLoading && /*#__PURE__*/_react.default.createElement(_reactNativeCloudCa.Loading, null));
  };
  const renderListDocumentView = () => {
    var _requestDecoded$Autho6, _requestDecoded$Autho7;
    return /*#__PURE__*/_react.default.createElement(_reactNativeCloudCa.ListDocumentView, {
      documents: requestDecoded === null || requestDecoded === void 0 ? void 0 : (_requestDecoded$Autho6 = requestDecoded.AuthorisationData) === null || _requestDecoded$Autho6 === void 0 ? void 0 : (_requestDecoded$Autho7 = _requestDecoded$Autho6.Documents) === null || _requestDecoded$Autho7 === void 0 ? void 0 : _requestDecoded$Autho7.Document
    });
  };
  return /*#__PURE__*/_react.default.createElement(_reactRouterNative.NativeRouter, null, /*#__PURE__*/_react.default.createElement(_reactRouterNative.Routes, null, /*#__PURE__*/_react.default.createElement(_reactRouterNative.Route, {
    path: "/",
    Component: rootViewContainer
  }), /*#__PURE__*/_react.default.createElement(_reactRouterNative.Route, {
    path: "/listDocumentView",
    Component: renderListDocumentView
  })));
};
var _default = GetPendingAuthorisationRequestView;
exports.default = _default;
//# sourceMappingURL=GetPendingAuthorisationRequestView.js.map