"use strict";
const common_vendor = require("../../../common/vendor.js");
const TUIKit_components_TUISearch_searchTypeList = require("./search-type-list.js");
const TUIKit_components_common_Toast_index = require("../common/Toast/index.js");
const TUIKit_components_TUISearch_type = require("./type.js");
const TUIKit_utils_env = require("../../utils/env.js");
const TUIKit_components_common_Toast_type = require("../common/Toast/type.js");
const searchCloudMessages = (params) => {
  return common_vendor.Qt.searchCloudMessages(params).then((imResponse) => {
    return imResponse;
  }).catch((error) => {
    TUIKit_components_common_Toast_index.Toast({
      message: common_vendor.Wt.t("TUISearch.消息云端搜索失败：") + (error == null ? void 0 : error.message),
      type: TUIKit_components_common_Toast_type.TOAST_TYPE.ERROR,
      duration: 3e3
    });
    return null;
  });
};
const enterConversation = (item) => {
  const conversationID = (item == null ? void 0 : item.conversationID) || ((item == null ? void 0 : item.groupID) ? `GROUP${item == null ? void 0 : item.groupID}` : `C2C${item == null ? void 0 : item.userID}`);
  common_vendor.Xt.switchConversation(conversationID).then(() => {
    var _a;
    common_vendor.Jt.update(common_vendor.o.SEARCH, "currentSearchingStatus", {
      isSearching: false,
      searchType: "global"
    });
    common_vendor.Jt.update(common_vendor.o.SEARCH, "currentSearchInputValue", {
      value: "",
      searchType: "global"
    });
    TUIKit_utils_env.isUniFrameWork && ((_a = common_vendor.i) == null ? void 0 : _a.navigateTo({
      url: "/TUIKit/components/TUIChat/index"
    }));
  }).catch((error) => {
    common_vendor.index.__f__("warn", "at TUIKit/components/TUISearch/utils.ts:110", "switch conversation failed:", error == null ? void 0 : error.message);
    TUIKit_components_common_Toast_index.Toast({
      message: common_vendor.Wt.t("TUISearch.进入会话失败"),
      type: TUIKit_components_common_Toast_type.TOAST_TYPE.ERROR,
      duration: 1e3
    });
  });
};
const generateSearchResultShowName = (result, resultContent) => {
  var _a, _b, _c;
  if (!result) {
    return "";
  }
  if (result.ID) {
    return resultContent == null ? void 0 : resultContent.showName;
  }
  if (result.groupID) {
    return result.name || result.groupID;
  }
  if (result.userID) {
    return result.remark || result.nick || result.userID || "";
  }
  if ((_a = result.conversation) == null ? void 0 : _a.conversationID) {
    if (typeof result.conversation.getShowName === "function") {
      return result.conversation.getShowName();
    } else {
      return ((_c = (_b = common_vendor.Jt.getConversationModel(result.conversation.conversationID)) == null ? void 0 : _b.getShowName) == null ? void 0 : _c.call(_b)) || result.conversation.conversationID;
    }
  }
  return "";
};
const generateSearchResultAvatar = (result) => {
  var _a, _b, _c, _d;
  if (!result) {
    return "";
  }
  if (result.ID) {
    return result.avatar || "https://web.sdk.qcloud.com/component/TUIKit/assets/avatar_21.png";
  }
  if (result.groupID) {
    return result.avatar || `https://web.sdk.qcloud.com/im/assets/images/${result == null ? void 0 : result.type}.svg`;
  }
  if (result.userID) {
    return result.avatar || "https://web.sdk.qcloud.com/component/TUIKit/assets/avatar_21.png";
  }
  if ((_a = result == null ? void 0 : result.conversation) == null ? void 0 : _a.conversationID) {
    if (typeof result.conversation.getAvatar === "function") {
      return (_b = result.conversation) == null ? void 0 : _b.getAvatar();
    } else {
      return (_d = (_c = common_vendor.Jt.getConversationModel(result.conversation.conversationID)) == null ? void 0 : _c.getAvatar) == null ? void 0 : _d.call(_c);
    }
  }
  return "";
};
const generateSearchResultShowContent = (result, resultType, keywordList, isTypeShow = true) => {
  var _a, _b, _c, _d;
  if (result == null ? void 0 : result.groupID) {
    return [
      { text: "groupID: ", isHighlight: false },
      { text: result.groupID, isHighlight: true }
    ];
  }
  if (result == null ? void 0 : result.userID) {
    return [
      { text: "userID: ", isHighlight: false },
      { text: result.userID, isHighlight: true }
    ];
  }
  if ((result == null ? void 0 : result.conversation) || (result == null ? void 0 : result.flow)) {
    if ((result == null ? void 0 : result.messageCount) === 1 || (result == null ? void 0 : result.flow)) {
      const message = (result == null ? void 0 : result.flow) ? result : result == null ? void 0 : result.messageList[0];
      const text = ((_a = message == null ? void 0 : message.payload) == null ? void 0 : _a.text) || ((_b = message == null ? void 0 : message.payload) == null ? void 0 : _b.fileName) || ((_c = message == null ? void 0 : message.payload) == null ? void 0 : _c.description);
      const abstract = [];
      if ((message == null ? void 0 : message.type) && isTypeShow && message.type !== common_vendor.qt.TYPES.MSG_TEXT) {
        abstract.push({
          text: common_vendor.Wt.t(`TUISearch.${TUIKit_components_TUISearch_type.messageTypeAbstractMap[message.type]}`),
          isHighlight: false
        });
      }
      abstract.push(...generateMessageContentHighlight(text, keywordList));
      return abstract;
    } else {
      return [
        {
          text: `${result == null ? void 0 : result.messageCount}${common_vendor.Wt.t(
            "TUISearch.条相关"
          )}${common_vendor.Wt.t(
            `TUISearch.${resultType === "allMessage" ? "结果" : (_d = TUIKit_components_TUISearch_searchTypeList.searchMessageTypeList[resultType]) == null ? void 0 : _d.label}`
          )}`,
          isHighlight: false
        }
      ];
    }
  }
  return [];
};
const generateMessageContentHighlight = (content, keywordList) => {
  var _a;
  if (!content || !keywordList || !keywordList.length) {
    return [{ text: content || "", isHighlight: false }];
  }
  const matches = [];
  for (let i = 0; i < keywordList.length; i++) {
    const substring = (_a = keywordList[i]) == null ? void 0 : _a.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    const regex = new RegExp(substring, "gi");
    let match;
    while ((match = regex.exec(content)) !== null) {
      const start2 = match.index;
      const end = match.index + match[0].length - 1;
      matches.push([start2, end]);
    }
  }
  const mergedRanges = [matches[0]];
  if (matches.length > 1) {
    matches.sort((a, b) => a[0] - b[0]);
    for (let i = 1; i < matches.length; i++) {
      const currentRange = matches[i];
      const lastMergedRange = mergedRanges[mergedRanges.length - 1];
      if (currentRange[0] - 1 <= lastMergedRange[1]) {
        lastMergedRange[1] = Math.max(lastMergedRange[1], currentRange[1]);
      } else {
        mergedRanges.push(currentRange);
      }
    }
  }
  if (!mergedRanges[0]) {
    return [{ text: content, isHighlight: false }];
  }
  const contentArray = [];
  let start = 0;
  for (let i = 0; i < mergedRanges.length; i++) {
    const str1 = content.substring(start, mergedRanges[i][0]);
    str1 && contentArray.push({ text: str1, isHighlight: false });
    const str2 = content.substring(mergedRanges[i][0], mergedRanges[i][1] + 1);
    str2 && contentArray.push({ text: str2, isHighlight: true });
    start = mergedRanges[i][1] + 1;
  }
  const lastStr = content.substring(start);
  lastStr && contentArray.push({ text: lastStr, isHighlight: false });
  return contentArray;
};
const generateSearchResultTime = (timestamp) => {
  const todayZero = (/* @__PURE__ */ new Date()).setHours(0, 0, 0, 0);
  const thisYear = new Date((/* @__PURE__ */ new Date()).getFullYear(), 0, 1, 0, 0, 0, 0).getTime();
  const target = new Date(timestamp);
  const oneDay = 24 * 60 * 60 * 1e3;
  const oneWeek = 7 * oneDay;
  const diff = todayZero - target.getTime();
  function formatNum(num) {
    return num < 10 ? "0" + num : num.toString();
  }
  if (diff <= 0) {
    return `${formatNum(target.getHours())}:${formatNum(target.getMinutes())}`;
  } else if (diff <= oneDay) {
    return `${common_vendor.Wt.t("time.昨天")} ${formatNum(target.getHours())}:${formatNum(
      target.getMinutes()
    )}`;
  } else if (diff <= oneWeek - oneDay) {
    const weekdays = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
    const weekday = weekdays[target.getDay()];
    return `${common_vendor.Wt.t("time." + weekday)} ${formatNum(target.getHours())}:${formatNum(
      target.getMinutes()
    )}`;
  } else if (target.getTime() >= thisYear) {
    return `${target.getMonth() + 1}/${target.getDate()} ${formatNum(
      target.getHours()
    )}:${formatNum(target.getMinutes())}`;
  } else {
    return `${target.getFullYear()}/${target.getMonth() + 1}/${target.getDate()} ${formatNum(
      target.getHours()
    )}:${formatNum(target.getMinutes())}`;
  }
};
const generateSearchResultYMD = (timestamp) => {
  const date = new Date(timestamp * 1e3);
  const year = date.getFullYear();
  const month = ("0" + (date.getMonth() + 1)).slice(-2);
  const day = ("0" + date.getDate()).slice(-2);
  return `${year}-${month}-${day}`;
};
const debounce = (func, waitFor) => {
  let timeout = null;
  const debounced = (...args) => {
    if (timeout !== null) {
      clearTimeout(timeout);
      timeout = null;
    }
    timeout = setTimeout(() => func(...args), waitFor);
  };
  return debounced;
};
exports.debounce = debounce;
exports.enterConversation = enterConversation;
exports.generateSearchResultAvatar = generateSearchResultAvatar;
exports.generateSearchResultShowContent = generateSearchResultShowContent;
exports.generateSearchResultShowName = generateSearchResultShowName;
exports.generateSearchResultTime = generateSearchResultTime;
exports.generateSearchResultYMD = generateSearchResultYMD;
exports.searchCloudMessages = searchCloudMessages;
//# sourceMappingURL=../../../../.sourcemap/mp-weixin/TUIKit/components/TUISearch/utils.js.map
