"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 _util = require("./util");

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

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

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

var _button = _interopRequireDefault(require("../../../../../button"));

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

var _switch = _interopRequireDefault(require("../../../../../switch"));

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 asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(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 prefix = 'tita-okr-excel-progress-okr';

var OKRProgress = function OKRProgress(_ref) {
  var children = _ref.children,
      id = _ref.id,
      isO = _ref.isO,
      autoUpdate = _ref.autoUpdate,
      autoUpdateItem = _ref.autoUpdateItem,
      value = _ref.value,
      onChange = _ref.onChange,
      editable = _ref.editable,
      riskLevel = _ref.riskLevel,
      _ref$getPopupContaine = _ref.getPopupContainer,
      getPopupContainer = _ref$getPopupContaine === void 0 ? function () {
    return document.body;
  } : _ref$getPopupContaine;

  var _useState = (0, _react.useState)({
    childOkrProgress: -1,
    childkrProgress: -1,
    childEProgress: -1,
    Progress: 0,
    UpdateProgressWay: 0,
    UpdateObj: 0
  }),
      _useState2 = _slicedToArray(_useState, 2),
      recommandProgressObj = _useState2[0],
      setRecommandProgressObj = _useState2[1]; // 推荐值


  var _useState3 = (0, _react.useState)(value),
      _useState4 = _slicedToArray(_useState3, 2),
      progress = _useState4[0],
      setProgress = _useState4[1];

  var _useState5 = (0, _react.useState)(autoUpdate),
      _useState6 = _slicedToArray(_useState5, 2),
      updateOpen = _useState6[0],
      setUpdateOpen = _useState6[1]; // 设置自动更新


  var _useState7 = (0, _react.useState)(autoUpdateItem || 0),
      _useState8 = _slicedToArray(_useState7, 2),
      updateWay = _useState8[0],
      setUpdateWay = _useState8[1]; // 自动更新方式 0: 关闭， 1: 根据关见成果， 2: 子目标


  var _useState9 = (0, _react.useState)(riskLevel || isO ? 6 : 1),
      _useState10 = _slicedToArray(_useState9, 2),
      selected = _useState10[0],
      setSelected = _useState10[1];

  var _useState11 = (0, _react.useState)(''),
      _useState12 = _slicedToArray(_useState11, 2),
      errorText = _useState12[0],
      setErrorText = _useState12[1];

  var popupRef = (0, _react.useRef)({
    open: function open() {},
    close: function close() {}
  });
  var configure = isO ? (0, _util.getOSetting)() : (0, _util.getKrSetting)(); // 推荐

  var getRecommendProgress = /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      var getRecommandHandler, data, _data$Data, UpdateProgressWay, Progress;

      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              getRecommandHandler = isO ? _requestApi.getORecommandProgress : _requestApi.getKrRecommandProgress;
              _context.next = 3;
              return getRecommandHandler(id);

            case 3:
              data = _context.sent;

              if (data.Code === 1) {
                _data$Data = data.Data, UpdateProgressWay = _data$Data.UpdateProgressWay, Progress = _data$Data.Progress;
                setRecommandProgressObj(data.Data);
                setUpdateOpen(UpdateProgressWay !== 0);
                setUpdateWay(UpdateProgressWay === 0 ? 1 : UpdateProgressWay);
                setProgress(Progress);
              }

            case 5:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));

    return function getRecommendProgress() {
      return _ref2.apply(this, arguments);
    };
  }();

  var handlePopupVisibleChange = function handlePopupVisibleChange(visible) {
    if (visible) {
      getRecommendProgress();
    }
  };

  var handleProgressChange = function handleProgressChange(e) {
    e.persist();
    var value = e.target.value;

    if (!value || Number.isNaN(Number(value)) || Number(value) <= 0 || /\./g.test(value)) {
      setErrorText((0, _getLocale.getLocale)('OKR_MyO_KRP_Please0'));
    } else {
      setErrorText('');
    }

    setProgress(value);
  };

  var hideProgressPopup = function hideProgressPopup() {
    popupRef.current.close();
  };

  var confirmUpdateData = function confirmUpdateData() {
    if (onChange) {
      onChange({
        id: id,
        type: isO ? 'o' : 'kr',
        value: {
          progress: progress,
          status: selected,
          autoUpdate: updateOpen,
          autoUpdateItem: updateWay
        }
      });
    }

    hideProgressPopup();
  };

  var renderPopContent = (0, _react.useMemo)(function () {
    var _classNames;

    if (!editable) {
      return null;
    }

    return /*#__PURE__*/_react["default"].createElement("div", {
      className: "".concat(prefix, "__content")
    }, /*#__PURE__*/_react["default"].createElement("div", {
      className: "".concat(prefix, "__content-title")
    }, (0, _getLocale.getLocale)('OKR_MyO_Pop_Upd_Progresss1'), /*#__PURE__*/_react["default"].createElement(_tooltip["default"] // @ts-ignore
    , {
      overlay: configure.getRecommandText(updateOpen, updateWay, {}),
      placement: "top",
      align: {
        offset: [0, 5]
      }
    }, /*#__PURE__*/_react["default"].createElement("i", {
      className: "tu-icon-wiki ".concat(prefix, "__content-title-icon")
    }))), /*#__PURE__*/_react["default"].createElement("div", {
      className: (0, _classnames["default"])("".concat(prefix, "__content-input"), (_classNames = {}, _defineProperty(_classNames, "".concat(prefix, "__content-input--disable"), updateOpen), _defineProperty(_classNames, "".concat(prefix, "__content-input--error"), errorText), _classNames))
    }, /*#__PURE__*/_react["default"].createElement("input", {
      className: (0, _classnames["default"])("".concat(prefix, "__content-input-el"), _defineProperty({}, "".concat(prefix, "__content-input-el--disable"), updateOpen)),
      value: progress,
      onChange: handleProgressChange,
      disabled: updateOpen,
      placeholder: (0, _getLocale.getLocale)('OKR_MyO_KRP_Please0')
    }), "%"), errorText && /*#__PURE__*/_react["default"].createElement("div", {
      className: "".concat(prefix, "__content-input-error-text")
    }, errorText), /*#__PURE__*/_react["default"].createElement("div", {
      className: "".concat(prefix, "__content-status")
    }, /*#__PURE__*/_react["default"].createElement("div", {
      className: "".concat(prefix, "__content-status-title")
    }, (0, _getLocale.getLocale)('OKR_MyO_Pop_Upd_Status')), (isO ? (0, _util.getOptions)() : (0, _util.getKrOptions)()).map(function (option) {
      return /*#__PURE__*/_react["default"].createElement("div", {
        className: "".concat(prefix, "__content-status-item"),
        key: option.id,
        onClick: function onClick() {
          return setSelected(option.id);
        }
      }, /*#__PURE__*/_react["default"].createElement("i", {
        style: {
          color: option.color
        },
        className: selected === option.id ? 'tu-icon-singlebox-avtive' : 'tu-icon-singlebox-have'
      }), /*#__PURE__*/_react["default"].createElement("span", {
        className: "".concat(prefix, "__content-status-item-text")
      }, option.text));
    })), /*#__PURE__*/_react["default"].createElement(_switch["default"], {
      label: /*#__PURE__*/_react["default"].createElement("span", {
        className: "".concat(prefix, "__content-switch")
      }, configure.switchLabel),
      checked: updateOpen,
      onChange: function onChange(data) {
        setUpdateOpen(data);
      }
    }), updateOpen && /*#__PURE__*/_react["default"].createElement("div", {
      className: "".concat(prefix, "__content-auto-update")
    }, configure.options.map(function (option) {
      return /*#__PURE__*/_react["default"].createElement("div", {
        onClick: function onClick() {
          return setUpdateWay(option.key);
        },
        className: "".concat(prefix, "__content-auto-update-option")
      }, /*#__PURE__*/_react["default"].createElement("span", {
        className: (0, _classnames["default"])("".concat(prefix, "__content-auto-update-option-radio"), _defineProperty({}, "".concat(prefix, "__content-auto-update-option-radio--selected"), updateWay === option.key))
      }), /*#__PURE__*/_react["default"].createElement("span", {
        className: "".concat(prefix, "__content-auto-update-option-label")
      }, option.label, ' ', /*#__PURE__*/_react["default"].createElement(_tooltip["default"], {
        overlay: option.tooltip,
        placement: "top",
        align: {
          offset: [0, 5]
        }
      }, /*#__PURE__*/_react["default"].createElement("span", {
        className: (0, _classnames["default"])('tu-icon-question-mark', "".concat(prefix, "__content-auto-update-option-icon"))
      }))));
    })), /*#__PURE__*/_react["default"].createElement("div", {
      className: "".concat(prefix, "__content-bottom")
    }, /*#__PURE__*/_react["default"].createElement(_button["default"].Rect, {
      type: 'cancel',
      size: 'small',
      text: (0, _getLocale.getLocale)('Mod_Cancel'),
      onClick: hideProgressPopup
    }), /*#__PURE__*/_react["default"].createElement(_button["default"].Rect, {
      type: 'primary',
      size: 'small',
      text: (0, _getLocale.getLocale)('OKR_MyO_Butt_Determine'),
      disabled: !!errorText,
      onClick: confirmUpdateData
    })));
  }, [editable, updateOpen, configure, updateWay, selected, progress, errorText]);
  (0, _react.useEffect)(function () {
    if (!updateOpen) return;
    setErrorText('');
    var childOkrProgress = recommandProgressObj.childOkrProgress,
        childkrProgress = recommandProgressObj.childkrProgress,
        childEProgress = recommandProgressObj.childEProgress;

    if (updateWay === 1) {
      setProgress(isO ? (0, _util.transProgress)(childkrProgress) : (0, _util.transProgress)(childEProgress));
    }

    if (updateWay === 2) {
      setProgress((0, _util.transProgress)(childOkrProgress));
    }
  }, [updateWay, recommandProgressObj, updateOpen]);
  (0, _react.useEffect)(function () {
    setSelected(riskLevel);
  }, [riskLevel]);
  (0, _react.useEffect)(function () {
    setProgress(value);
  }, [value]);
  return /*#__PURE__*/_react["default"].createElement(_popup["default"], {
    popup: renderPopContent,
    onPopupVisibleChange: handlePopupVisibleChange,
    popupPlacement: 'bottom',
    ref: popupRef,
    getPopupContainer: getPopupContainer
  }, children);
};

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