"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.changeQueryString = changeQueryString;
exports.getQueryString = getQueryString;
exports.highLightWord = exports.hexToRgba = exports.getUrlForUserPage = void 0;
exports.htmlDecodeByHtmlRegExp = htmlDecodeByHtmlRegExp;
exports.htmlDecodeByRegExp = htmlDecodeByRegExp;
exports.htmlEncodeByRegExp = htmlEncodeByRegExp;
exports.htmlEncodeToHtmlByRegExp = htmlEncodeToHtmlByRegExp;
exports.openPage = exports.htmlToText = void 0;
exports.openUrl = openUrl;
exports.unHighLight = exports.toUpperCase = void 0;

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

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

var _cloneDeep = _interopRequireDefault(require("clone-deep"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

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 openUrl(url) {
  if (typeof url !== 'string') return;
  var newTab = window.open(url);
  if (!newTab) return;
  newTab.opener = null;
  newTab.location = url;
}

function htmlEncodeByRegExp(str) {
  if (!str) return "";
  var htmlString = {
    "<": "&lt;",
    ">": "&gt;",
    // "&": '&amp;',
    "'": "&#39;",
    "\"": "&quot;"
  };
  return str.replace(/[<>'"]/g, function (s) {
    return htmlString[s];
  });
}

function htmlDecodeByRegExp(str) {
  if (!str) return "";
  var arrEntities = {
    lt: "<",
    gt: ">",
    nbsp: " ",
    amp: "&",
    quot: "\"",
    "#39": "'"
  };
  return str.replace(/&(lt|gt|nbsp|amp|quot|#39);/gi, function (all, t) {
    return arrEntities[t];
  });
}

function changeQueryString(key, value) {
  var hash = decodeURIComponent(window.location.hash);
  var queryObject = {};
  var markIndex = hash.indexOf("?"); // contain query string in fragments

  if (markIndex > -1) {
    // build query object
    var hashName = hash.slice(0, markIndex);
    var queryString = hash.slice(markIndex + 1);
    var queryArray = queryString.split("&");
    queryArray.forEach(function (item) {
      var _item$split = item.split("="),
          _item$split2 = _slicedToArray(_item$split, 2),
          tempItem0 = _item$split2[0],
          tempItem1 = _item$split2[1];

      queryObject[tempItem0] = tempItem1;
    });
    queryObject[key] = value;
    var arr = [];
    Object.keys(queryObject).forEach(function (name) {
      arr.push("".concat(name, "=").concat(queryObject[name]));
    });
    window.location.hash = "".concat(hashName, "?").concat(arr.join("&"));
  } else {
    window.location.hash = hash;
  }
}

function getQueryString() {
  // 获取Url上的参数，以{}返回
  var hash = decodeURIComponent(window.location.hash);
  var queryObject = {};
  var markIndex = hash.indexOf("?"); // contain query string in fragments

  if (markIndex > -1) {
    // build query object
    var queryString = hash.slice(markIndex + 1);
    var queryArray = queryString.split("&");

    for (var i = 0; i < queryArray.length; i += 1) {
      var queryPair = queryArray[i].split("=");

      if (queryPair[0] !== "_k") {
        queryObject[queryPair[0]] = decodeURIComponent(queryPair[1]);
      }
    }
  }

  return queryObject;
}

var highLightWord = function highLightWord(_ref) {
  var parentDom = _ref.parentDom,
      _ref$keyWord = _ref.keyWord,
      keyWord = _ref$keyWord === void 0 ? "" : _ref$keyWord,
      _ref$className = _ref.className,
      className = _ref$className === void 0 ? "highlight" : _ref$className,
      _ref$nodeType = _ref.nodeType,
      nodeType = _ref$nodeType === void 0 ? "span" : _ref$nodeType;

  if (parentDom && keyWord) {
    var reg = new RegExp(keyWord, "i");

    if (parentDom.nodeType === 3) {
      var match = parentDom.data.match(reg);
      var currentDom = parentDom;

      while (match) {
        var highlight = document.createElement(nodeType);
        highlight.className = className;
        var wordNode = currentDom.splitText(match.index);
        currentDom = wordNode.splitText(match[0].length);
        var wordClone = wordNode.cloneNode(true);
        highlight.appendChild(wordClone);
        wordNode.parentNode.replaceChild(highlight, wordNode);
        match = currentDom.data.match(reg);
      }
    } else {
      var doms = Array.from(parentDom.childNodes);

      if (doms && doms.length > 0) {
        doms.forEach(function (dom) {
          // @ts-ignore      1是元素  3是文本节点
          if (dom.nodeType === 3) {
            var _match = dom.data.match(reg);

            var _currentDom = dom;

            while (_match) {
              var _highlight = document.createElement(nodeType);

              _highlight.className = className;

              var _wordNode = _currentDom.splitText(_match.index);

              _currentDom = _wordNode.splitText(_match[0].length);

              var _wordClone = _wordNode.cloneNode(true);

              _highlight.appendChild(_wordClone);

              _wordNode.parentNode.replaceChild(_highlight, _wordNode);

              _match = _currentDom.data.match(reg);
            }
          } else if (dom.nodeType === 1 && dom.childNodes) {
            for (var i = 0; i < dom.childNodes.length; i += 1) {
              i += highLightWord({
                parentDom: dom.childNodes[i],
                keyWord: keyWord
              });
            }
          }
        });
      }
    }
  }
};

exports.highLightWord = highLightWord;

var unHighLight = function unHighLight(_ref2) {
  var parentDom = _ref2.parentDom,
      _ref2$className = _ref2.className,
      className = _ref2$className === void 0 ? "highlight" : _ref2$className,
      _ref2$nodeType = _ref2.nodeType,
      nodeType = _ref2$nodeType === void 0 ? "span" : _ref2$nodeType;
  var doms = parentDom.querySelectorAll("".concat(nodeType, " .").concat(className));

  if (doms) {
    doms.forEach(function (dom) {
      var parentNode = dom.parentNode;
      var firstChild = dom.firstChild;
      parentNode.replaceChild(firstChild, dom);
      parentNode.normalize();
    });
  }
};

exports.unHighLight = unHighLight;

var hexToRgba = function hexToRgba(hex) {
  var opacity = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
  return "rgba(".concat(parseInt("0x".concat(hex.slice(1, 3)), 16), ",").concat(parseInt("0x".concat(hex.slice(3, 5)), 16), ",").concat(parseInt("0x".concat(hex.slice(5, 7)), 16), ",").concat(opacity, ")");
};

exports.hexToRgba = hexToRgba;

var getUrlForUserPage = function getUrlForUserPage(options) {
  var defults = {
    userId: "",
    // 是否是外部联系人，外部联系人没有 2是外部联系人
    userType: 2
  };

  var configs = _objectSpread(_objectSpread({}, defults), options);

  if (!configs.userId || (0, _platform.isDD)(true) || (0, _platform.isFeishu)(true) || configs.userType === 2) {
    return "";
  }

  var userInfo = window.BSGlobal.loginUserInfo;

  if (configs.userId === undefined) {
    configs.userId = userInfo.Id;
  }

  var urlHost = window.BSGlobal.titaHost;
  var homeUrl = "".concat(urlHost, "/").concat(userInfo.Id, "/PageBuilderForEdit#/view?to_user_id=").concat(configs.userId);
  var homeCenter = "".concat(urlHost, "/u/").concat(userInfo.Id, "/Home#").concat(encodeURIComponent("widget/italent?iTalentFrameType=iframe&iTalentFrame=".concat(encodeURIComponent(homeUrl))));
  return homeCenter;
};

exports.getUrlForUserPage = getUrlForUserPage;

var openPage = function openPage(url) {
  if ((0, _openData.isPlatform)("dd")) {
    window.open(url, "_self");
  } else {
    window.open(url, "_blank");
  }
}; // html标签转义


exports.openPage = openPage;

function htmlEncodeToHtmlByRegExp(str) {
  var temp = "";
  if (str.length === 0) return ""; // temp = str.replace(/&/g, "&amp;")

  temp = str.replace(/</g, "&lt;");
  temp = temp.replace(/>/g, "&gt;"); // temp = temp.replace(/ /g, "&nbsp;")

  temp = temp.replace(/'/g, "&#39;");
  temp = temp.replace(/"/g, "&quot;");
  temp = temp.replace(/\n/g, "<br/>");
  return temp;
}

function htmlDecodeByHtmlRegExp(str) {
  var temp = "";
  if (str.length === 0) return "";
  temp = str.replace(/&amp;/g, "&");
  temp = temp.replace(/&lt;/g, "<");
  temp = temp.replace(/&gt;/g, ">");
  temp = temp.replace(/&nbsp;/g, " ");
  temp = temp.replace(/&#39;/g, "'");
  temp = temp.replace(/&quot;/g, "\"");
  temp = temp.replace(/<br\/>/g, "\n");
  return temp;
}

var htmlToText = function htmlToText(text) {
  var div = document.createElement("div");
  div.innerHTML = text;
  var newtext = div.innerText || div.textContent;
  return newtext;
};

exports.htmlToText = htmlToText;

var toUpperCase = function toUpperCase(obj) {
  var newObj = (0, _cloneDeep["default"])(obj);

  if (Object.prototype.toString.call(newObj) === '[object Object]') {
    for (var key in newObj) {
      var pre = key.substring(0, 1);
      var upPre = pre.toUpperCase();
      var word = key.substring(1);

      if (Object.prototype.toString.call(newObj[key]) === '[object Object]') {
        newObj[upPre + word] = toUpperCase(newObj[key]);
      } else {
        newObj[upPre + word] = newObj[key];
      }

      if (pre !== upPre) {
        delete newObj[key];
      }
    }
  }

  return newObj;
};

exports.toUpperCase = toUpperCase;