"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 _dayjs = _interopRequireDefault(require("dayjs"));

var _button = _interopRequireDefault(require("../button"));

var _titaUi = require("tita-ui");

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

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

var _contact = _interopRequireDefault(require("./contact"));

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

var _tools = require("../../utils/tools");

require("./index.css");

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

var _window$BSGlobal, _window$BSGlobal$tena, _window$BSGlobal2, _window$BSGlobal2$ten;

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 _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 preCls = 'tita-survey-model';
var Rect = _button["default"].Rect;
var loginUserInfo = window.BSGlobal.loginUserInfo;
var Role = new _auth.MyRole();
var Version = ((_window$BSGlobal = window.BSGlobal) === null || _window$BSGlobal === void 0 ? void 0 : (_window$BSGlobal$tena = _window$BSGlobal.tenantAuthentication) === null || _window$BSGlobal$tena === void 0 ? void 0 : _window$BSGlobal$tena.version) || ((_window$BSGlobal2 = window.BSGlobal) === null || _window$BSGlobal2 === void 0 ? void 0 : (_window$BSGlobal2$ten = _window$BSGlobal2.tenantAuthentication) === null || _window$BSGlobal2$ten === void 0 ? void 0 : _window$BSGlobal2$ten.Version) || 1;

var SurveyModel = function SurveyModel(_ref) {
  var activityName = _ref.activityName,
      title = _ref.title,
      startTime = _ref.startTime,
      endTime = _ref.endTime,
      scores = _ref.scores,
      scoringKeywords = _ref.scoringKeywords,
      reasonTags = _ref.reasonTags,
      advisePlaceholder = _ref.advisePlaceholder;

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

  var _useState3 = (0, _react.useState)(''),
      _useState4 = _slicedToArray(_useState3, 2),
      score = _useState4[0],
      setScore = _useState4[1];

  var _useState5 = (0, _react.useState)(''),
      _useState6 = _slicedToArray(_useState5, 2),
      scoreType = _useState6[0],
      setScoreType = _useState6[1];

  var _useState7 = (0, _react.useState)(''),
      _useState8 = _slicedToArray(_useState7, 2),
      reason = _useState8[0],
      setReason = _useState8[1];

  var _useState9 = (0, _react.useState)(''),
      _useState10 = _slicedToArray(_useState9, 2),
      advice = _useState10[0],
      setAdvice = _useState10[1];

  var _useState11 = (0, _react.useState)(false),
      _useState12 = _slicedToArray(_useState11, 2),
      contact = _useState12[0],
      setContact = _useState12[1];

  var handleCloseSurvey = function handleCloseSurvey() {
    setDialogVisible(false);
    localStorage.setItem("survey_model_date__".concat(loginUserInfo === null || loginUserInfo === void 0 ? void 0 : loginUserInfo.Id), (0, _dayjs["default"])().toString());
  };

  (0, _react.useEffect)(function () {
    if (Version === 1) return;
    if ((0, _helpers.isDingDing)()) return;
    if (!!window.location.hostname.match(/.work/)) return;
    var newDate = (0, _dayjs["default"])();
    var oldDate = localStorage.getItem("survey_model_date__".concat(loginUserInfo === null || loginUserInfo === void 0 ? void 0 : loginUserInfo.Id));

    if (endTime) {
      if ((0, _dayjs["default"])(endTime).valueOf() < (0, _dayjs["default"])().valueOf()) {
        return;
      }
    }

    if (oldDate) {
      var oldDay = (0, _dayjs["default"])(oldDate);

      if (newDate.diff(oldDay, 'day') < 7) {
        return;
      }
    }

    (0, _requestApi.getData)(activityName).then(function (res) {
      if (res.code === 200) {
        var _res$data, _res$data$list;

        if (!(res !== null && res !== void 0 && (_res$data = res.data) !== null && _res$data !== void 0 && (_res$data$list = _res$data.list) !== null && _res$data$list !== void 0 && _res$data$list.length)) {
          setTimeout(function () {
            setDialogVisible(true);
          }, 15000);
        } else {
          setDialogVisible(false);
        }
      } else {
        setDialogVisible(false);
      }
    });
  }, []);

  var handleScore = function handleScore(score) {
    setScore(score);

    if (score < 7) {
      setScoreType('bad');
    } else if (score < 9) {
      setScoreType('normal');
    } else {
      setScoreType('good');
    }
  };

  var handleReason = function handleReason(reason) {
    setReason(reason);
  };

  var onAdviceChange = function onAdviceChange(value) {
    setAdvice(value);
  };

  var handleSubmit = function handleSubmit(contact) {
    var tenantInfo = window.BSGlobal.tenantInfo;
    var npsStartTime = (0, _dayjs["default"])(startTime).unix();
    var npsEndTime = (0, _dayjs["default"])(endTime).unix();
    var result = {
      fields: {
        nps_activity_name: activityName,
        nps_activity_title: title,
        nps_start_time: npsStartTime,
        nps_end_time: npsEndTime,
        nps_score: score,
        nps_advice: (0, _tools.htmlEncodeByRegExp)(advice),
        nps_score_reason: reason,
        user_id: loginUserInfo === null || loginUserInfo === void 0 ? void 0 : loginUserInfo.Id,
        user_name: loginUserInfo === null || loginUserInfo === void 0 ? void 0 : loginUserInfo.Name,
        user_contact: (0, _tools.htmlEncodeByRegExp)(contact),
        user_role_name: Role.getRole(),
        tenant_id: tenantInfo === null || tenantInfo === void 0 ? void 0 : tenantInfo.Id,
        tenant_name: tenantInfo === null || tenantInfo === void 0 ? void 0 : tenantInfo.Name,
        tenant_source_name: tenantInfo === null || tenantInfo === void 0 ? void 0 : tenantInfo.Source.toString(),
        tenant_version_name: _bsGlobal.VERSION_MAP[Version]
      }
    };
    (0, _requestApi.sendData)(result, 'nps_survey').then(function (res) {
      console.log('提交成功');
    });
  };

  var handleToNext = function handleToNext() {
    setDialogVisible(false);
    setContact(true);
  };

  if (contact) return /*#__PURE__*/_react["default"].createElement(_contact["default"], {
    sendData: handleSubmit,
    visilble: contact,
    setVisible: setContact
  });
  if (!dialogVisible) return /*#__PURE__*/_react["default"].createElement("div", null);
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])('tita-survey-model')
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__head")
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__head-title")
  }, title), /*#__PURE__*/_react["default"].createElement("span", {
    className: "tu-icon-canceled ".concat(preCls, "__head-close "),
    onClick: handleCloseSurvey
  })), (scores === null || scores === void 0 ? void 0 : scores.length) && /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__score")
  }, scores.map(function (item) {
    return /*#__PURE__*/_react["default"].createElement("div", {
      className: (0, _classnames["default"])("".concat(preCls, "__score-item"), _defineProperty({}, "".concat(preCls, "__score-item--active"), item === score)),
      key: item,
      onClick: function onClick() {
        return handleScore(item);
      }
    }, item);
  })), (scoringKeywords === null || scoringKeywords === void 0 ? void 0 : scoringKeywords.length) && /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__keywords")
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__keywords-left")
  }, scoringKeywords[0]), /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__keywords-right")
  }, scoringKeywords[1]))), scoreType && /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__content")
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__tags")
  }, reasonTags[scoreType].map(function (item, key) {
    return /*#__PURE__*/_react["default"].createElement("div", {
      className: (0, _classnames["default"])("".concat(preCls, "__tags-item"), _defineProperty({}, "".concat(preCls, "__tags-item--active"), item === reason)),
      key: key,
      onClick: function onClick() {
        return handleReason(item);
      }
    }, item);
  })), /*#__PURE__*/_react["default"].createElement(_titaUi.Textarea, {
    placeholder: advisePlaceholder,
    value: advice,
    onChange: function onChange(e) {
      return onAdviceChange(e.target.value);
    },
    maxLine: 4,
    maxLength: 500,
    wrapperClass: "".concat(preCls, "__text")
  }), /*#__PURE__*/_react["default"].createElement(Rect, {
    type: "primary",
    className: "".concat(preCls, "__btn"),
    onClick: handleToNext
  }, "\u63D0\u4EA4")));
};

SurveyModel.defaultProps = {
  scoringKeywords: ['不愿意', '非常愿意'],
  scores: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  reasonTags: {
    bad: ['视角效果不美观', '没有 Excel 便捷', '感受不到管理效率提升', '速度太慢', '操作复杂', '系统不稳定', '功能不满足'],
    normal: ['管理效率有提升', '能解决大部分管理问题', '操作再简单一些', '系统不是很稳定'],
    good: ['OKR 与绩效天然打通', '能追踪目标落地过程', '团队管理高效', '视角效果很好']
  },
  advisePlaceholder: '你觉得哪些地方可以做到更好？'
};
var _default = SurveyModel;
exports["default"] = _default;