import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { queryFlowTemplateApi } from '@/api/capability/flow';
import { FLOW_TEMPLATE_PUBLIC_STATUS } from '@/utils/enum/flow';

interface Template {
  templateName?: string;
  templateCode?: string;
  [k: string]: any;
}

export const useTaskStore = defineStore('task', () => {
  const templates = ref<Template[]>([]);
  const loaded = ref(false);

  const options = computed(() =>
    templates.value.map((item) => ({
      label: item.templateName || '',
      value: item.templateCode || '',
    }))
  );

  const fetchTemplates = async (force = false) => {
    if (!force && loaded.value && templates.value.length) return templates.value;
    try {
      const req = {
        current: 1,
        size: 99999,
        type: FLOW_TEMPLATE_PUBLIC_STATUS.PUBLIC,
      };
      const res: any = await queryFlowTemplateApi(req);
      if (res && res.code === 200) {
        const list = res.data?.data || res.data || [];
        templates.value = Array.isArray(list) ? list : [];
      } else {
        templates.value = [];
      }
      loaded.value = true;
    } catch (e) {
      templates.value = [];
      loaded.value = true;
    }
    return templates.value;
  };

  return { templates, options, fetchTemplates, loaded };
});
