"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 _classnames = _interopRequireDefault(require("classnames"));

var _reactCropper = _interopRequireDefault(require("react-cropper"));

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

var _conditionRender = _interopRequireDefault(require("../condition-render"));

var _requestApi = require("./request-api");

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

var _constant = require("./constant");

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

require("cropperjs/dist/cropper.css");

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 _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

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 = "tita-ui-change-person-photo";

function ChangePhoto(props) {
  var visible = props.visible,
      onCancel = props.onCancel,
      _props$type = props.type,
      type = _props$type === void 0 ? "person" : _props$type,
      handleSuccessUploadPhoto = props.handleSuccessUploadPhoto,
      title = props.title;
  var modalRef = (0, _react.useRef)();
  var cropperRef = (0, _react.useRef)(null);

  var _useState = (0, _react.useState)(""),
      _useState2 = _slicedToArray(_useState, 2),
      image = _useState2[0],
      setImage = _useState2[1];

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

  var _useState5 = (0, _react.useState)("#"),
      _useState6 = _slicedToArray(_useState5, 2),
      cropData = _useState6[0],
      setCropData = _useState6[1];

  var _useState7 = (0, _react.useState)(false),
      _useState8 = _slicedToArray(_useState7, 2),
      isEnter = _useState8[0],
      setIsEnter = _useState8[1];

  var _useState9 = (0, _react.useState)(""),
      _useState10 = _slicedToArray(_useState9, 2),
      fileName = _useState10[0],
      setFileName = _useState10[1];

  var item = _constant.List.find(function (item) {
    return item.id === type;
  });

  var onChange = function onChange(e) {
    var files;

    if (e.dataTransfer) {
      files = e.dataTransfer.files;
    } else if (e.target) {
      files = e.target.files;
    }

    setFileName(files[0].name);
    var reader = new FileReader();

    reader.onload = function () {
      setImage(reader.result);
    };

    reader.readAsDataURL(files[0]);
  };

  var dataURLtoFile = function dataURLtoFile(dataurl, filename) {
    var arr = dataurl.split(",");
    var mime = arr[0].match(/:(.*?);/)[1];
    var bstr = atob(arr[1]);
    var n = bstr.length;
    var u8arr = new Uint8Array(n);

    for (var i = n; i >= 0; i -= 1) {
      u8arr[i] = bstr.charCodeAt(i);
    }

    return new File([u8arr], filename, {
      type: mime
    });
  };

  var onCrop = function onCrop() {
    var imageElement = cropperRef.current;
    var cropper = imageElement.cropper;
    setCropData(cropper.getCroppedCanvas().toDataURL());
    var base64Url = cropper.getCroppedCanvas().toDataURL();
    var newFile = dataURLtoFile(base64Url, fileName);
    var formData = new FormData();
    formData.append("file", newFile);
    setCropper(formData);
  };

  var handleSuccessSave = function handleSuccessSave(resp) {
    if (resp.Code === 1) {
      _toast["default"].Success((0, _getLocale.getLocale)("Pro_page_Plan_Saved"));

      onCancel();
      setImage("");
      handleSuccessUploadPhoto(cropData);
    } else {
      _toast["default"].Error(resp.Message);

      setImage("");
    }
  };

  var handleSaveInfo = function handleSaveInfo() {
    if (image) {
      if (type === "person") {
        (0, _requestApi.saveUserPhoto)(cropper).then(function (resp) {
          handleSuccessSave(resp);
        });
      } else if (type === "enterprise") {
        (0, _requestApi.saveTenantLogo)(cropper).then(function (resp) {
          handleSuccessSave(resp);
        });
      } else {
        (0, _requestApi.saveBrowserIcon)(cropper).then(function (resp) {
          handleSuccessSave(resp);
        });
      }
    }
  };

  var handleEnterAgain = function handleEnterAgain() {
    setIsEnter(true);
  };

  var handleLeaveAgain = function handleLeaveAgain() {
    setIsEnter(false);
  };

  var handleCancel = function handleCancel() {
    onCancel();
    setImage("");
  };

  return /*#__PURE__*/_react["default"].createElement(_dialog["default"], {
    visible: visible,
    ref: modalRef,
    width: 480,
    mask: true,
    centered: true,
    title: title,
    noHeadLine: true,
    maskClosable: false,
    onClose: handleCancel,
    onCancel: handleCancel,
    okText: (0, _getLocale.getLocale)("Mod_Save"),
    noFooterLine: true,
    onOk: handleSaveInfo
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: preCls
  }, !image ? /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__upload")
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__upload-preview")
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__upload-right")
  }, /*#__PURE__*/_react["default"].createElement("i", {
    className: (0, _classnames["default"])("".concat(preCls, "__upload-right-icon"), "tu-icon-upload")
  }), /*#__PURE__*/_react["default"].createElement("input", {
    type: "file",
    onChange: onChange,
    className: "".concat(preCls, "__upload-right-input"),
    accept: item === null || item === void 0 ? void 0 : item.accept
  }), /*#__PURE__*/_react["default"].createElement("span", {
    className: "".concat(preCls, "__upload-right-title")
  }, (0, _getLocale.getLocale)("Pro_detail_ClickUpload")), /*#__PURE__*/_react["default"].createElement("span", {
    className: "".concat(preCls, "__upload-right-tips")
  }, item === null || item === void 0 ? void 0 : item.tips))), /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__upload-left")
  }, /*#__PURE__*/_react["default"].createElement(_conditionRender["default"], {
    condition: type === "person"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__upload-left-box1")
  }), /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__upload-left-box2")
  }), /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__upload-left-box3")
  })), /*#__PURE__*/_react["default"].createElement(_conditionRender["default"], {
    condition: type === "enterprise" || type === "browser"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__upload-left-box")
  }), /*#__PURE__*/_react["default"].createElement("span", {
    className: "".concat(preCls, "__upload-left-preview")
  }, item === null || item === void 0 ? void 0 : item.previewTitle)))) : /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__img")
  }, /*#__PURE__*/_react["default"].createElement(_reactCropper["default"], {
    src: image,
    style: {
      height: 240,
      width: 240
    },
    background: false,
    responsive: true,
    autoCropArea: item === null || item === void 0 ? void 0 : item.autoCropArea,
    checkOrientation: true,
    minCropBoxHeight: item === null || item === void 0 ? void 0 : item.minCropBoxHeight,
    minCropBoxWidth: item === null || item === void 0 ? void 0 : item.minCropBoxWidth,
    initialAspectRatio: item === null || item === void 0 ? void 0 : item.initialAspectRatio,
    guides: true,
    preview: ".img-preview",
    ref: cropperRef,
    crop: onCrop
  }), /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])("".concat(preCls, "__preview-box"), _defineProperty({}, "".concat(preCls, "__preview-box-bgc"), type === "enterprise"), _defineProperty({}, "".concat(preCls, "__preview-box-browser"), type === "browser"))
  }, /*#__PURE__*/_react["default"].createElement(_conditionRender["default"], {
    condition: type === "person"
  }, /*#__PURE__*/_react["default"].createElement("img", {
    src: cropData,
    className: "".concat(preCls, "__preview-box1"),
    alt: "bigImage"
  }), /*#__PURE__*/_react["default"].createElement("img", {
    src: cropData,
    className: "".concat(preCls, "__preview-box2"),
    alt: "middleImage"
  }), /*#__PURE__*/_react["default"].createElement("img", {
    src: cropData,
    className: "".concat(preCls, "__preview-box3"),
    alt: "smallImage"
  })), /*#__PURE__*/_react["default"].createElement(_conditionRender["default"], {
    condition: type === "enterprise"
  }, /*#__PURE__*/_react["default"].createElement("img", {
    src: cropData,
    className: "".concat(preCls, "__preview-enterprise-img"),
    alt: "previewImage"
  }), /*#__PURE__*/_react["default"].createElement("span", {
    className: "".concat(preCls, "__preview-enterprise-title")
  }, item === null || item === void 0 ? void 0 : item.previewTitle)), /*#__PURE__*/_react["default"].createElement(_conditionRender["default"], {
    condition: type === "browser"
  }, /*#__PURE__*/_react["default"].createElement("img", {
    src: cropData,
    className: "".concat(preCls, "__preview-browser-img"),
    alt: "previewImage"
  }), /*#__PURE__*/_react["default"].createElement("span", {
    className: "".concat(preCls, "__preview-browser-name")
  }, "Tita"), /*#__PURE__*/_react["default"].createElement("span", {
    className: "".concat(preCls, "__preview-browser-title")
  }, item === null || item === void 0 ? void 0 : item.previewTitle)))), /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__title")
  }, /*#__PURE__*/_react["default"].createElement("input", {
    accept: item === null || item === void 0 ? void 0 : item.accept,
    type: "file",
    onChange: onChange,
    className: (0, _classnames["default"])("".concat(preCls, "__title-input"), _defineProperty({}, "".concat(preCls, "__title-input--show"), image)),
    onMouseEnter: handleEnterAgain,
    onMouseLeave: handleLeaveAgain
  }), /*#__PURE__*/_react["default"].createElement("span", {
    className: (0, _classnames["default"])("".concat(preCls, "__title-again"), _defineProperty({}, "".concat(preCls, "__title-again--show"), image), _defineProperty({}, "".concat(preCls, "__title-again--hover"), isEnter))
  }, (0, _getLocale.getLocale)("Set_PI_Reupload")), /*#__PURE__*/_react["default"].createElement(_conditionRender["default"], {
    condition: type === "person"
  }, /*#__PURE__*/_react["default"].createElement("span", {
    className: "".concat(preCls, "__title-preview")
  }, item === null || item === void 0 ? void 0 : item.previewTitle)))));
}

var _default = ChangePhoto;
exports["default"] = _default;