"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"] = _default;

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

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

var _dayjs = _interopRequireDefault(require("dayjs"));

var _quarterOfYear = _interopRequireDefault(require("dayjs/plugin/quarterOfYear"));

var _header = _interopRequireDefault(require("./header"));

var _noOkr = _interopRequireDefault(require("../../no-okr"));

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

var _shareDialog = _interopRequireDefault(require("../../share-dialog"));

var _level2Search = _interopRequireDefault(require("../../level2-search"));

var _requestApis = require("../../request-apis");

var _useStorage15 = _interopRequireDefault(require("../../hooks/useStorage"));

var _drawerManager = _interopRequireDefault(require("../../../../components/drawer-manager"));

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

var _unsupportIe = _interopRequireDefault(require("../../unsupport-ie"));

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 _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 asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

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

function _objectDestructuringEmpty(obj) { if (obj == null) throw new TypeError("Cannot destructure undefined"); }

_dayjs["default"].extend(_quarterOfYear["default"]);

function _default(props) {
  _objectDestructuringEmpty(props); // 使用存储的State


  var _useStorage = (0, _useStorage15["default"])('period', {
    annualNum: "".concat(new Date().getFullYear()),
    cycleType: '2',
    yqmNum: "".concat((0, _dayjs["default"])().quarter())
  }),
      _useStorage2 = _slicedToArray(_useStorage, 2),
      period = _useStorage2[0],
      setPeriod = _useStorage2[1];

  var _useStorage3 = (0, _useStorage15["default"])('showkr', false),
      _useStorage4 = _slicedToArray(_useStorage3, 2),
      showkr = _useStorage4[0],
      setShowKr = _useStorage4[1];

  var _useStorage5 = (0, _useStorage15["default"])('showCardKr', false),
      _useStorage6 = _slicedToArray(_useStorage5, 2),
      showCardKr = _useStorage6[0],
      setShowCardKr = _useStorage6[1];

  var _useStorage7 = (0, _useStorage15["default"])('searchType', 'company'),
      _useStorage8 = _slicedToArray(_useStorage7, 2),
      searchType = _useStorage8[0],
      setSearchType = _useStorage8[1];

  var _useStorage9 = (0, _useStorage15["default"])('level2Selected', {}),
      _useStorage10 = _slicedToArray(_useStorage9, 2),
      level2Selected = _useStorage10[0],
      setLevel2Selected = _useStorage10[1];

  var _useStorage11 = (0, _useStorage15["default"])('rootNode', {
    rootId: 0,
    rootName: ''
  }, {
    noLocal: true
  }),
      _useStorage12 = _slicedToArray(_useStorage11, 2),
      rootNode = _useStorage12[0],
      setRootNode = _useStorage12[1];

  var _useState = (0, _react.useState)(true),
      _useState2 = _slicedToArray(_useState, 2),
      exist = _useState2[0],
      setExist = _useState2[1]; // 租户是否有okr


  var _useState3 = (0, _react.useState)(!!level2Selected.name),
      _useState4 = _slicedToArray(_useState3, 2),
      hasSubSearch = _useState4[0],
      setHasSubSearch = _useState4[1];

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

  var _useState7 = (0, _react.useState)('horizontal'),
      _useState8 = _slicedToArray(_useState7, 2),
      direction = _useState8[0],
      setDirection = _useState8[1]; // 默认水平


  var _useState9 = (0, _react.useState)(false),
      _useState10 = _slicedToArray(_useState9, 2),
      fullScreen = _useState10[0],
      setFullScreen = _useState10[1]; // 全屏模式状态


  var _useState11 = (0, _react.useState)({}),
      _useState12 = _slicedToArray(_useState11, 2),
      selectOkr = _useState12[0],
      setSelectOkr = _useState12[1];

  var _useState13 = (0, _react.useState)(false),
      _useState14 = _slicedToArray(_useState13, 2),
      shareDialogVisible = _useState14[0],
      setShareDialogVisible = _useState14[1];

  var _useState15 = (0, _react.useState)(false),
      _useState16 = _slicedToArray(_useState15, 2),
      showMask = _useState16[0],
      setShowMask = _useState16[1];

  var _useStorage13 = (0, _useStorage15["default"])('openLevel', 2),
      _useStorage14 = _slicedToArray(_useStorage13, 2),
      openLevel = _useStorage14[0],
      setOpenLevel = _useStorage14[1];

  var _useState17 = (0, _react.useState)(false),
      _useState18 = _slicedToArray(_useState17, 2),
      forceRender = _useState18[0],
      setForceRender = _useState18[1];

  var okrMapRef = (0, _react.useRef)();
  var okrPage = (0, _react.useRef)();
  (0, _react.useEffect)(function () {
    (0, _requestApis.checkTenantOkrExist)().then(function (res) {
      return setExist(res && res.obj || false);
    });
  }, []);
  (0, _react.useEffect)(function () {
    if (fullScreen) {
      (0, _utils.openFullscreen)();
    } else {
      (0, _utils.closeFullscreen)();
    }
  }, [fullScreen]);
  (0, _react.useEffect)(function () {
    if (searchType == 'company') {
      setRootNode({
        rootId: 0,
        rootName: _utils.tenantName
      });
    } else {
      setRootNode(_objectSpread(_objectSpread({}, level2Selected), {}, {
        rootId: level2Selected.id,
        rootName: level2Selected.name
      }));
    }
  }, [searchType, level2Selected]);

  var onMapActionsHandler = function onMapActionsHandler(iconType) {
    switch (iconType) {
      case 'export':
        exportCurrentFlow();
        break;

      case 'share':
        setShareDialogVisible(true);
        break;

      case 'fullscreen':
        // 全屏
        var cardFlat = document.querySelector('.titaui-menus__menu-card');

        if (cardFlat) {
          cardFlat.style.display = 'none';
        }

        setFullScreen(true);
        break;

      case 'quit-fullscreen':
        // 退出全屏
        var cardFlat = document.querySelector('.titaui-menus__menu-card');

        if (cardFlat) {
          cardFlat.style.display = 'flex';
        }

        setFullScreen(false);
        break;

      case 'horizontal':
        setDirection(iconType);
        setForceRender(true);
        setTimeout(function () {
          return setForceRender(false);
        }, 100);
        break;

      case 'vertical':
        setDirection(iconType);
        setForceRender(true);
        setTimeout(function () {
          return setForceRender(false);
        }, 100);
        break;

      default:
        break;
    }
  }; // 二级搜索，触发搜索更新值


  var setLevel2SelectedHandler = function setLevel2SelectedHandler(node) {
    var restAttrs = {}; // 把用户头像带过去

    if (node.nodeType == 'person') {
      restAttrs.avatar = node.data.avatar;
    }

    setLevel2Selected(_objectSpread({
      name: node.title,
      id: node.id
    }, restAttrs));
  }; // 部门、群组、成员，选项切换后执行
  // 初始化二级搜索值


  var onSearchChangeHandler = function onSearchChangeHandler(iconType) {
    var _window$BSGlobal$logi = window.BSGlobal.loginUserInfo,
        Id = _window$BSGlobal$logi.Id,
        Name = _window$BSGlobal$logi.Name,
        Department = _window$BSGlobal$logi.Department,
        DepartmentId = _window$BSGlobal$logi.DepartmentId,
        UserAvatar = _window$BSGlobal$logi.UserAvatar;
    setSearchType(iconType);

    switch (iconType) {
      case 'company':
        return setHasSubSearch(false);

      case 'depart':
        setLevel2Selected({
          id: DepartmentId,
          name: Department
        });
        break;

      case 'group':
        // 群组的默认显示项为数据列表的第一个节点
        // 清空其他选项值，等待异步回调选中第一个数据
        setLevel2Selected({});
        break;

      case 'user':
        var userAvatar = {
          color: UserAvatar.Color,
          small: UserAvatar.Small,
          hasAvatar: UserAvatar.HasAvatar,
          big: UserAvatar.Original || UserAvatar.original || UserAvatar.Big || UserAvatar.Large
        };
        setLevel2Selected({
          id: Id,
          name: Name,
          avatar: userAvatar // 把用户头像带过去

        });
        break;

      default:
        break;
    }

    setHasSubSearch(true);
  }; // 导出图片


  var exportCurrentFlow = function exportCurrentFlow() {
    okrMapRef.current.exportCurrentFlow();
  };

  var onKrPushUpdateKr = /*#__PURE__*/function () {
    var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(data) {
      var workMileStoneId, workId;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              workMileStoneId = selectOkr && selectOkr.workId;
              workId = selectOkr && selectOkr.parentId;
              (0, _requestApis.onUpdateKr)({
                workId: workId,
                workMileStoneId: workMileStoneId,
                mileStoneName: data
              }).then(function (res) {});

            case 3:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));

    return function onKrPushUpdateKr(_x) {
      return _ref.apply(this, arguments);
    };
  }();

  var onKrPushChange = function onKrPushChange(name, value, id) {
    var data = {};

    if (name == 'user') {
      var avatar = {};

      for (var key in value.UserAvatar) {
        avatar[key[0].toLocaleLowerCase() + key.substring(1)] = value.UserAvatar[key];
      }

      data = {
        user: {
          avatar: avatar,
          name: value.Name,
          userId: value.Id
        }
      };
    } else if (name == 'date') {
      data = {
        startDate: value.startDate,
        endDate: value.endDate
      };
    } else if (name == 'progress') {
      data = {
        progress: value
      };
    } else if (name == 'mileStoneName') {
      data = {
        mileStoneName: value
      };
    } else {
      return;
    } // 回写修改后的数据 进 OKR 地图组件


    okrMapRef.current.updateNodeData({
      data: data,
      id: id
    });
  }; // 点击OKR地图节点后，打开推屏


  var onNodeClickHandler = function onNodeClickHandler(node) {
    var modelType = node.modelType,
        data = node.data;

    if (modelType == 'work') {
      _drawerManager["default"].open('okrDetail', {
        okrId: data.workId
      });
    } else if (modelType == 'kr') {
      if (!data.mapkrVisible) return;
      setSelectOkr(_objectSpread(_objectSpread({}, data), {}, {
        workId: data.mileStoneId,
        workName: data.mileStoneName,
        progress: data.progress,
        modelType: 2,
        parentId: data.workId,
        startData: data.startDate,
        endData: data.endDate,
        parentKrId: 0,
        workCounter: {
          subTotal: data.counter.workTotal
        },
        krTotal: 0,
        principalUser: data.user
      }));

      _drawerManager["default"].open('krDetail', {
        krId: data.mileStoneId
      });
    }
  }; // 删除节点，回写给OKR地图组件


  var onKrDelete = function onKrDelete(_ref2) {
    var id = _ref2.id;
    okrMapRef.current.deleteNode({
      id: id
    });
  };

  var onHideHandler = function onHideHandler() {
    setShowMask(false);
  };

  var onShowHandler = function onShowHandler() {
    setShowMask(true);
  };

  return /*#__PURE__*/_react["default"].createElement(_unsupportIe["default"], null, function (OkrSearchPanel) {
    var _classNames;

    return /*#__PURE__*/_react["default"].createElement("div", {
      className: (0, _classnames["default"])((_classNames = {}, _defineProperty(_classNames, "".concat(_precls["default"], "__dark"), darkTheme), _defineProperty(_classNames, "".concat(_precls["default"], "__fullscreen"), fullScreen), _classNames))
    }, /*#__PURE__*/_react["default"].createElement("div", {
      className: (0, _classnames["default"])(_precls["default"]),
      ref: okrPage
    }, /*#__PURE__*/_react["default"].createElement(_header["default"], {
      onBtnClick: onMapActionsHandler,
      onShowKrClick: function onShowKrClick(val) {
        return setShowKr(val);
      },
      onShowCardKr: function onShowCardKr(val) {
        return setShowCardKr(val);
      },
      onSearchChange: onSearchChangeHandler,
      onPeriodChange: function onPeriodChange(period) {
        return setPeriod(period);
      },
      onThemeChange: function onThemeChange() {
        return setDarkTheme(!darkTheme);
      },
      onLevelChange: function onLevelChange(level) {
        return setOpenLevel(level);
      },
      openLevel: openLevel,
      searchType: searchType,
      fullScreen: fullScreen,
      darkTheme: darkTheme,
      direction: direction,
      showkr: showkr,
      showCardKr: showCardKr,
      period: period
    }), /*#__PURE__*/_react["default"].createElement("div", {
      className: (0, _classnames["default"])("".concat(_precls["default"], "__content"))
    }, function () {
      // 根据选择的搜索类型不同，show出不同的组件
      if (!hasSubSearch) return undefined;
      if (searchType == 'company') return undefined;
      return /*#__PURE__*/_react["default"].createElement(_level2Search["default"], {
        key: searchType,
        type: searchType,
        searchType: searchType,
        selected: level2Selected,
        setSelected: setLevel2SelectedHandler
      });
    }(), function () {
      if (forceRender) {
        return /*#__PURE__*/_react["default"].createElement("span", null);
      }

      if (exist) {
        return /*#__PURE__*/_react["default"].createElement(OkrSearchPanel, _extends({
          ref: okrMapRef,
          showkr: showkr,
          showCardKr: showCardKr,
          direction: direction,
          darkTheme: darkTheme,
          openLevel: openLevel,
          searchType: searchType,
          onNodeClick: onNodeClickHandler
        }, period, rootNode, {
          okrType: _utils.okrTypeMap[searchType]
        }));
      }

      return /*#__PURE__*/_react["default"].createElement(_noOkr["default"], null);
    }(), showMask && /*#__PURE__*/_react["default"].createElement("div", {
      className: (0, _classnames["default"])("".concat(_precls["default"], "__content-mask"))
    })), /*#__PURE__*/_react["default"].createElement(_shareDialog["default"], {
      visible: shareDialogVisible,
      setVisible: setShareDialogVisible,
      period: period,
      showkr: showkr,
      rootNode: rootNode,
      darkTheme: darkTheme,
      direction: direction,
      searchType: searchType,
      level2Selected: level2Selected
    })));
  });
}