"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

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

var _popup = _interopRequireDefault(require("../../../components/popup"));

var _getLocale = require("../../../utils/getLocale");

var _tooltip = _interopRequireDefault(require("../../../components/tooltip"));

var _dialog = _interopRequireDefault(require("../../../components/dialog"));

var _titaUi = require("tita-ui");

var _rcUpload = _interopRequireDefault(require("rc-upload"));

var _toast = _interopRequireDefault(require("../../../components/toast"));

var _helpers = require("../../../utils/helpers");

var _platform = require("../../../utils/platform");

var _precls = require("../precls");

require("./index.css");

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 _objectDestructuringEmpty(obj) { if (obj == null) throw new TypeError("Cannot destructure undefined"); }

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 = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

var preCls = 'okr-import';
var OkrImportModal = /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
  var _useState = (0, _react.useState)(false),
      _useState2 = _slicedToArray(_useState, 2),
      dialogVisible = _useState2[0],
      setDialogVisible = _useState2[1];

  var _useState3 = (0, _react.useState)(),
      _useState4 = _slicedToArray(_useState3, 2),
      file = _useState4[0],
      setFile = _useState4[1];

  var onClose = function onClose() {
    setDialogVisible(false);
  };

  (0, _react.useImperativeHandle)(ref, function () {
    return {
      showOkrImport: function showOkrImport() {
        return setDialogVisible(true);
      },
      closeOkrImport: function closeOkrImport() {
        return setDialogVisible(false);
      }
    };
  });

  var downloadTemplate = function downloadTemplate() {
    window.open((0, _helpers.getApiUrl)("import/okrTemplate"), (0, _platform.isFeishu)(true) || (0, _platform.isDD)(true) ? '_self' : '_blank');
  };

  var validateFileType = function validateFileType(file) {
    if (!/\.xls(x)?$/.test(file.name)) {
      _toast["default"].Error('暂不支持此文件类型，请上传 Excel 文件格式');

      return false;
    }

    setFile(file);
    return false;
  };

  var clearFile = function clearFile() {
    return setFile(undefined);
  };

  var submitFileHandler = function submitFileHandler() {
    if (file) {
      var formData = new FormData(); // FormData 对象
      // @ts-ignore

      formData.append('file', file);
      var url = (0, _helpers.getApiUrl)("okr/import");
      var xhr = new XMLHttpRequest(); //创建xhr

      xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
          var result = JSON.parse(xhr.responseText); // 上传成功接口返回数据

          if (result.Code === 1) {
            setFile(undefined);
            onClose();

            _toast["default"].Success(result.Message || '上传成功');
          } else {
            _toast["default"].Error(result.Message || '上传失败，请联系客服或重试');
          }
        } else {// Toast.Error(`${xhr.status}:上传出错`)
        }
      };

      xhr.open('POST', url, true);
      xhr.send(formData); //开始上传，发送form数据
    } else {
      _toast["default"].Error('请至少上传一个文件');
    }
  };

  return /*#__PURE__*/_react["default"].createElement(_dialog["default"], {
    destroyOnClose: true,
    noHeadLine: true,
    noFooterLine: true,
    onCancel: onClose,
    onClose: onClose,
    onOk: submitFileHandler,
    title: (0, _getLocale.getLocale)('Per_Ma_form_BatchImport'),
    visible: dialogVisible,
    width: 455
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: preCls
  }, /*#__PURE__*/_react["default"].createElement("div", null, (0, _getLocale.getLocale)('OKR_ComAll_DimporttemplatOKR'), /*#__PURE__*/_react["default"].createElement(_titaUi.Button, {
    type: "border",
    shape: "round",
    size: "s",
    style: {
      height: '32px',
      padding: '0 13px',
      fontWeight: 500,
      borderRadius: 16
    },
    onClick: downloadTemplate
  }, (0, _getLocale.getLocale)('Per_ID_DownTemp'))), /*#__PURE__*/_react["default"].createElement("div", {
    style: {
      marginTop: 14
    }
  }, (0, _getLocale.getLocale)('Per_ID_Uploadtemfile'), /*#__PURE__*/_react["default"].createElement(_rcUpload["default"], {
    beforeUpload: validateFileType
  }, /*#__PURE__*/_react["default"].createElement(_titaUi.Button, {
    shape: "round",
    type: "border",
    size: "s",
    style: {
      height: '32px',
      padding: '0 13px',
      fontWeight: 500,
      borderRadius: 16
    }
  }, file ? (0, _getLocale.getLocale)('Set_PI_Reupload') : (0, _getLocale.getLocale)('Pro_page_File_Butt_UploadFolder')))), !!file && /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__selected-file")
  }, /*#__PURE__*/_react["default"].createElement("img", {
    src: require("../img/excel.svg")
  }), /*#__PURE__*/_react["default"].createElement("span", null, file.name), /*#__PURE__*/_react["default"].createElement("i", {
    className: "tu-icon-circle",
    onClick: clearFile
  }))));
});

var OkrImport = function OkrImport(_ref) {
  _objectDestructuringEmpty(_ref);

  // const [dialogVisible, setDialogVisible] = useState(false);
  var popupRef = (0, _react.useRef)();
  var dialogRef = (0, _react.useRef)();

  var openOperateRecordPush = function openOperateRecordPush() {
    if (popupRef.current) {
      // @ts-ignore
      popupRef.current.close();
    }

    if (dialogRef.current) {
      // @ts-ignore
      dialogRef.current.showOkrImport();
    }
  };

  var popup = /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(_precls.precls, "__header-record-popup")
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(_precls.precls, "__header-record-item"),
    onClick: openOperateRecordPush
  }, /*#__PURE__*/_react["default"].createElement("i", {
    className: "tu-icon-daoru"
  }), /*#__PURE__*/_react["default"].createElement("span", {
    className: "".concat(_precls.precls, "__header-record-item-content")
  }, (0, _getLocale.getLocale)('OKR_ComAll_ImportingOKR'))));

  return /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement(_popup["default"], {
    ref: popupRef,
    popup: popup,
    popupAlign: {
      offset: [0, 4]
    }
  }, /*#__PURE__*/_react["default"].createElement(_tooltip["default"], {
    overlay: (0, _getLocale.getLocale)('Feed_Set_Pop_Butt_More'),
    placement: "top"
  }, /*#__PURE__*/_react["default"].createElement("span", {
    className: "".concat(_precls.precls, "__header-record")
  }, /*#__PURE__*/_react["default"].createElement("i", {
    className: "tu-icon-more1"
  })))), /*#__PURE__*/_react["default"].createElement(OkrImportModal, {
    ref: dialogRef
  }));
};

OkrImport['OkrImportModal'] = OkrImportModal;
var _default = OkrImport;
exports["default"] = _default;