"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 _titaUi = require("tita-ui");

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

var _userSelector = _interopRequireDefault(require("../../user-selector"));

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

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

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

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 _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 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 _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 visibilityList = [{
  value: 2,
  lable: (0, _getLocale.getLocale)("OKR_MyO_From_Associatedmem")
}, {
  value: 3,
  lable: (0, _getLocale.getLocale)("OKR_MyO_Pop_Directrep")
}, {
  value: 4,
  lable: (0, _getLocale.getLocale)("OKR_MyO_Pop_Specified")
}];

if (window.BSGlobal.tenantInfo.isOpenInfo) {
  visibilityList.unshift({
    value: 1,
    lable: (0, _getLocale.getLocale)("OKR_MyO_Pop_Public")
  });
}

function _default(_ref) {
  var _ref$canEdit = _ref.canEdit,
      canEdit = _ref$canEdit === void 0 ? false : _ref$canEdit,
      workId = _ref.workId,
      _ref$visibilityProp = _ref.visibilityProp,
      visibilityProp = _ref$visibilityProp === void 0 ? 2 : _ref$visibilityProp,
      _ref$visiableScopePro = _ref.visiableScopeProp,
      visiableScopeProp = _ref$visiableScopePro === void 0 ? {} : _ref$visiableScopePro,
      onSave = _ref.onSave;
  var selectorRef = (0, _react.useRef)();

  var _useState = (0, _react.useState)(visiableScopeProp),
      _useState2 = _slicedToArray(_useState, 2),
      visibilityArea = _useState2[0],
      setVisibilityArea = _useState2[1];

  var _useState3 = (0, _react.useState)(visibilityProp),
      _useState4 = _slicedToArray(_useState3, 2),
      visibility = _useState4[0],
      setVisibility = _useState4[1];

  var updateVisibility = /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      var _visibilityArea$users, users, _visibilityArea$depar, departments, _visibilityArea$group, groups, areaUserIds, areaOrgIds, areaGroupIds;

      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _visibilityArea$users = visibilityArea.users, users = _visibilityArea$users === void 0 ? [] : _visibilityArea$users, _visibilityArea$depar = visibilityArea.departments, departments = _visibilityArea$depar === void 0 ? [] : _visibilityArea$depar, _visibilityArea$group = visibilityArea.groups, groups = _visibilityArea$group === void 0 ? [] : _visibilityArea$group;
              areaUserIds = (users || []).reduce(function (res, cur) {
                return [].concat(_toConsumableArray(res), [cur.userId]);
              }, []);
              areaOrgIds = (departments || []).reduce(function (res, cur) {
                return [].concat(_toConsumableArray(res), [cur.id]);
              }, []);
              areaGroupIds = (groups || []).reduce(function (res, cur) {
                return [].concat(_toConsumableArray(res), [cur.id]);
              }, []);
              _context.next = 6;
              return (0, _requestApi.updateOkrVisibility)({
                workId: workId,
                visibility: visibility,
                areaUserIds: areaUserIds,
                areaOrgIds: areaOrgIds,
                areaGroupIds: areaGroupIds
              });

            case 6:
              onSave && onSave();

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

    return function updateVisibility() {
      return _ref2.apply(this, arguments);
    };
  }();

  (0, _react.useEffect)(function () {
    if (!visibility) return;
    updateVisibility();
  }, [visibility, visibilityArea]);

  var onOptionChange = function onOptionChange(v) {
    if (v === 4) {
      selectorRef.current && selectorRef.current.open();
    } else {
      setVisibility(v);
    }
  };

  var onOk = function onOk(selectNodes) {
    setVisibility(4);
    setVisibilityArea(selectNodes);
    selectorRef.current && selectorRef.current.close();
  };

  var renderLabel = function renderLabel() {
    if (visibility === 4) {
      var _visibilityArea$group2 = visibilityArea.groups,
          groups = _visibilityArea$group2 === void 0 ? [] : _visibilityArea$group2,
          _visibilityArea$depar2 = visibilityArea.departments,
          departments = _visibilityArea$depar2 === void 0 ? [] : _visibilityArea$depar2,
          _visibilityArea$users2 = visibilityArea.users,
          users = _visibilityArea$users2 === void 0 ? [] : _visibilityArea$users2;
      var text = [];
      var jsxDom = [];
      (departments || []).forEach(function (item) {
        jsxDom.push( /*#__PURE__*/_react["default"].createElement(_openData.OpenDepartmentName, {
          id: item.id,
          name: item.name
        }));
        jsxDom.push( /*#__PURE__*/_react["default"].createElement("span", null, "\u3001"));
        text.push(item.name);
      });
      (users || []).forEach(function (item) {
        jsxDom.push( /*#__PURE__*/_react["default"].createElement(_openData.OpenUserName, {
          id: item.userId,
          name: item.name
        }));
        jsxDom.push( /*#__PURE__*/_react["default"].createElement("span", null, "\u3001"));
        text.push(item.name);
      });
      (groups || []).forEach(function (item) {
        jsxDom.push( /*#__PURE__*/_react["default"].createElement("span", null, item.name, "\u3001"));
        text.push(item.name);
      });
      if (!text.length) return (0, _getLocale.getLocale)('OKR_MyO_E_Associatedm');
      return (0, _openData.isWechat)() ? jsxDom : text.join('、');
    } // @ts-ignore


    return visibilityList.find(function (i) {
      return i.value === visibility;
    }).lable;
  };

  var renderSelect = function renderSelect() {
    return /*#__PURE__*/_react["default"].createElement("div", {
      className: "visibility"
    }, /*#__PURE__*/_react["default"].createElement("span", null, renderLabel()), canEdit && /*#__PURE__*/_react["default"].createElement(_tooltip["default"], {
      overlay: (0, _getLocale.getLocale)('Mod_Editor')
    }, /*#__PURE__*/_react["default"].createElement("span", {
      className: "tu-icon-edit visibility-edit-icon tu-ml-10"
    })));
  };

  return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, canEdit && /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_userSelector["default"], {
    ref: selectorRef // @ts-ignore
    ,
    multiple: true,
    onOk: onOk,
    position: "center",
    selectNodes: visibilityArea,
    trigger: /*#__PURE__*/_react["default"].createElement("div", {
      style: {
        visibility: 'hidden',
        position: 'absolute',
        zIndex: -1,
        height: 36
      }
    }, "empty select")
  }), /*#__PURE__*/_react["default"].createElement(_titaUi.Select, {
    value: visibility,
    onChange: onOptionChange,
    options: visibilityList // @ts-ignore
    ,
    onClick: function onClick(e) {
      return e.stopPropagation();
    },
    renderSelect: renderSelect
  })), !canEdit && renderSelect());
}