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

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

var _moment = _interopRequireDefault(require("moment"));

var _krWeight = _interopRequireDefault(require("./components-new/kr-weight"));

var _okrAlign = _interopRequireDefault(require("./components-new/okr-align"));

var _okrCycle = _interopRequireDefault(require("./components-new/okr-cycle"));

var _okrPrincipal = _interopRequireDefault(require("./components-new/okr-principal"));

var _krConfidence = _interopRequireDefault(require("./components-new/kr-confidence"));

var _okrClassify = _interopRequireDefault(require("./components-new/okr-classify"));

var _okrType = _interopRequireDefault(require("./components-new/okr-type"));

var _okrVisibility = _interopRequireDefault(require("./components-new/okr-visibility"));

var _okrName = _interopRequireDefault(require("./components-new/okr-name"));

var _tableExcelV = _interopRequireDefault(require("../table-excel-v2"));

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

var _hooks2 = _interopRequireDefault(require("../../utils/hooks"));

require("./index.css");

var _setting = require("./setting");

var _classnames = _interopRequireDefault(require("classnames"));

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

var preCls = 'tita-okr-excel-create';

var getIitDatas = function getIitDatas(props) {
  return [(0, _utils.getIitData)(props), (0, _utils.getIitData)(props), (0, _utils.getIitData)(props)];
};

function filterRemoveItem(data) {
  return data.filter(function (_ref) {
    var isDelete = _ref.isDelete;
    return !isDelete;
  }).map(function (item) {
    item.krs = item.krs.filter(function (_ref2) {
      var isDelete = _ref2.isDelete;
      return !isDelete;
    });
    return item;
  });
}

