"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"] = exports.ViewType = exports.MoreMenuType = void 0;

var _react = _interopRequireWildcard(require("react"));

var _reactRouter = require("react-router");

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

var _guideTip = _interopRequireDefault(require("../../../components/guide-tip"));

var _keywordSearch = _interopRequireDefault(require("../../../components/keyword-search"));

var _popupSelect = _interopRequireDefault(require("../../../components/popup-select"));

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

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

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

var _localStorage = require("../../../utils/local-storage");

var _context = require("../context");

var _precls = require("../precls");

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

var _comments = _interopRequireDefault(require("./comments"));

var _createOkr = _interopRequireDefault(require("./create-okr"));

var _departTitle = _interopRequireDefault(require("./depart-title"));

var _filter = _interopRequireDefault(require("./filter"));

var _okrImport = _interopRequireDefault(require("./okr-import"));

var _operateRecord = _interopRequireDefault(require("./operate-record"));

var _relationTitle = _interopRequireDefault(require("./relation-title"));

var _userTitle = _interopRequireDefault(require("./user-title"));

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 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 _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 ViewType;
exports.ViewType = ViewType;

(function (ViewType) {
  ViewType["Card"] = "card";
  ViewType["Table"] = "table";
  ViewType["Map"] = "map";
})(ViewType || (exports.ViewType = ViewType = {}));

var MoreMenuType;
exports.MoreMenuType = MoreMenuType;

(function (MoreMenuType) {
  MoreMenuType["Adds"] = "adds";
  MoreMenuType["Record"] = "record";
  MoreMenuType["ImportOkr"] = "importOkr";
})(MoreMenuType || (exports.MoreMenuType = MoreMenuType = {}));

var viewConfig = function viewConfig() {
  return {
    table: {
      icon: 'tu-icon-pc-table-s',
      title: (0, _getLocale.getLocale)('OKR_MyO_KRP_Table')
    },
    card: {
      icon: 'tu-icon-pc-card-s',
      title: (0, _getLocale.getLocale)('Pro_Butt_Card')
    },
    map: {
      icon: 'tu-icon-yangshi-ditu',
      title: (0, _getLocale.getLocale)('OKR_MyO_Text_Alignment')
    }
  };
};

var getTableTip = function getTableTip() {
  var _window$BSGlobal$logi;

  return !localStorage.getItem("OkrTableTypeTip_".concat((_window$BSGlobal$logi = window.BSGlobal.loginUserInfo) === null || _window$BSGlobal$logi === void 0 ? void 0 : _window$BSGlobal$logi.Id));
};

var setTableTip = function setTableTip() {
  var _window$BSGlobal$logi2;

  localStorage.setItem("OkrTableTypeTip_".concat((_window$BSGlobal$logi2 = window.BSGlobal.loginUserInfo) === null || _window$BSGlobal$logi2 === void 0 ? void 0 : _window$BSGlobal$logi2.Id), 'true');
}; // const Auth = new BaseAuth()
// const okrImportShow = Auth.isAssistant() || Auth.isBoss() || Auth.isDepartmentLeader() || Auth.isManager() || Auth.isSuperManager()


var titaTracker = function titaTracker(type) {
  var name = {
    card: '卡片',
    table: '表格',
    map: '地图'
  }[type];

  if (window.titaTracker && !localStorage.getItem('titaccc')) {
    window.titaTracker('action').record({
      productName: 'OKR展示模式',
      actionGroup: '选择OKR展示模式',
      actionName: "\u9009\u62E9OKR\u5C55\u793A\u6A21\u5F0F\uFF1A".concat(name)
    });
  }
};

var getViewTypeMenuData = function getViewTypeMenuData(relationShip) {
  return [{
    label: /*#__PURE__*/_react["default"].createElement("p", {
      className: "".concat(_precls.precls, "__view-tyoe-list-item")
    }, /*#__PURE__*/_react["default"].createElement("span", {
      className: "tu-icon-pc-card-s"
    }), /*#__PURE__*/_react["default"].createElement("span", null, (0, _getLocale.getLocale)('Pro_Butt_Card'))),
    value: 'card'
  }, {
    label: /*#__PURE__*/_react["default"].createElement("p", {
      className: "".concat(_precls.precls, "__view-tyoe-list-item")
    }, /*#__PURE__*/_react["default"].createElement("span", {
      className: "tu-icon-pc-table-s"
    }), /*#__PURE__*/_react["default"].createElement("span", null, (0, _getLocale.getLocale)('OKR_MyO_KRP_Table'))),
    value: 'table'
  }, {
    label: /*#__PURE__*/_react["default"].createElement("p", {
      className: "".concat(_precls.precls, "__view-tyoe-list-item")
    }, /*#__PURE__*/_react["default"].createElement("span", {
      className: "tu-icon-yangshi-ditu"
    }), /*#__PURE__*/_react["default"].createElement("span", null, (0, _getLocale.getLocale)('OKR_MyO_Text_Alignment'))),
    value: 'map',
    visible: relationShip === 1
  }];
};

