"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 _classnames = _interopRequireDefault(require("classnames"));

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

var _avatar = _interopRequireDefault(require("../../avatar"));

var _progress = _interopRequireDefault(require("../../progress"));

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

var _statusTime = _interopRequireDefault(require("../../status-time"));

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

var _ePriority = _interopRequireDefault(require("../../e-priority"));

var _dialogConfirm = _interopRequireWildcard(require("../../dialog-confirm"));

var _eStatusDropdown = _interopRequireDefault(require("./e-status-dropdown"));

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

var _constant = require("./constant");

var _getProcessColor = _interopRequireDefault(require("./get-process-color"));

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

var _platform = require("../../../utils/platform");

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

var _helpers = require("../../../utils/helpers");

var _auth = require("../../../utils/auth");

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

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

var TooltipText = _tooltip["default"].Text; // status=3 已过期 status=2 已完成

function ETaskNode(props) {
  var _okrInfo$authority;

  var index = props.index,
      title = props.title,
      data = props.data,
      _props$createUserId = props.createUserId,
      createUserId = _props$createUserId === void 0 ? {} : _props$createUserId,
      _props$krUser = props.krUser,
      krUser = _props$krUser === void 0 ? {} : _props$krUser,
      _props$hasProgress = props.hasProgress,
      hasProgress = _props$hasProgress === void 0 ? true : _props$hasProgress,
      _props$hasRelation = props.hasRelation,
      hasRelation = _props$hasRelation === void 0 ? true : _props$hasRelation,
      _props$isPushScreen = props.isPushScreen,
      isPushScreen = _props$isPushScreen === void 0 ? true : _props$isPushScreen,
      _props$hasPrinciple = props.hasPrinciple,
      hasPrinciple = _props$hasPrinciple === void 0 ? true : _props$hasPrinciple;

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

  var _useState3 = (0, _react.useState)(data.progress),
      _useState4 = _slicedToArray(_useState3, 1),
      progress = _useState4[0];

  var _useState5 = (0, _react.useState)(data.principalUser || {}),
      _useState6 = _slicedToArray(_useState5, 2),
      user = _useState6[0],
      setUser = _useState6[1];

  var _useState7 = (0, _react.useState)(data.status === 2),
      _useState8 = _slicedToArray(_useState7, 2),
      isGray = _useState8[0],
      setIsGray = _useState8[1];

  var _useState9 = (0, _react.useState)(data.status === 4),
      _useState10 = _slicedToArray(_useState9, 2),
      isCancel = _useState10[0],
      setIsCancel = _useState10[1];

  var _useState11 = (0, _react.useState)("".concat(data.priority)),
      _useState12 = _slicedToArray(_useState11, 2),
      priority = _useState12[0],
      setPriority = _useState12[1];

  var _useState13 = (0, _react.useState)({
    deadLine: data.deadLine,
    isLongTerm: data.isLongTerm,
    status: data.status,
    riskLevel: data.riskLevel
  }),
      _useState14 = _slicedToArray(_useState13, 2),
      dataInfo = _useState14[0],
      setDataInfo = _useState14[1];

  var _useState15 = (0, _react.useState)(function () {
    return (0, _bsGlobal.getBSGlobal)('TaskAdvancedSetting').TaskFunctionSetting.TaskPriority;
  }),
      _useState16 = _slicedToArray(_useState15, 1),
      isShowPriority = _useState16[0];

  var okrInfo = {}; // extraEditAuth = new KRAuth({ user: krUser, createUserId }).hasAuth()
  // || new OAuth({
  //   principalUser: okrInfo.principalUser,
  //   createUserId: okrInfo.createUserId,
  // }).hasAuth()

  var hasEditAuth = new _auth.EAuth({
    principalUser: data.principalUser,
    user: data.user
  }).hasAuth() && // || extraEditAuth
  data.status !== 5;
  var isParticipant = ((_okrInfo$authority = okrInfo.authority) === null || _okrInfo$authority === void 0 ? void 0 : _okrInfo$authority.roleRelation) && okrInfo.authority.roleRelation.roleType === 2;
  var hasRelativeAuth = new _auth.KRAuth({
    user: krUser,
    createUserId: createUserId
  }).hasAuth() || new _auth.OAuth({
    principalUser: okrInfo.principalUser,
    createUserId: okrInfo.createUserId
  }).hasAuth();

  var onEditUserHandler = function onEditUserHandler(_ref) {
    var _ref2 = _slicedToArray(_ref, 1),
        user = _ref2[0];

    (0, _requestApis.updateTaskPrincipal)({
      taskId: data.taskId,
      toUserId: Number(user.id)
    }).then(function (data) {
      if (data.Code === 1) {
        setUser(user.data);

        _toast["default"].Success((0, _getLocale.getLocale)('Mod_Successfuloperat'), {
          canClose: false
        });
      } else {
        _toast["default"].Error(data.Message, {
          canClose: false
        });
      }
    })["catch"](function () {
      _toast["default"].Error('网络异常', {
        canClose: false
      });
    });
  };

  var onEStatusChangeHandler = function onEStatusChangeHandler(statusType) {
    (0, _requestApis.updateTaskStatus)({
      taskId: data.taskId,
      status: _constant.EStatusClass2StatusType[statusType]
    }).then(function (resp) {
      if (resp.Code === 1) {
        _toast["default"].Success((0, _getLocale.getLocale)('Mod_Successfuloperat'), {
          canClose: false
        });

        setDataInfo(_objectSpread(_objectSpread({}, dataInfo), {}, {
          status: _constant.EStatusClass2StatusType[statusType]
        }));
        setIsGray(_constant.EStatusClass2StatusType[statusType] === 2);
        setIsCancel(_constant.EStatusClass2StatusType[statusType] === 4);
      } else {
        _toast["default"].Error(resp.Message, {
          canClose: false
        });
      }
    })["catch"](function () {
      _toast["default"].Error('网络异常', {
        canClose: false
      });
    });
  };

  var onSureUnConnectHandler = function onSureUnConnectHandler() {
    (0, _requestApis.cancelRel)({
      krId: data.mileStoneId,
      objType: data.objType,
      okrId: okrInfo.workId,
      taskId: data.taskId
    }).then(function (resp) {
      if (resp.Code === 1) {
        _toast["default"].Success((0, _getLocale.getLocale)('Mod_Successfuloperat'), {
          canClose: false
        });
      } else {
        _toast["default"].Error(resp.Message, {
          canClose: false
        });
      }
    })["catch"](function () {
      _toast["default"].Error('网络异常', {
        canClose: false
      });
    })["finally"](setUnConnectVisible(false));
  };

  var updateDateHandler = /*#__PURE__*/function () {
    var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(e) {
      var res;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              if (!(!hasEditAuth || dataInfo.status === 2)) {
                _context.next = 2;
                break;
              }

              return _context.abrupt("return");

            case 2:
              _context.next = 4;
              return window.openDatePicker(e.target, {
                isShowCycleView: false,
                rangepickerOptions: {
                  startDate: dataInfo.startDate,
                  endDate: dataInfo.deadLine
                }
              });

            case 4:
              res = _context.sent;
              _context.next = 7;
              return (0, _requestApis.updateTaskDate)({
                taskId: data.taskId,
                startDate: res.startDate,
                endDate: res.endDate,
                isLongTerm: res.isLongTerm
              }).then(function (resp) {
                if (resp.Code === 1) {
                  setDataInfo(_objectSpread(_objectSpread({}, dataInfo), {}, {
                    deadLine: resp.Data.deadLine,
                    isLongTerm: resp.Data.isLongTerm,
                    status: resp.Data.status
                  }));

                  _toast["default"].Success((0, _getLocale.getLocale)('Mod_Successfuloperat'), {
                    canClose: false
                  });
                } else {
                  _toast["default"].Error(resp.Message, {
                    canClose: false
                  });
                }
              })["catch"](function () {
                _toast["default"].Error('网络异常', {
                  canClose: false
                });
              });

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

    return function updateDateHandler(_x) {
      return _ref3.apply(this, arguments);
    };
  }();

  var onEPriorityChangeHandler = function onEPriorityChangeHandler(selectPriority) {
    (0, _requestApis.setTaskPriority)({
      taskId: data.taskId,
      priority: selectPriority
    }).then(function (resp) {
      if (resp.Code === 1) {
        _toast["default"].Success(resp.Message);

        setPriority(selectPriority);
      } else {
        _toast["default"].Error(resp.Message);
      }
    });
  };

  var handleShowTaskDetail = function handleShowTaskDetail() {
    if ((0, _platform.isPlatform)('dd')) {
      _drawerManager["default"].close();
    }

    if (isPushScreen) {
      var _window$Talent, _window$Talent2;

      (_window$Talent = window.Talent) === null || _window$Talent === void 0 ? void 0 : _window$Talent.app.vent.off("global-pull-screen:closed:".concat(data.taskId));
      (_window$Talent2 = window.Talent) === null || _window$Talent2 === void 0 ? void 0 : _window$Talent2.app.vent.on("global-pull-screen:closed:".concat(data.taskId), function () {// refreshEList && refreshEList();
      }); // 任务：打开推屏

      window.Talent.app.vent.trigger('global-pull-screen', data.taskId, 'task');
    } else {
      window.open("//".concat(window.location.host).concat(window.location.pathname, "#more/taskinfo?id=").concat(data.taskId));
    }
  };

  return /*#__PURE__*/_react["default"].createElement("div", {
    key: index,
    className: (0, _classnames["default"])("".concat(_precls["default"], "__e-task-node"))
  }, /*#__PURE__*/_react["default"].createElement("span", {
    className: (0, _classnames["default"])("".concat(_precls["default"], "__e-task-node-prefix"))
  }, /*#__PURE__*/_react["default"].createElement(_eStatusDropdown["default"], {
    onChange: onEStatusChangeHandler,
    checked: _constant.EStatusStatus2ClassType[dataInfo.status],
    hasAuth: hasEditAuth && data.editStatusable
  })), isShowPriority && /*#__PURE__*/_react["default"].createElement("span", {
    className: (0, _classnames["default"])("".concat(_precls["default"], "__e-task-node-priority"))
  }, /*#__PURE__*/_react["default"].createElement(_ePriority["default"], {
    onChange: onEPriorityChangeHandler,
    checked: priority,
    hasAuth: hasEditAuth,
    status: data.status
  })), /*#__PURE__*/_react["default"].createElement("span", {
    className: (0, _classnames["default"])("".concat(_precls["default"], "__e-task-node-title"), _defineProperty({}, "".concat(_precls["default"], "__e-project-node-gray"), isCancel || isGray)),
    onClick: handleShowTaskDetail
  }, /*#__PURE__*/_react["default"].createElement(TooltipText, {
    text: (0, _helpers.escapeHtml)(title),
    isPercent: true
  })), /*#__PURE__*/_react["default"].createElement("span", {
    className: (0, _classnames["default"])("".concat(_precls["default"], "__e-task-node-actions"))
  }, hasPrinciple && /*#__PURE__*/_react["default"].createElement("span", {
    className: (0, _classnames["default"])("".concat(_precls["default"], "__e-task-node-actions-user"))
  }, /*#__PURE__*/_react["default"].createElement(_avatar["default"].Text, {
    name: user === null || user === void 0 ? void 0 : user.name,
    id: user === null || user === void 0 ? void 0 : user.userId,
    width: 92,
    editable: dataInfo.status !== 2 && hasEditAuth,
    onEditUser: onEditUserHandler,
    isGetRoot: true,
    showAvatar: true,
    avatar: user === null || user === void 0 ? void 0 : user.avatar,
    extraCls: (isCancel || isGray) && "".concat(_precls["default"], "__e-project-node-gray")
  })), /*#__PURE__*/_react["default"].createElement("span", {
    className: (0, _classnames["default"])("".concat(_precls["default"], "__e-task-node-actions-date"), _defineProperty({}, "".concat(_precls["default"], "__e-task-node-actions-date--canedit"), dataInfo.status !== 2 && hasEditAuth)),
    onClick: updateDateHandler
  }, /*#__PURE__*/_react["default"].createElement(_statusTime["default"], {
    deadLine: dataInfo.deadLine,
    isLongTerm: dataInfo.isLongTerm,
    isCancel: dataInfo.status === 4,
    isComplete: dataInfo.status === 2
  })), hasProgress && /*#__PURE__*/_react["default"].createElement("span", {
    className: (0, _classnames["default"])("".concat(_precls["default"], "__e-task-node-actions-progress ").concat((isGray || isCancel) && "".concat(_precls["default"], "__e-project-node-gray")))
  }, /*#__PURE__*/_react["default"].createElement(_progress["default"].Circle, {
    size: 22,
    width: 3,
    percent: progress,
    linear: true,
    linearId: data.taskId,
    linearStartColor: (0, _getProcessColor["default"])(dataInfo.riskLevel, 'linearStartColor', dataInfo.status),
    linearEndColor: (0, _getProcessColor["default"])(dataInfo.riskLevel, 'linearEndColor', dataInfo.status),
    backgroundColor: (0, _getProcessColor["default"])(dataInfo.riskLevel, 'backgroundColor', dataInfo.status)
  })), okrInfo.status === 1 && hasRelation && (hasRelativeAuth || isParticipant) ? /*#__PURE__*/_react["default"].createElement(_tooltip["default"], {
    overlay: (0, _getLocale.getLocale)('OKR_MyO_Text_Cancel'),
    placement: "top"
  }, /*#__PURE__*/_react["default"].createElement("span", {
    className: (0, _classnames["default"])("".concat(_precls["default"], "__e-task-node-actions-connect")),
    onClick: function onClick() {
      return setUnConnectVisible(true);
    }
  }, /*#__PURE__*/_react["default"].createElement("span", {
    className: "tu-icon-quxiaoguanlian e-node-status-icon"
  }))) : null), /*#__PURE__*/_react["default"].createElement(_dialogConfirm["default"], {
    visible: unConnectVisible,
    type: "warning"
  }, /*#__PURE__*/_react["default"].createElement("span", {
    type: "title"
  }, (0, _getLocale.getLocale)('OKR_MyO_Text_Cancelass')), /*#__PURE__*/_react["default"].createElement("span", {
    type: "content"
  }, (0, _getLocale.getLocale)('OKR_MyO_Text_TtasknotO')), /*#__PURE__*/_react["default"].createElement(_dialogConfirm.CancelButton, {
    type: "button",
    onClick: function onClick() {
      return setUnConnectVisible(false);
    }
  }, (0, _getLocale.getLocale)('Mod_Cancel')), /*#__PURE__*/_react["default"].createElement(_dialogConfirm.SureButton, {
    type: "button",
    onClick: onSureUnConnectHandler
  }, (0, _getLocale.getLocale)('OKR_MyO_Butt_Determine'))));
}

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