"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 _tooltip = _interopRequireDefault(require("../tooltip"));

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

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

var _FormItemV = _interopRequireDefault(require("./FormItemV2"));

var _Input = _interopRequireDefault(require("../../components-v1/input/Input"));

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

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

var _utils = require("./utils");

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

var _openData = require("../../utils/open-data");

require("./style/style.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 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 _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); }

function totalWeightCalculator(milepostData) {
  return milepostData.reduce(function (acc, curr) {
    return acc + Number(curr.krWeight);
  }, 0);
}

// NOTE 数据验证 数据收集 全都放在这一层
var EditKrWightModal = /*#__PURE__*/function (_Component) {
  _inherits(EditKrWightModal, _Component);

  var _super = _createSuper(EditKrWightModal);

  //    work/headInfo?workId=54798
  function EditKrWightModal(props) {
    var _this;

    _classCallCheck(this, EditKrWightModal);

    _this = _super.call(this, props);

    _this.reduceData = function (milepostData) {
      // 降低数据量
      if (milepostData == null || milepostData.length == 0) {
        return [];
      }

      return (0, _utils.ReCalibratePrecision)(milepostData).map(function (_ref) {
        var feedId = _ref.feedId,
            mileStoneId = _ref.mileStoneId,
            user = _ref.user,
            mileStoneName = _ref.mileStoneName,
            krWeight = _ref.krWeight;
        return {
          feedId: feedId,
          mileStoneId: mileStoneId,
          user: user,
          mileStoneName: mileStoneName,
          krWeight: krWeight,
          isDirty: false
        };
      });
    };

    _this.onModalClose = function () {
      _this.props.onClose && _this.props.onClose();
    };

    _this.handleOk = function () {
      if (!_this.state.isValid) {
        _toast["default"].Warning('关键成果总权重须等于100%');

        return;
      }

      var _this$props$autoReque = _this.props.autoRequest,
          autoRequest = _this$props$autoReque === void 0 ? true : _this$props$autoReque;

      if (autoRequest) {
        var url = "kr/updateKrWeight?okrId=".concat(_this.props.workId);

        var data = _this.state.milepostData.map(function (_ref2) {
          var mileStoneId = _ref2.mileStoneId,
              krWeight = _ref2.krWeight;
          return {
            id: mileStoneId,
            krWeight: krWeight
          };
        });

        (0, _requestV.taker)((0, _requestV.getApiUrl)(url), 'post', data).then(function (res) {
          _this.props.onOk && _this.props.onOk(); // @ts-ignore

          window.Talent.app.vent.trigger('updateProgress:Project-Progress-View', {});
        });
        _this.props.onOk && _this.props.onOk(data);
      }
    };

    _this.handleCancel = function () {
      // 别对外双绑数据
      _this.props.onCancel && _this.props.onCancel();
    };

    _this.viewInitRecalibrateWeight = function () {// 如果只是点开弹层不做修改 33.3 * 3 是被允许的
    };

    _this.handleWeightChange = function (event, feedId) {
      var krWeight = event.target.value;
      var milepostData = _this.state.milepostData;

      _this.setState({
        isValid: true
      });

      var _milepostData = milepostData.map(function (data) {
        if (data.feedId == feedId) {
          if ((0, _utils.KrWeightValidator)(krWeight)) {
            return _objectSpread(_objectSpread({}, data), {}, {
              krWeight: krWeight,
              isDirty: false
            });
          }

          return _objectSpread(_objectSpread({}, data), {}, {
            krWeight: krWeight,
            isDirty: true
          });
        }

        return data;
      });

      _this.setState({
        milepostData: _milepostData
      }, _this.totalValidator);
    };

    _this.blurReCalibratePrecision = function () {
      var milepostData = _this.state.milepostData; // 首先是找 finedIndex 找到验证通过并且不为整数的权重

      var index = milepostData.findIndex(function (_ref3) {
        var krWeight = _ref3.krWeight;
        return (0, _utils.KrWeightValidator)(krWeight) && !Number.isInteger(Number(krWeight));
      });

      if (index !== -1) {
        _this.setState({
          milepostData: milepostData.map(function (data) {
            return _objectSpread(_objectSpread({}, data), {}, {
              krWeight: Number(data.krWeight).toFixed(1)
            });
          })
        });
      }
    };

    _this.krWeights = function () {
      // 加一个真假值数组
      var _isValidArray = _this.state.milepostData.map(function (_ref4) {
        var krWeight = _ref4.krWeight;
        return (0, _utils.KrWeightValidator)(krWeight);
      });

      var _isValid = _isValidArray.find(function (e) {
        return e !== true;
      });

      return _isValid == undefined;
    };

    _this.totalValidator = function () {
      var milepostData = _this.state.milepostData;

      var _totalWeight = totalWeightCalculator(milepostData);

      if (_totalWeight > 99.9 && _totalWeight < 100.1 && _this.krWeights()) {
        if (milepostData.length > 1) {
          _this.setState({
            isValid: true
          });
        } else if (_totalWeight != 100) {
          // 只有一个
          _this.setState({
            isValid: false
          });
        }
      } else {
        _this.setState({
          isValid: false
        });
      }
    };

    _this.state = {
      milepostData: [],
      isValid: false,
      totalWeight: 100,
      isDone: false
    };
    return _this;
  }

  _createClass(EditKrWightModal, [{
    key: "getData",
    value: function getData() {
      var url = "okr/kr?okrId=".concat(this.props.workId);
      return (0, _requestV.taker)((0, _requestV.getApiUrl)(url));
    }
  }, {
    key: "isWorkDone",
    value: function isWorkDone() {
      var url = "work/headInfo?workId=".concat(this.props.workId);
      return (0, _requestV.taker)((0, _requestV.getApiUrl2)(url));
    }
  }, {
    key: "componentWillMount",
    value: function componentWillMount() {
      var _this2 = this;

      if (!this.props.isShowModal) return;
      this.isWorkDone().then(function (_ref5) {
        var Data = _ref5.Data;
        return _this2.setState({
          isDone: Data.status == 2
        });
      });
      this.getData().then(function (_ref6) {
        var Data = _ref6.Data;
        return _this2.setState({
          milepostData: _this2.reduceData(Data),
          isValid: true
        });
      });
    }
  }, {
    key: "componentWillReceiveProps",
    value: function componentWillReceiveProps(nextProps) {
      var _this3 = this;

      if (nextProps.isShowModal !== this.props.isShowModal && nextProps.isShowModal) {
        this.getData().then(function (_ref7) {
          var Data = _ref7.Data;
          return _this3.setState({
            milepostData: _this3.reduceData(Data),
            isValid: true
          });
        });
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this4 = this;

      var isShowModal = this.props.isShowModal;
      var _this$state = this.state,
          milepostData = _this$state.milepostData,
          isValid = _this$state.isValid,
          isDone = _this$state.isDone;
      return /*#__PURE__*/_react["default"].createElement(_dialog["default"], {
        title: (0, _getLocale.getLocale)('OKR_MyO_Text_krweightsetting'),
        noFooterLine: true,
        visible: !isDone && isShowModal,
        width: "570px",
        isModalValid: isValid // 这个参数就可以在本组件中控制
        ,
        onClose: this.onModalClose,
        onOk: this.handleOk,
        onCancel: this.handleCancel,
        zIndex: 2000
      }, /*#__PURE__*/_react["default"].createElement(_style.EditWightContent, null, milepostData && milepostData.map(function (data, index) {
        var feedId = data.feedId,
            mileStoneId = data.mileStoneId,
            user = data.user,
            mileStoneName = data.mileStoneName,
            krWeight = data.krWeight; // 这里是异步的数据 为毛渲染不出来？

        if (feedId) {
          // 为啥就得这样写呢
          return /*#__PURE__*/_react["default"].createElement(_style.KrListItem, {
            key: mileStoneId,
            style: data.isDirty ? {
              marginBottom: 36
            } : {
              marginBottom: 22
            }
          }, /*#__PURE__*/_react["default"].createElement(_style.KrCounter, null, /*#__PURE__*/_react["default"].createElement("div", {
            className: "kr-counter"
          }, "KR".concat(index + 1))), /*#__PURE__*/_react["default"].createElement(_tooltip["default"], {
            overlay: (0, _openData.parseString)(mileStoneName),
            placement: "top",
            align: {
              offset: [0, 5]
            }
          }, /*#__PURE__*/_react["default"].createElement(_style.KrTitle, null, (0, _openData.parseString)(mileStoneName))), /*#__PURE__*/_react["default"].createElement(_style.FormItemWrapper, {
            style: {
              width: 140
            }
          }, /*#__PURE__*/_react["default"].createElement(_style.FormItemLabel, null, (0, _getLocale.getLocale)('OKR_MyO_Text_Weights')), /*#__PURE__*/_react["default"].createElement(_FormItemV["default"], {
            isDirty: data.isDirty,
            errorText: (0, _getLocale.getLocale)('OKR_MyO_KRP_Please0and100')
          }, /*#__PURE__*/_react["default"].createElement(_Input["default"], {
            suffixIcon: (0, _getLocale.getLocale)('OKR_MyO_Pop_Upd_Percentage'),
            value: krWeight,
            onChange: function onChange(value) {
              return _this4.handleWeightChange(value, feedId);
            },
            onBlur: function onBlur() {
              return _this4.blurReCalibratePrecision();
            }
          }))));
        }
      })));
    }
  }]);

  return EditKrWightModal;
}(_react.Component);

exports["default"] = EditKrWightModal;