"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 _cloneDeep = _interopRequireDefault(require("clone-deep"));

var _uuid = _interopRequireDefault(require("uuid"));

var _bsGlobal = require("../../../utils/bs-global");

var _roundWeight = require("../../../utils/roundWeight");

var _krItem = _interopRequireDefault(require("./krItem"));

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

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

var _okrCreateSuggest = require("../fields/okr-create-suggest");

var _krAdd = _interopRequireDefault(require("../img/kr-add.svg"));

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

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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

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 _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 _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 _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; }

function KrDatas(props) {
  var isApplyTpl = props.isApplyTpl,
      isCustomWeight = props.isCustomWeight,
      wrapperRef = props.wrapperRef,
      setKrDatas = props.setKrDatas,
      krDatas = props.krDatas,
      setIsCustomWeight = props.setIsCustomWeight,
      container = props.container,
      handleKrInputStateChange = props.handleKrInputStateChange,
      setKrsCheckResult = props.setKrsCheckResult,
      krIsValidate = props.krIsValidate,
      setKrIsValidate = props.setKrIsValidate,
      _props$setIsInputCont = props.setIsInputContent,
      setIsInputContent = _props$setIsInputCont === void 0 ? function () {} : _props$setIsInputCont;
  var krCheckId = 0;

  var _useState = (0, _react.useState)(),
      _useState2 = _slicedToArray(_useState, 2),
      inputKrInfo = _useState2[0],
      setInputKrInfo = _useState2[1];

  var _useState3 = (0, _react.useState)([]),
      _useState4 = _slicedToArray(_useState3, 2),
      krsCheckFriendlyResult = _useState4[0],
      setKrsCheckFriendlyResult = _useState4[1]; // 存储每条kr的校验结果，用了统计最后的校验结果


  var timerRef = (0, _react.useRef)();
  var krNameIsEmpty = (0, _react.useRef)(!inputKrInfo || !inputKrInfo.mileStoneName);
  var krDatasRef = (0, _react.useRef)(krDatas);
  var setting = (0, _bsGlobal.getBSGlobal)('OkrAdvancedSetting').KRSetting;

  var _getUserInfo = (0, _bsGlobal.getUserInfo)(),
      Name = _getUserInfo.Name,
      Id = _getUserInfo.Id,
      UserAvatar = _getUserInfo.UserAvatar;

  var openKrWeight = setting.KrWeight;
  var total = 0;

  if (isCustomWeight) {
    krDatas.forEach(function (kr) {
      return total += Number(kr.krWeight);
    }); // total = RoundWeight(total); // 不知道为啥，这样如果自定义了总的超过100了还是会展示total100

    total = total.toFixed(1);
  } else {
    total = 100;
  }

  var getKrAnalysisInfo = function getKrAnalysisInfo() {
    krCheckId += 1;
    var tempCheckId = krCheckId;
    (0, _requestApi.getKrAnalysisInfos)({
      text: inputKrInfo.mileStoneName
    }) // @ts-ignore
    .then(function (data) {
      if (tempCheckId !== krCheckId) {
        return;
      }

      var tempKrCheckResult = _toConsumableArray(krsCheckFriendlyResult);

      var targetKrIndex = tempKrCheckResult.findIndex(function (kr) {
        return kr.uuid === inputKrInfo.uuid;
      });

      if (targetKrIndex !== -1) {
        tempKrCheckResult.splice(targetKrIndex, 1, {
          uuid: inputKrInfo.uuid,
          hasNumWords: data.hasNumWords
        });
      } else {
        tempKrCheckResult.push({
          uuid: inputKrInfo.uuid,
          hasNumWords: data.hasNumWords
        });
      }

      if (krNameIsEmpty.current) {
        setKrsCheckResult({
          finalResult: _okrCreateSuggest.EOkrCreateSuggestResultType.normal,
          friendlyResult: []
        });
      } else {
        setKrsCheckFriendlyResult(tempKrCheckResult);
        setKrsCheckResult({
          finalResult: data.hasNumWords ? _okrCreateSuggest.EOkrCreateSuggestResultType.correct : _okrCreateSuggest.EOkrCreateSuggestResultType.wrong,
          friendlyResult: tempKrCheckResult
        });
      }
    })["catch"](function (err) {
      _toast["default"].Error(err);
    })["finally"](function () {
      setIsInputContent(false);
    });
  }; // 添加KR


  function addKr() {
    var krDatasClone = (0, _cloneDeep["default"])(krDatasRef.current);
    var krsCount = krDatasClone.length;
    setKrIsValidate(false);
    setTimeout(function () {
      if (!wrapperRef.current || krsCount < 6) return;
      wrapperRef.current.scrollTop = wrapperRef.current.scrollHeight;
    }, 0);

    if (!isCustomWeight) {
      var krWeight = (0, _roundWeight.RoundWeight)(100 / (krsCount + 1));

      var _newKrs = [].concat(_toConsumableArray(krDatasClone.map(function (kr) {
        return _objectSpread(_objectSpread({}, kr), {}, {
          krWeight: krWeight
        });
      })), [{
        uuid: _uuid["default"].v1(),
        principalId: Id,
        principalName: Name,
        userAvatar: UserAvatar,
        krWeight: krWeight,
        mileStoneName: '',
        mileStoneNamePureTextExcludeAt: '',
        mileStoneNameRichText: undefined,
        aiteUsers: [],
        confidenceIndex: 5
      }]);

      setKrDatas(_newKrs);
      krDatasRef.current = _newKrs;
      return;
    }

    var newKrs = [].concat(_toConsumableArray(krDatasClone), [{
      uuid: _uuid["default"].v1(),
      principalId: Id,
      principalName: Name,
      userAvatar: UserAvatar,
      krWeight: 0,
      mileStoneName: '',
      mileStoneNamePureTextExcludeAt: '',
      mileStoneNameRichText: undefined,
      aiteUsers: [],
      confidenceIndex: 5
    }]);
    setKrDatas(newKrs);
    krDatasRef.current = newKrs;
  } // 修改KR


  var changeKr = function changeKr(kr) {
    var index = krDatasRef.current.findIndex(function (data) {
      return data.uuid == kr.uuid;
    });

    if (krDatasRef.current[index].krWeight !== kr.krWeight) {
      setIsCustomWeight(true);
    }

    var newKrs = _toConsumableArray(krDatasRef.current);

    newKrs[index] = kr;
    setKrDatas(newKrs);
    krDatasRef.current = newKrs;
    setInputKrInfo(kr);
  }; // 删除KR


  var deleteKr = function deleteKr(id) {
    var krDatasClone = (0, _cloneDeep["default"])(krDatasRef.current);
    setKrIsValidate(false);
    var newKrDatas = krDatasClone.filter(function (k) {
      return k.uuid !== id;
    });

    if (!isCustomWeight && openKrWeight) {
      newKrDatas = newKrDatas.map(function (kr) {
        return _objectSpread(_objectSpread({}, kr), {}, {
          krWeight: (0, _roundWeight.RoundWeight)(100 / newKrDatas.length)
        });
      });
    }

    setKrDatas(newKrDatas);
    krDatasRef.current = newKrDatas;

    var tempKrCheckResult = _toConsumableArray(krsCheckFriendlyResult);

    var targetKrIndex = tempKrCheckResult.findIndex(function (kr) {
      return kr.uuid === inputKrInfo.uuid;
    });

    if (targetKrIndex !== -1) {
      tempKrCheckResult.splice(targetKrIndex, 1);
    }

    setKrsCheckFriendlyResult(tempKrCheckResult);
    setKrsCheckResult({
      finalResult: _okrCreateSuggest.EOkrCreateSuggestResultType.normal,
      friendlyResult: tempKrCheckResult
    });
  };

  var onKrInputStateChange = (0, _react.useCallback)(function (isFocus, krInfo) {
    setInputKrInfo(krInfo);
    handleKrInputStateChange === null || handleKrInputStateChange === void 0 ? void 0 : handleKrInputStateChange(isFocus);
  }, []);
  (0, _react.useEffect)(function () {
    // 防抖
    krNameIsEmpty.current = !inputKrInfo || !inputKrInfo.mileStoneName;

    if (!inputKrInfo || !inputKrInfo.mileStoneName) {
      setIsInputContent(false);
      setKrsCheckResult({
        finalResult: _okrCreateSuggest.EOkrCreateSuggestResultType.normal,
        friendlyResult: []
      });
    } else if (timerRef.current) {
      clearTimeout(timerRef.current);
      timerRef.current = setTimeout(getKrAnalysisInfo, 1000);
    } else {
      timerRef.current = setTimeout(getKrAnalysisInfo, 1000);
    }

    return function () {
      clearTimeout(timerRef.current);
    };
  }, [inputKrInfo, setIsInputContent]);
  (0, _react.useEffect)(function () {
    krDatasRef.current = krDatas;
  }, [isApplyTpl]);
  return /*#__PURE__*/_react["default"].createElement("div", null, krDatasRef.current.map(function (kr, index) {
    return /*#__PURE__*/_react["default"].createElement(_krItem["default"], {
      key: kr === null || kr === void 0 ? void 0 : kr.uuid,
      krData: kr,
      changeKr: changeKr,
      deleteKr: deleteKr,
      container: container,
      index: index + 1,
      onKrInputStateChange: onKrInputStateChange,
      krIsValidate: krIsValidate,
      setIsInputContent: setIsInputContent
    });
  }), /*#__PURE__*/_react["default"].createElement("div", {
    className: "krs-info"
  }, /*#__PURE__*/_react["default"].createElement("span", {
    className: "add-kr-btn",
    onClick: addKr
  }, /*#__PURE__*/_react["default"].createElement("img", {
    className: "add-kr-btn__icon",
    src: _krAdd["default"],
    alt: ""
  }), (0, _getLocale.getLocale)('OKR_MyO_Pop_Butt_AddKR')), krDatasRef.current.length > 0 && openKrWeight && /*#__PURE__*/_react["default"].createElement("span", {
    className: "krs-info__total-weight"
  }, (0, _getLocale.getLocale)('OKR_MyO_Pop_Text_Total'), total, "%")));
}

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