import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import { useAuthStore } from './auth';
import VillageApi from '@/api/inhert/VillageApi';

/** 
 * 采集模块状态 
 */
export const useCollectStore = defineStore('collect', () => {
  const collectableModules = ref(new Set<number>());
  const collectableAllModules = ref(new Map<number, string>());
  const collectableCatalogs = ref<number[]>([]);
  const authStore = useAuthStore();

  /**
   * 设置采集模块状态数据
   */
  function setCollectableModules(modules: Set<number>) {
    collectableModules.value = modules;
  }
  /**
   * 判断是否可以采集指定目录
   */
  function canCollectCatalog(catalogId: number) {
    if (authStore.isAdmin)
      return true;
    return collectableCatalogs.value.includes(catalogId);
  }
  /**
   * 判断是否可以采集指定模块
   */
  function canCollect(collectModuleId: number) {
    if (authStore.isAdmin)
      return true;
    if (collectableModules.value.has(collectModuleId))
      return true;
    return collectableModules.value.has(collectModuleId);
  }

  async function loadCollectableModules() {
    const res = await VillageApi.getVolunteerInfo();
    const collectableModules = res.collectModule || [];
    const collectableModulesMap = await VillageApi.getCollectModuleMap();
    for (const [k,v] of collectableModulesMap)
      collectableAllModules.value.set(v, k);
    const needRemoveKeys = new Set<string>();
    if (!authStore.isAdmin) {
      for (const [key,id] of collectableModulesMap)
        if (!collectableModules.includes(id))
          needRemoveKeys.add(key);
    }
    for (const key of needRemoveKeys)
      collectableModulesMap.delete(key);
    collectableCatalogs.value = res.catalogIds || [];
    console.log('CollectableModulesMap', collectableModules, collectableModulesMap);
    setCollectableModules(new Set(collectableModules));
  }
  
  /**
   * 判断采集模块状态是否为空
   */
  const isEmpty = computed(() => collectableModules.value.size === 0 && collectableCatalogs.value.length === 0);

  return { 
    isEmpty,
    collectableModules,
    collectableCatalogs,
    setCollectableModules,
    canCollect,
    canCollectCatalog,
    loadCollectableModules,
  }
})
