import { computed, ref } from "vue";
import { useSessionStorage } from "@vueuse/core";
import { defineStore } from "pinia";
import { getNameByexternalUserId } from "@/api/wecom.js";
import { memberStore } from "./member";
/**
 * @description 员工外部联系人
 */
export default defineStore("wxContactStore", () => {
  const taskList = ref([]);
  const pending = ref({});
  const contact = useSessionStorage("wx-contact-store", {});
  const contactName = computed(() =>
    Object.keys(contact.value).reduce((acc, key) => {
      if (contact.value[key] && contact.value[key].name) {
        acc[key] = contact.value[key].name;
      }
      return acc;
    }, {})
  );

  const contactFollowUsers = computed(() =>
    Object.keys(contact.value).reduce((acc, key) => {
      if (contact.value[key] && Array.isArray(contact.value[key].followUsers)) {
        acc[key] = contact.value[key].followUsers;
      }
      return acc;
    }, {})
  );

  async function getWxContact(externalUserId) {
    if (!externalUserId || pending.value[externalUserId]) return;
    pending.value[externalUserId] = true;
    const { corpInfo } = memberStore();
    const params = {
      corpId: corpInfo.corpId,
      permanentCode: corpInfo.permanent_code,
      externalUserId: externalUserId,
    };
    const { success, data } = await getNameByexternalUserId(params);
    if (success) {
      const name = data && data.data && data.data.external_contact ? data.data.external_contact.name : "";
      const followUsers = data && data.data && Array.isArray(data.data.follow_user) ? data.data.follow_user.map((i) => i.userid).filter(Boolean) : [];
      contact.value[externalUserId] = { name, followUsers };
    }
    pending.value[externalUserId] = false;
    delete pending.value[externalUserId];
    runTask();

  }

  function getContacts(list, reGet = false) {
    list.forEach((id) => {
      if (id && (!contact.value[id] || reGet)) {
        contact.value[id] = {};
        getWxContact(id);
      }
    });
  }

  function addTask(externalUserId) {
    if (taskList.value.includes(externalUserId) || pending.value[externalUserId]) return;
    taskList.value.push(externalUserId);
    runTask()
  }

  function runTask() {
    const keys = Object.keys(pending.value);
    if (keys.length >= 10) return;
    const externalUserId = taskList.value.shift();
    if (externalUserId) {
      getWxContact(externalUserId);
    }
  }


  return { contactName, contactFollowUsers, getContacts, addTask, pending };
});
