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

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

  /**
   * 设置采集模块状态数据
   */
  function setCollectableModules(modules: Map<string, number>) {
    collectableModules.value = modules;
  }
  /**
   * 判断是否可以采集指定目录
   */
  function canCollectCatalog(catalogId: number) {
    if (authStore.isAdmin)
      return true;
    return collectableCatalogs.value.includes(catalogId);
  }
  /**
   * 判断是否可以采集指定模块
   */
  function canCollect(module: string) {
    if (authStore.isAdmin)
      return true;
    if (collectableModules.value.has(CollectableModulesNameMapping[module]))
      return true;
    return collectableModules.value.has(module);
  }
  /**
   * 获取采集模块的内部名称
   */
  function getCollectModuleId(module: string) {
    if (collectableAllModules.value.has(CollectableModulesNameMapping[module]))
      return collectableAllModules.value.get(CollectableModulesNameMapping[module]);
    return collectableAllModules.value.get(module);
  }
  /**
   * 从ID获取采集模块的内部名称
   */
  function getCollectModuleInternalNameById(id: number) {
    for (const [key, value] of collectableAllModules.value) {
      if (value == id) {
        for (const k2 in CollectableModulesNameMapping) {
          if (CollectableModulesNameMapping[k2] == key) {
            return k2;
          }
        }
      }
    }
    return '';
  }

  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(k, v);
    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(collectableModulesMap);
  }
  
  /**
   * 判断采集模块状态是否为空
   */
  const isEmpty = computed(() => collectableModules.value.size === 0 && collectableCatalogs.value.length === 0);

  return { 
    isEmpty,
    collectableModules,
    setCollectableModules,
    getCollectModuleInternalNameById,
    getCollectModuleId,
    canCollect,
    canCollectCatalog,
    loadCollectableModules,
  }
})