function Header(props, ref) {
  var _useContext = (0, _react.useContext)(_context.Context),
      departmentName = _useContext.departmentName,
      departmentId = _useContext.departmentId,
      toUserId = _useContext.toUserId,
      relation = _useContext.relation,
      annualNum = _useContext.annualNum,
      cycleType = _useContext.cycleType,
      yqmNum = _useContext.yqmNum;

  var history = (0, _reactRouter.useHistory)();
  var relationShip = parseInt(relation, 10);
  var onSearch = props.onSearch,
      onFrontAddOKR = props.onFrontAddOKR,
      _props$viewType = props.viewType,
      defaultViewType = _props$viewType === void 0 ? ViewType.Card : _props$viewType,
      onChangeViewType = props.onChangeViewType;

  var _useState = (0, _react.useState)(false),
      _useState2 = _slicedToArray(_useState, 2),
      onlyThisDept = _useState2[0],
      setOnlyThisDept = _useState2[1];

  var _useState3 = (0, _react.useState)(defaultViewType),
      _useState4 = _slicedToArray(_useState3, 2),
      viewType = _useState4[0],
      setViewType = _useState4[1];

  var _useState5 = (0, _react.useState)(getViewTypeMenuData(relationShip)),
      _useState6 = _slicedToArray(_useState5, 2),
      viewTypeMenuData = _useState6[0],
      setViewTypeMenuData = _useState6[1];

  var _useState7 = (0, _react.useState)(),
      _useState8 = _slicedToArray(_useState7, 2),
      moreMenuSelectValue = _useState8[0],
      setMoreMenuSelectValue = _useState8[1];

  var moreMenuData = (0, _react.useMemo)(function () {
    return [{
      label: (0, _getLocale.getLocale)('OKR_ComAll_Batchcreation'),
      icon: 'APPgengduo',
      value: MoreMenuType.Adds
    }, {
      label: (0, _getLocale.getLocale)('OKR_ComAll_ImportingOKR'),
      icon: 'daoru1',
      value: MoreMenuType.ImportOkr
    }, {
      label: (0, _getLocale.getLocale)('Per_details_OperationRecord'),
      icon: 'jinzhan-s',
      value: MoreMenuType.Record,
      visible: Number(cycleType) !== -1 && ![2, 3].includes(Number(relation)) && departmentId === undefined
    }];
  }, [cycleType, relation, departmentId]);

  var _useState9 = (0, _react.useState)(false),
      _useState10 = _slicedToArray(_useState9, 2),
      init = _useState10[0],
      setInit = _useState10[1];

  var _useState11 = (0, _react.useState)(getTableTip()),
      _useState12 = _slicedToArray(_useState11, 2),
      showTableTip = _useState12[0],
      setShowTableTip = _useState12[1];

  var _useState13 = (0, _react.useState)(),
      _useState14 = _slicedToArray(_useState13, 2),
      userInfo = _useState14[0],
      setUserInfo = _useState14[1];

  var okrImportRef = (0, _react.useRef)(null);
  (0, _react.useEffect)(function () {
    setViewTypeMenuData(getViewTypeMenuData(relationShip));
  }, [relationShip]);
  (0, _react.useEffect)(function () {
    if (toUserId !== undefined || relationShip === 1) {
      var userId = toUserId;
      if (relationShip === 1) userId = (0, _bsGlobal.getUserInfo)().Id;

      if (userId) {
        (0, _requestApi.getUserInfoById)(userId).then(function (res) {
          setUserInfo(res.Data);
        });
      }
    }
  }, [toUserId, relation]);
  (0, _react.useEffect)(function () {
    setInit(true);
  }, []);
  (0, _react.useEffect)(function () {
    if (init) {
      onSearch({
        onlyThisDept: onlyThisDept
      });
    }
  }, [onlyThisDept]);
  var createOkrRef = (0, _react.useRef)();
  (0, _react.useImperativeHandle)(ref, function () {
    return {
      openCreateModal: function openCreateModal() {
        return createOkrRef.current.openCreateModal();
      },
      setCase: function setCase(data) {
        return createOkrRef.current.setCase(data);
      }
    };
  });

  var gotoOkrMap = function gotoOkrMap() {
    var _window$BSGlobal$tena, _window$BSGlobal$tena2;

    var rootNode = {
      rootId: 0,
      // @ts-ignore
      rootName: ((_window$BSGlobal$tena = window.BSGlobal.tenantInfo) === null || _window$BSGlobal$tena === void 0 ? void 0 : _window$BSGlobal$tena.Name) || ''
    };
    var level2Selected = {
      id: 0,
      // @ts-ignore
      name: ((_window$BSGlobal$tena2 = window.BSGlobal.tenantInfo) === null || _window$BSGlobal$tena2 === void 0 ? void 0 : _window$BSGlobal$tena2.Name) || ''
    };
    var searchType = 'company';

    if (departmentId && departmentId !== -1) {
      rootNode.rootId = departmentId;
      rootNode.rootName = departmentName || '';
      searchType = 'depart';
      level2Selected.id = departmentId;
      level2Selected.name = departmentName || '';
    }

    if (toUserId) {
      rootNode.rootId = toUserId;
      rootNode.rootName = userInfo.name || '';
      searchType = 'user';
      level2Selected.id = toUserId;
      level2Selected.name = userInfo.name || '';
    }

    if (parseInt(relation, 10) === 1) {
      rootNode.rootId = (0, _bsGlobal.getUserInfo)().Id;
      rootNode.rootName = (0, _bsGlobal.getUserInfo)().Name || '';
      searchType = 'user';
      level2Selected.id = (0, _bsGlobal.getUserInfo)().Id;
      level2Selected.name = (0, _bsGlobal.getUserInfo)().Name || '';
    }

    var urlQuery = ["searchType=".concat(searchType), "period=".concat(JSON.stringify({
      cycleType: cycleType,
      annualNum: annualNum,
      yqmNum: yqmNum
    })), "rootNode=".concat(JSON.stringify(rootNode)), "level2Selected=".concat(JSON.stringify(level2Selected))].join('&');
    var origin = window.location.href.split('#')[0];
    window.location.href = "".concat(origin, "/#okr/map?").concat(urlQuery);
  };

  var getTitle = function getTitle() {
    if (relationShip === 1) {
      return /*#__PURE__*/_react["default"].createElement(_userTitle["default"], {
        toUserId: (0, _bsGlobal.getUserInfo)().Id
      });
    }

    if (relationShip === 2 || relationShip === 3) {
      return /*#__PURE__*/_react["default"].createElement(_relationTitle["default"], {
        relation: relation
      });
    }

    if (toUserId) {
      return /*#__PURE__*/_react["default"].createElement(_userTitle["default"], {
        toUserId: toUserId
      });
    }

    if (departmentName) {
      return /*#__PURE__*/_react["default"].createElement(_departTitle["default"], {
        onlyThisDept: onlyThisDept,
        onChange: setOnlyThisDept,
        departmentName: departmentName,
        departmentId: departmentId
      });
    }

    return null;
  };

  var onChangeViewTypeHandler = (0, _react.useCallback)(function (type) {
    titaTracker(type);

    if (type === ViewType.Map) {
      gotoOkrMap();
      return;
    }

    setViewType(type);
    if (onChangeViewType) onChangeViewType(type);
  }, [onChangeViewType]);
  var viewInfo = viewConfig()[viewType];
  var onHideTableTip = (0, _react.useCallback)(function () {
    setTableTip();
    setShowTableTip(false);
  }, []); // 设置默认季度

  var useLocalStorage = new _localStorage.LocalStorage();
  var cacheFilterParams = useLocalStorage.getItem('okr-filter-cycle');

  var _useState15 = (0, _react.useState)(cacheFilterParams || {
    annualNum: "".concat(new Date().getFullYear()),
    cycleType: '2',
    yqmNum: "".concat((0, _moment["default"])().quarter())
  }),
      _useState16 = _slicedToArray(_useState15, 2),
      searchParams = _useState16[0],
      setSearchParams = _useState16[1];

  var onChangeMoreMenuHandler = (0, _react.useCallback)(function (value) {
    if (value === MoreMenuType.Adds) {
      var _searchParams$annualN = searchParams.annualNum,
          _annualNum = _searchParams$annualN === void 0 ? new Date().getFullYear() : _searchParams$annualN,
          _searchParams$cycleTy = searchParams.cycleType,
          _cycleType = _searchParams$cycleTy === void 0 ? '2' : _searchParams$cycleTy,
          _searchParams$yqmNum = searchParams.yqmNum,
          _yqmNum = _searchParams$yqmNum === void 0 ? (0, _moment["default"])().quarter() : _searchParams$yqmNum;

      history.push("/excel-okr-create?annualNum=".concat(_annualNum, "&cycleType=").concat(_cycleType, "&yqmNum=").concat(_yqmNum));
      return;
    } else if (value === MoreMenuType.ImportOkr) {
      if (okrImportRef.current) {
        // @ts-ignore
        okrImportRef.current.showOkrImport();
      }
    }

    setMoreMenuSelectValue(value);
  }, [searchParams]);

  var _onSearch = (0, _react.useCallback)(function (params) {
    if (params.annualNum !== undefined) setSearchParams(_objectSpread({}, params));
    if (onSearch) onSearch(params);
  }, [onSearch, setSearchParams]);

  var onOperateRecordCloseHandler = (0, _react.useCallback)(function () {
    setMoreMenuSelectValue(undefined);
  }, []);
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(_precls.precls, "__header")
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(_precls.precls, "__header-left")
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(_precls.precls, "__header-item")
  }, getTitle())), /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(_precls.precls, "__header-right")
  }, Number(departmentId) === 0 && /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(_precls.precls, "__header-item")
  }, /*#__PURE__*/_react["default"].createElement(_keywordSearch["default"], {
    onSearch: onSearch
  })), ![2, 3].includes(relationShip) &&
  /*#__PURE__*/
  // 我关注的 我参与的 没有创建按钮
  _react["default"].createElement("div", {
    className: "".concat(_precls.precls, "__header-item")
  }, /*#__PURE__*/_react["default"].createElement(_createOkr["default"], {
    ref: createOkrRef,
    onFrontAddOKR: onFrontAddOKR
  })), /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(_precls.precls, "__header-item")
  }, /*#__PURE__*/_react["default"].createElement(_guideTip["default"], {
    visible: showTableTip,
    content: /*#__PURE__*/_react["default"].createElement("div", {
      className: "".concat(_precls.precls, "__table-tip")
    }, "\u65B0\u589E OKR \u8868\u683C\u67E5\u770B\u6A21\u5F0F\uFF0C\u67E5\u770B\u66F4\u4FBF\u6377\uFF0C\u5207\u6362\u4F53\u9A8C\u4E00\u4E0B"),
    onClickClose: setTableTip,
    popupPlacement: "bottom",
    zIndex: 1000
  }, /*#__PURE__*/_react["default"].createElement(_popupSelect["default"], {
    menuData: viewTypeMenuData,
    popupPlacement: "bottom",
    action: "click",
    onChange: onChangeViewTypeHandler,
    onVisableChange: onHideTableTip
  }, /*#__PURE__*/_react["default"].createElement(_tooltip["default"], {
    overlay: viewInfo.title,
    placement: "top"
  }, /*#__PURE__*/_react["default"].createElement("span", {
    className: "".concat(_precls.precls, "__header-icon--view-type")
  }, /*#__PURE__*/_react["default"].createElement("span", {
    className: viewInfo.icon
  }), /*#__PURE__*/_react["default"].createElement("span", {
    className: "tu-icon-caret-down ".concat(_precls.precls, "__header-down-icon")
  })))))), /*#__PURE__*/_react["default"].createElement(_comments["default"], {
    toUserId: toUserId,
    relation: relationShip,
    userInfo: userInfo
  }), /*#__PURE__*/_react["default"].createElement(_filter["default"], {
    onSearch: _onSearch
  }), relationShip === 1 && /*#__PURE__*/_react["default"].createElement(_popupSelect["default"], {
    menuData: moreMenuData,
    popupPlacement: "bottomRight",
    action: "click",
    onChange: onChangeMoreMenuHandler
  }, /*#__PURE__*/_react["default"].createElement(_tooltip["default"], {
    overlay: (0, _getLocale.getLocale)('Feed_Set_Pop_Butt_More'),
    placement: "top"
  }, /*#__PURE__*/_react["default"].createElement("span", {
    className: "".concat(_precls.precls, "__header-record")
  }, /*#__PURE__*/_react["default"].createElement("i", {
    className: "tu-icon-more1"
  })))), userInfo && /*#__PURE__*/_react["default"].createElement(_operateRecord["default"], {
    toUserId: toUserId,
    userInfo: userInfo,
    onClose: onOperateRecordCloseHandler,
    activation: moreMenuSelectValue === MoreMenuType.Record,
    relation: relationShip,
    okrFeedParams: {
      objId: departmentId === undefined ? Number(toUserId || (0, _bsGlobal.getUserInfo)().Id) : Number(departmentId),
      // 人员或部门Id
      objType: departmentId === undefined ? 1 : 2,
      // 1：负责人，2：部门
      cycleType: Number(cycleType),
      // 目标周期：0-自定义，1-年度，2-季度，3-月度
      yqmNum: Number(yqmNum),
      annualNum: Number(annualNum)
    }
  }), Number(departmentId) === 0 && /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(_precls.precls, "__header-item")
  }, /*#__PURE__*/_react["default"].createElement(_okrImport["default"], null)), /*#__PURE__*/_react["default"].createElement(_okrImport["default"].OkrImportModal, {
    ref: okrImportRef
  })));
}

var _default = /*#__PURE__*/(0, _react.forwardRef)(Header);

exports["default"] = _default;