var OKRExcelCreate = function OKRExcelCreate(_ref3) {
  var _ref3$className = _ref3.className,
      className = _ref3$className === void 0 ? '' : _ref3$className,
      _ref3$tableClassName = _ref3.tableClassName,
      tableClassName = _ref3$tableClassName === void 0 ? '' : _ref3$tableClassName,
      okrData = _ref3.okrData,
      onChange = _ref3.onChange;

  var _useState = (0, _react.useState)({}),
      _useState2 = _slicedToArray(_useState, 2),
      dicData = _useState2[0],
      setDicData = _useState2[1];

  (0, _react.useEffect)(function () {
    setDicData((0, _hooks.dic)());
  }, []);
  var annualNum = (0, _hooks2["default"])('annualNum');
  var cycleType = (0, _hooks2["default"])('cycleType');
  var yqmNum = (0, _hooks2["default"])('yqmNum');
  var cycleData = cycleType !== '-1' && {
    annualNum: annualNum,
    cycleType: cycleType,
    yqmNum: yqmNum
  } || {
    annualNum: "".concat(new Date().getFullYear()),
    cycleType: '2',
    yqmNum: "".concat((0, _moment["default"])().quarter())
  };
  var data = (0, _react.useRef)(okrData && okrData.length ? okrData : getIitDatas(cycleData));

  var _useState3 = (0, _react.useState)((0, _utils.formatDataToOKRExcelTableData)(data.current)),
      _useState4 = _slicedToArray(_useState3, 2),
      excelTableData = _useState4[0],
      setExcelTableData = _useState4[1];

  var _useState5 = (0, _react.useState)(false),
      _useState6 = _slicedToArray(_useState5, 2),
      isMax = _useState6[0],
      setIsMax = _useState6[1];

  var _useState7 = (0, _react.useState)(data.current.length <= 1),
      _useState8 = _slicedToArray(_useState7, 2),
      hiddenRemoveIcon = _useState8[0],
      setHiddenRemoveIcon = _useState8[1];

  var update = (0, _react.useCallback)(function (_ref4) {
    var type = _ref4.type,
        rowIdx = _ref4.rowIdx,
        rootIdx = _ref4.rootIdx,
        itemData = _ref4.itemData,
        uuid = _ref4.uuid,
        rootUuid = _ref4.rootUuid;

    if (type === 'update') {
      itemData.krs = _toConsumableArray(itemData.krs);
      var index = data.current.findIndex(function (item) {
        return item.uuid === itemData.uuid;
      });
      data.current[index] = itemData;
    }

    if (type === 'removeO') {
      var _index = data.current.findIndex(function (item) {
        return item.uuid === uuid;
      });

      if (data.current[_index].isSaved) {
        data.current[_index].isDelete = true;
      } else {
        data.current.splice(_index, 1);
      }

      setIsMax(data.current.length >= 50); // 如果只剩最后一个了则隐藏删除按钮

      var effectiveKrs = data.current.filter(function (_ref5) {
        var isDelete = _ref5.isDelete;
        return !isDelete;
      });
      setHiddenRemoveIcon(effectiveKrs.length <= 1);
    }

    if (type === 'removeKr') {
      var rootIndex = data.current.findIndex(function (item) {
        return item.uuid === rootUuid;
      });
      var krIndex = data.current[rootIndex].krs.findIndex(function (item) {
        return item.uuid === uuid;
      }); // 重新计算最后一个 kr 的权重

      var _effectiveKrs = data.current[rootIndex].krs.filter(function (_ref6) {
        var isDelete = _ref6.isDelete;
        return !isDelete;
      });

      var averageWeight = parseFloat((100 / _effectiveKrs.length).toFixed(1));
      data.current[rootIndex].krs.splice(krIndex, 1); // 是否是均分的

      var isAverage = _effectiveKrs.findIndex(function (item) {
        return item.krWeight !== averageWeight;
      }) === -1;

      if (isAverage) {
        data.current[rootIndex].krs = data.current[rootIndex].krs.map(function (item) {
          return _objectSpread(_objectSpread({}, item), {}, {
            krWeight: parseFloat((100 / (_effectiveKrs.length - 1)).toFixed(1))
          });
        });
      } else {
        var newEffectiveKrs = data.current[rootIndex].krs.filter(function (_ref7) {
          var isDelete = _ref7.isDelete;
          return !isDelete;
        });
        var totalWeight = newEffectiveKrs.slice(0, newEffectiveKrs.length - 1).reduce(function (pre, cur) {
          return pre + cur.krWeight;
        }, 0);
        newEffectiveKrs[newEffectiveKrs.length - 1].krWeight = parseFloat((100 - totalWeight).toFixed(1));
        data.current[rootIndex].krs = data.current[rootIndex].krs.map(function (item) {
          return _objectSpread({}, item);
        });
      }
    }

    if (onChange) onChange(data.current.map(function (item) {
      return _objectSpread(_objectSpread({}, item), {}, {
        childs: null
      });
    }));
    setExcelTableData(filterRemoveItem(data.current));
  }, []);
  var columnsOption = (0, _react.useMemo)(function () {
    return [{
      title: dicData['目标（O）'],
      dataIndex: 'name',
      key: 'name',
      width: 400,
      render: (0, _okrName["default"])(update, true)
    }, {
      title: dicData['目标类型'],
      dataIndex: 'okrType',
      key: 'okrType',
      width: 100,
      hidden: !_setting.showKrType,
      render: (0, _okrType["default"])(update)
    }, {
      title: dicData['目标类别'],
      dataIndex: 'okrClassify',
      key: 'okrClassify',
      width: 120,
      hidden: !_setting.showKrClassify,
      render: (0, _okrClassify["default"])(update)
    }, {
      title: dicData['目标周期'],
      dataIndex: 'cycle',
      key: 'cycle',
      width: 200,
      render: (0, _okrCycle["default"])(update)
    }, {
      title: dicData['对齐目标'],
      dataIndex: 'parentOKR.principalUser.name',
      key: 'parentOKR.principalUser.name',
      width: 300,
      render: (0, _okrAlign["default"])(update)
    }, {
      title: dicData['目标负责人'],
      dataIndex: 'principalUser.name',
      key: 'principalUser.name',
      width: 100,
      render: (0, _okrPrincipal["default"])(update, true)
    }, {
      title: dicData['可见范围'],
      dataIndex: 'visibility',
      key: 'visibility',
      width: 150,
      render: (0, _okrVisibility["default"])(update)
    }, {
      title: dicData['关键成果（KR）'],
      dataIndex: 'name',
      key: 'kr.name',
      width: 400,
      level: 2,
      render: (0, _okrName["default"])(update, false)
    }, {
      title: dicData['KR 负责人'],
      dataIndex: 'user.name',
      key: 'kr.user.name',
      width: 160,
      level: 2,
      render: (0, _okrPrincipal["default"])(update, false)
    }, {
      title: dicData['KR 权重'],
      dataIndex: 'krWeight',
      key: 'krWeight',
      width: 160,
      align: 'center',
      level: 2,
      renderFill: true,
      hidden: !_setting.showKrWeight,
      render: (0, _krWeight["default"])(update)
    }, {
      title: dicData['信心指数'],
      dataIndex: 'confidenceIndex',
      key: 'confidenceIndex',
      width: 160,
      align: 'center',
      level: 2,
      hidden: !_setting.showKrConfidence,
      render: (0, _krConfidence["default"])(update)
    }];
  }, [dicData]);

  var onAddOHandler = function onAddOHandler() {
    if (isMax) return;
    data.current.push((0, _utils.getIitData)(cycleData));
    setExcelTableData(filterRemoveItem(data.current));
    if (onChange) onChange(data.current.map(function (item) {
      return _objectSpread(_objectSpread({}, item), {}, {
        childs: null
      });
    }));
    setIsMax(data.current.length >= 50); // 如果只剩最后一个了则隐藏删除按钮

    var effectiveKrs = data.current.filter(function (_ref8) {
      var isDelete = _ref8.isDelete;
      return !isDelete;
    });
    setHiddenRemoveIcon(effectiveKrs.length <= 1);
  }; // {/* <PopupSelect
  //   menuData={columnCtlData}
  //   popupPlacement="bottomLeft"
  //   action="click"
  //   mode="checkbox"
  //   height={292}
  //   onChange={onColumnsHideOrShow}
  //   autoClose={false}
  // >
  //   <div className={`${preCls}__column-ctl`}>
  //     <span className="tu-icon-APP-shezhi" />
  //   </div>
  // </PopupSelect> */}


  return /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(className)
  }, /*#__PURE__*/_react["default"].createElement(_tableExcelV["default"], {
    className: (0, _classnames["default"])("".concat(preCls, "__table-excel-v2 ").concat(tableClassName), _defineProperty({}, "".concat(preCls, "--disabled-remove"), hiddenRemoveIcon)),
    rowKey: "uuid",
    fixedHeader: true // pinned={[1, 0]}
    ,
    columns: columnsOption,
    dataSource: excelTableData,
    rowLastNode: /*#__PURE__*/_react["default"].createElement("div", {
      onClick: onAddOHandler,
      className: "".concat(preCls, "__add-o")
    }, /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement("i", {
      className: "tu-icon-add1"
    }), /*#__PURE__*/_react["default"].createElement("p", null, (0, _getLocale.getLocale)(isMax ? 'OKR_ComAll_Supports50' : 'OKR_ComAll_AddObjective'))))
  }));
};

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