"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 _editPop = _interopRequireDefault(require("./edit-pop"));

var _requestV = require("../../../../../../../utils/request-v1");

var _tools = require("../../../../../../../utils/tools");

var _UserSelectorPop = _interopRequireDefault(require("../../../../../../../components-v1/userSelector/UserSelectorPop"));

var _avatar = _interopRequireDefault(require("../../../../../../../components-v1/avatar"));

var _style = require("./style");

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

var _i18nFrontTranslate = require("../../../../../../../utils/i18n-front-translate");

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 _extends() { _extends = Object.assign || 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); }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread 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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

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

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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

var Score = /*#__PURE__*/function (_PureComponent) {
  _inherits(Score, _PureComponent);

  var _super = _createSuper(Score);

  function Score(p) {
    var _this;

    _classCallCheck(this, Score);

    _this = _super.call(this, p);

    _this.showScore = function () {};

    _this.deleteUser = function (index) {
      var atUsers = _this.state.atUsers;

      var newU = _toConsumableArray(atUsers);

      newU.splice(index, 1);

      _this.setState({
        atUsers: newU
      });
    };

    _this.handleAddAtUser = function (user) {
      var atUsers = _this.state.atUsers;
      if (atUsers.findIndex(function (u) {
        return u.Id == user.Id;
      }) != -1) return;

      _this.setState({
        atUsers: [user]
      });
    };

    _this.handleUpdateScore = function (value) {
      // @ts-ignore
      var _this$props = _this.props,
          changeProp = _this$props.changeProp,
          mileStoneId = _this$props.mileStoneId,
          onChangeScore = _this$props.onChangeScore;
      var url = (0, _requestV.getApiUrl)("kr/evaluate?workMileStoneId=".concat(_this.props.mileStoneId));
      var reg = /^(0(\.\d{1,2})?|1(\.0{1,2})?)$/;

      if (reg.test(value) || value == "1" || value == "0") {
        if (_this.state.scoreInfoText.length > 1000) {
          _this.setState({
            showScoreInfoError: true
          });

          return;
        }

        var data = {
          evaluateValue: parseFloat(value),
          toUserId: _this.state.atUsers.map(function (u) {
            return u.Id;
          }).join(","),

          /**
           * 新增评分说明字段
           */
          remark: (0, _tools.htmlEncodeByRegExp)((0, _tools.htmlDecodeByRegExp)(_this.state.scoreInfoText))
        };
        (0, _requestV.taker)(url, "POST", data).then(function () {
          onChangeScore(data.evaluateValue);
          changeProp && changeProp("remark", (0, _tools.htmlEncodeByRegExp)((0, _tools.htmlDecodeByRegExp)(_this.state.scoreInfoText)), mileStoneId);
        });
        return;
      }

      return (0, _getLocale.getLocale)("OKR_MyO_KRP_Please0and1");
    };

    _this.handleScoreInfoTextChange = function (e) {
      _this.setState({
        scoreInfoText: e.target.value,
        areaLength: e.target.value.length
      }, function () {
        if (_this.state.areaLength > 1000) {
          _this.setState({
            showScoreInfoError: true
          });
        } else {
          _this.state.showScoreInfoError && _this.setState({
            showScoreInfoError: false
          });
        }
      });
    };

    _this.getScoreEditPopOption = function () {
      var _this$state = _this.state,
          atUsers = _this$state.atUsers,
          showScoreInfoError = _this$state.showScoreInfoError;
      return {
        title: (0, _getLocale.getLocale)("OKR_MyO_Himhertocheck"),
        inputName: (0, _getLocale.getLocale)("Per_Ass_New_Appr_detail_Scor"),
        onConfirm: _this.handleUpdateScore,
        value: _this.props.value,
        placeHolder: (0, _getLocale.getLocale)("OKR_MyO_KRP_Please0and1"),
        align: "left",
        type: "line",
        disable: true,
        container: _this.props.container,
        scoreInfoText: _this.state.scoreInfoText,
        isValueValid: !showScoreInfoError,
        onShow: function onShow() {
          _this.setState({
            atUsers: [],
            showUserSelector: false
          });
        },

        /**
         * 新增评分弹层 --start
         */
        information: _this.state.showScoreInfoError ? /*#__PURE__*/_react["default"].createElement(_style.ScoreInfoWrapperError, {
          "data-length": (0, _i18nFrontTranslate.inputWordTrans)(_this.state.areaLength, 1000)
        }, /*#__PURE__*/_react["default"].createElement(_style.ScoreInfoSpanText, {
          style: {
            minWidth: _getLocale.isEn ? "75px" : "30px"
          }
        }, (0, _getLocale.getLocale)("OKR_MyO_Description")), /*#__PURE__*/_react["default"].createElement(_style.ScoreInfoSpanTextareaError, {
          ref: _this.state.scoreInfoErrorRef,
          placeholder: (0, _getLocale.getLocale)("OKR_MyO_scoredescription"),
          onChange: _this.handleScoreInfoTextChange,
          value: (0, _tools.htmlDecodeByRegExp)(_this.state.scoreInfoText)
        })) : /*#__PURE__*/_react["default"].createElement(_style.ScoreInfoWrapper, null, /*#__PURE__*/_react["default"].createElement(_style.ScoreInfoSpanText, {
          style: {
            minWidth: _getLocale.isEn ? "75px" : "30px"
          }
        }, (0, _getLocale.getLocale)("OKR_MyO_Description")), /*#__PURE__*/_react["default"].createElement(_style.ScoreInfoSpanTextarea, {
          ref: _this.state.scoreInfoRef,
          placeholder: (0, _getLocale.getLocale)("OKR_MyO_scoredescription"),
          onChange: _this.handleScoreInfoTextChange,
          value: (0, _tools.htmlDecodeByRegExp)(_this.state.scoreInfoText)
        })),

        /**
         * 新增评分弹层 --end
         */
        extra: /*#__PURE__*/_react["default"].createElement(_style.ExtraWrapper, null, /*#__PURE__*/_react["default"].createElement(_style.CallSomeoneSpan, null, (0, _getLocale.getLocale)("OKR_MyO_himher")), atUsers.map(function (item, index) {
          return /*#__PURE__*/_react["default"].createElement(_style.AvatarWrapper, {
            key: index
          }, /*#__PURE__*/_react["default"].createElement(_avatar["default"], {
            size: _avatar["default"].size(7),
            name: item.Name,
            src: item.UserAvatar.Medium,
            color: item.UserAvatar.Color,
            userId: item.Id
          }), /*#__PURE__*/_react["default"].createElement("span", {
            className: "tu-icon-cross",
            onClick: function onClick() {
              return _this.deleteUser(index);
            }
          }));
        }), /*#__PURE__*/_react["default"].createElement(_UserSelectorPop["default"], {
          className: "icon-add-wrapper",
          align: "bottom left",
          multi: false,
          onSubmit: function onSubmit(users, depts) {
            _this.handleAddAtUser(users[0]);
          }
        }, /*#__PURE__*/_react["default"].createElement(_style.Add, {
          className: "tu-icon-add"
        })))
      };
    };

    _this.getDefaultEvaluate = function () {
      var _this$props2 = _this.props,
          isEvaluate = _this$props2.isEvaluate,
          value = _this$props2.value,
          hasText = _this$props2.hasText;
      return isEvaluate ? /*#__PURE__*/_react["default"].createElement("span", null, /*#__PURE__*/_react["default"].createElement("span", {
        style: {
          color: "#0CC991",
          fontSize: "12px",
          cursor: "pointer"
        }
      }, value), hasText ? (0, _getLocale.getLocale)("Per_Set_Form_Quantifier_Points") : "") : /*#__PURE__*/_react["default"].createElement("p", {
        style: {
          color: "#BFC3C7",
          fontSize: "12px"
        }
      }, "--");
    };

    _this.getCanEditableEvaluate = function () {
      var _this$props3 = _this.props,
          isEvaluate = _this$props3.isEvaluate,
          value = _this$props3.value,
          hasText = _this$props3.hasText,
          renderTag = _this$props3.renderTag;
      if (renderTag) return renderTag();
      return isEvaluate ? /*#__PURE__*/_react["default"].createElement("span", null, /*#__PURE__*/_react["default"].createElement("span", {
        style: {
          color: "#0CC991",
          cursor: "pointer",
          fontSize: "12px"
        }
      }, value), hasText ? (0, _getLocale.getLocale)("Per_Set_Form_Quantifier_Points") : "") : /*#__PURE__*/_react["default"].createElement("span", {
        style: {
          color: "#106ECC",
          fontSize: "12px",
          cursor: "pointer"
        }
      }, (0, _getLocale.getLocale)("Per_Ass_New_Appr_detail_Scor"));
    };

    _this.state = {
      atUsers: [],
      showUserSelector: false,
      // 新增评分说明textarea字段值,
      scoreInfoText: "",
      showScoreInfoError: false,
      areaLength: 0,
      scoreInfoRef: /*#__PURE__*/_react["default"].createRef(),
      scoreInfoErrorRef: /*#__PURE__*/_react["default"].createRef(),
      scoreInfoEle: null,
      scoreInfoErrorEle: null,
      textareaValue: ""
    };
    return _this;
  }

  _createClass(Score, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this$state2 = this.state,
          scoreInfoRef = _this$state2.scoreInfoRef,
          scoreInfoErrorRef = _this$state2.scoreInfoErrorRef;
      var _this$props4 = this.props,
          textAreaValue = _this$props4.textAreaValue,
          setRefInParent = _this$props4.setRefInParent;
      this.setState({
        scoreInfoEle: scoreInfoRef.current,
        scoreInfoErrorEle: scoreInfoErrorRef.current,
        scoreInfoText: textAreaValue,
        showScoreInfoError: textAreaValue.length > 1000,
        areaLength: textAreaValue.length
      });
      this.score && setRefInParent(this.score.refs);
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps, prevState, snapshot) {
      var textareaValue = this.state.textareaValue;
      var textAreaValue = this.props.textAreaValue;

      if (textAreaValue !== textareaValue) {
        this.setState({
          textareaValue: textAreaValue,
          scoreInfoText: textAreaValue
        });
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      // @ts-ignore
      var _this$props5 = this.props,
          value = _this$props5.value,
          editable = _this$props5.editable,
          hasText = _this$props5.hasText,
          isEvaluate = _this$props5.isEvaluate,
          align = _this$props5.align,
          evaluateEditable = _this$props5.evaluateEditable,
          createTask = _this$props5.createTask,
          noIconEdit = _this$props5.noIconEdit;
      return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, evaluateEditable ? /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_editPop["default"], _extends({}, this.getScoreEditPopOption(), {
        // @ts-ignore
        ref: function ref(r) {
          return _this2.score = r;
        },
        align: align,
        popClassName: "krPush-score"
      }), this.getCanEditableEvaluate()), !noIconEdit ? /*#__PURE__*/_react["default"].createElement(_style.IconEdit, {
        className: "tu-icon-edit",
        "data-for": "krPush",
        "data-tip": (0, _getLocale.getLocale)("Mod_Editor"),
        onClick: function onClick(e) {
          // @ts-ignore
          _this2.score.handleClick(e);
        }
      }) : null) : this.getDefaultEvaluate());
    }
  }]);

  return Score;
}(_react.PureComponent);

exports["default"] = Score;
Score.defaultProps = {
  hasText: false
};