"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 _toast = _interopRequireDefault(require("../../../../../toast"));

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

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

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

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

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

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

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

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

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

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

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

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

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

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

var _tooltipText = _interopRequireDefault(require("../../../../../tooltip/tooltip-text"));

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

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

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

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

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

function _default(props) {
  var _okrInfo$authority, _okrInfo$aiteUsers;

  var index = props.index,
      title = props.title,
      data = props.data,
      level = props.level,
      isLeaf = props.isLeaf,
      createUserId = props.createUserId,
      krUser = props.krUser,
      _props$krAiteUsers = props.krAiteUsers,
      krAiteUsers = _props$krAiteUsers === void 0 ? [] : _props$krAiteUsers;

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

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

  var _useState5 = (0, _react.useState)({
    deadLine: data.deadLine,
    isLongTerm: data.isLongTerm,
    status: data.status,
    riskLevel: data.riskLevel
  }),
      _useState6 = _slicedToArray(_useState5, 2),
      dateInfo = _useState6[0],
      setDateInfo = _useState6[1];

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

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

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

  var _useContext = (0, _react.useContext)(_context2.CommonContext),
      okrInfo = _useContext.okrInfo;

  var _useContext2 = (0, _react.useContext)(_context2.EListContext),
      refreshEList = _useContext2.refreshEList;

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

  var hasAuth = (new _auth.EAuth({
    principalUser: data.principalUser,
    user: data.user
  }).hasAuth() || new _auth.KRAuth({
    user: krUser,
    createUserId: createUserId
  }).hasAuth() || new _auth.OAuth({
    principalUser: okrInfo.principalUser,
    createUserId: okrInfo.createUserId
  }).hasAuth()) && data.status !== 5;
  var isParticipant = ((_okrInfo$authority = okrInfo.authority) === null || _okrInfo$authority === void 0 ? void 0 : _okrInfo$authority.roleRelation) && okrInfo.authority.roleRelation.roleType === 2 || !!((_okrInfo$aiteUsers = okrInfo.aiteUsers) !== null && _okrInfo$aiteUsers !== void 0 && _okrInfo$aiteUsers.find(function (item) {
    return (0, _bsGlobal.getUserInfo)().Id == item;
  })) || !!(krAiteUsers !== null && krAiteUsers !== void 0 && krAiteUsers.find(function (item) {
    return (0, _bsGlobal.getUserInfo)().Id == item;
  }));
  var hasRelativeAuth = new _auth.KRAuth({
    user: data.user,
    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)({
      task_id: data.taskId,
      to_user_id: 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(resp.Message, {
          canClose: false
        });
      }
    })["catch"](function () {
      _toast["default"].Error("网络异常", {
        canClose: false
      });
    });
  };

  var onEStatusChangeHandler = function onEStatusChangeHandler(statusType) {
    (0, _requestApis.updateTaskStatus)({
      task_id: data.taskId,
      status: _constant.EStatusClass2StatusType[statusType]
    }).then(function (resp) {
      if (resp.Code === 1) {
        setDateInfo(_objectSpread(_objectSpread({}, dateInfo), {}, {
          status: _constant.EStatusClass2StatusType[statusType]
        }));
        setIsGray(_constant.EStatusClass2StatusType[statusType] === 2);
        setIsCancel(_constant.EStatusClass2StatusType[statusType] === 4);

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

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

        refreshEList();
      } else {
        _toast["default"].Error(resp.Message, {
          canClose: false
        });
      }
    })["catch"](function () {
      _toast["default"].Error("网络异常", {
        canClose: false
      });
    })["finally"](setUnConnectVisible(false));
  };

  var onEditDateHandler = (0, _react.useCallback)( /*#__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 (hasAuth) {
                _context.next = 2;
                break;
              }

              return _context.abrupt("return");

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

            case 4:
              res = _context.sent;
              _context.next = 7;
              return (0, _requestApis.updateTaskDate)({
                task_id: data.taskId,
                startDate: res.startDate,
                endDate: res.endDate,
                isLongTerm: res.isLongTerm
              }).then(function (resp) {
                if (resp.Code === 1) {
                  setDateInfo({
                    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 (_x) {
      return _ref3.apply(this, arguments);
    };
  }(), []);

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

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

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

    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-level2-node"))
  }, /*#__PURE__*/_react["default"].createElement("span", {
    className: (0, _classnames["default"])("".concat(_precls["default"], "__e-task-level2-node-prefix"))
  }, /*#__PURE__*/_react["default"].createElement(_eStatusDropdown["default"], {
    onChange: onEStatusChangeHandler,
    checked: _constant.EStatusStatus2ClassType[dateInfo.status],
    hasAuth: hasAuth
  })), 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: hasAuth,
    status: data.status
  })), /*#__PURE__*/_react["default"].createElement("span", {
    className: (0, _classnames["default"])("".concat(_precls["default"], "__e-task-level2-node-title ").concat(isCancel ? "".concat(_precls["default"], "__e-project-node-gray") : "")),
    onClick: handleShowTaskDetail
  }, /*#__PURE__*/_react["default"].createElement(_tooltipText["default"], {
    text: (0, _helpers.escapeHtml)(title),
    isPercent: true
  })), /*#__PURE__*/_react["default"].createElement("span", {
    className: (0, _classnames["default"])("".concat(_precls["default"], "__e-task-level2-node-actions"))
  }, /*#__PURE__*/_react["default"].createElement("span", {
    className: (0, _classnames["default"])("".concat(_precls["default"], "__e-task-level2-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: 64,
    editable: hasAuth,
    onEditUser: onEditUserHandler,
    isGetRoot: true,
    extraCls: (isCancel || isGray) && "".concat(_precls["default"], "__e-project-node-gray")
  })), /*#__PURE__*/_react["default"].createElement("span", {
    className: (0, _classnames["default"])("".concat(_precls["default"], "__e-task-level2-node-actions-date")),
    onClick: onEditDateHandler
  }, /*#__PURE__*/_react["default"].createElement(_statusTime["default"], {
    deadLine: dateInfo.deadLine,
    isLongTerm: dateInfo.isLongTerm,
    isCancel: dateInfo.status === 4,
    isComplete: dateInfo.status === 2
  })), /*#__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: data.progress,
    linear: true,
    linearId: data.taskId,
    linearStartColor: (0, _getProcessColor["default"])(dateInfo.riskLevel, "linearStartColor", dateInfo.status),
    linearEndColor: (0, _getProcessColor["default"])(dateInfo.riskLevel, "linearEndColor", dateInfo.status),
    backgroundColor: (0, _getProcessColor["default"])(dateInfo.riskLevel, "backgroundColor", dateInfo.status)
  })), okrInfo.status === 1 && (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"))));
}