import { storeToRefs } from "pinia";
import { memberStore } from "@/store/member";
import { teamStore } from "@/store/team";
import { openEnterpriseChat } from "@/utils/jssdk";
import { urlParamsToObject } from "@/utils/index.js";
import { getAccessUser as accessUser, getNameByexternalUserId as getNameByexternalUserIdUrl } from "@/api/wecom.js";

import { selectedChatMember } from "@/api/member.js";
// 防抖函数
function debounce(func, delay) {
  let timer;
  return function (...args) {
    clearTimeout(timer); // 清除之前的定时器
    timer = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}
// 判断是否在企业微信环境
function envjudgwxWork() {
  var ua = navigator.userAgent.toLowerCase();
  return ua.match(/wxwork/i) == "wxwork";
}
// 判断是否是手机端
function isMobile() {
  var isMobile = window.navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
  return Boolean(isMobile);
}
// 授权登陆获取用户访问信息
async function getAccessUser() {
  const oldCode = sessionStorage.getItem("CODE");
  sessionStorage.removeItem("NEWCODE");
  let { code } = urlParamsToObject(window.location.href);
  sessionStorage.setItem("NEWCODE", code);
  if (sessionStorage.getItem("corpId")) return sessionStorage.getItem("corpId");
  if (!code || code == oldCode) return {};
  let res = await accessUser(code);
  const { userid, corpid, errcode } = res.data;
  if (errcode === 0) {
    userid && sessionStorage.setItem("userId", userid);
    corpid && sessionStorage.setItem("corpId", corpid);
    code && sessionStorage.setItem("CODE", code);
    return corpid;
  } else {
    return {};
  }
}
// 通过外部联系人userId获取外部联系信息
async function getNameByexternalUserId(externalUserId) {
  const { corpInfo } = memberStore();
  const params = {
    corpId: corpInfo.corpId,
    permanentCode: corpInfo.permanent_code,
    externalUserId: externalUserId,
  };
  let { data } = await getNameByexternalUserIdUrl(params);
  return data || [];
}

function getCorpTags(tagIds) {
  const { corpInfo } = memberStore();
  const tags = Array.isArray(corpInfo.tags) ? corpInfo.tags : [];
  const list = tags
    .map(({ label, options }) => {
      const opts = Array.isArray(options) ? options.filter((opt) => tagIds.some((i) => i == opt.id)) : [];
      return { label, options: [...opts] };
    })
    .filter((i) => i.options.length);
  const flatList = list.reduce((list, item) => [...list, ...item.options], []);
  return { list, flatList };
}

function openChatWindow(memberId, externalUserId, userId = "", payload = {}) {
  if (!memberId && !externalUserId && !userId) return;
  memberId && updateChatMember(memberId, externalUserId, payload);
  return new Promise((resolve, reject) => {
    openEnterpriseChat(externalUserId, userId, (res) => {
      if (res === "success") resolve();
      else reject();
    });
  });
}

async function updateChatMember(memberId, externalUserId, payload) {
  const { currentTeamId } = storeToRefs(teamStore());
  await selectedChatMember({
    memberId,
    externalUserId,
    userId: sessionStorage.getItem("userId"),
    corpId: sessionStorage.getItem("corpId"),
    teamId: currentTeamId.value || "",
    payload,
  });
}

function isURL(str) {
  const urlPattern = /^(https?):\/\/.+$/;
  return urlPattern.test(str);
}

export { debounce, envjudgwxWork, isMobile, getAccessUser, getNameByexternalUserId, getCorpTags, openChatWindow, isURL };
