import { ref, computed } from "vue";
import { defineStore } from "pinia";
import { getCorpMemberJob } from "@/api/corp.js";
import { getRegion } from "@/api/knowledgeBase";
import { getCustomerType, getHealthIndicatorsTemplate } from "@/api/member";

export const dbStore = defineStore("dbStore", () => {
  const province = ref([]); // 省
  const area = ref({}); // 区域
  const healthIndicatorsTemplate = ref([]); // 健康指标模板
  const jobList = ref(null); // 岗位列表
  const jobMap = computed(() =>
    (jobList.value || []).reduce((acc, cur) => {
      acc[cur.value] = cur.name;
      return acc;
    }, {})
  );

  const stageList = ref([]);

  async function getArea(code) {
    const { success, data, message } = await getRegion(code);
    if (success) {
      const list = data && Array.isArray(data.data) ? data.data : [];
      if (code) area.value[code] = list;
      else province.value = list;
      return { success, list };
    } else {
      return { success, message };
    }
  }

  async function getStageList() {
    const { data } = await getCustomerType();
    const list = data.data && Array.isArray(data.data) ? data.data : [];
    stageList.value = list.map((i) => ({ label: i.name, value: i.type }));
  }

  async function getHealthIndicatorTemplate() {
    const { data } = await getHealthIndicatorsTemplate();
    healthIndicatorsTemplate.value = Array.isArray(data.templateList) ? data.templateList : [];
  }

  async function getJobList() {
    if (Array.isArray(jobList.value)) return jobList.value;
    const { data, success } = await getCorpMemberJob();
    if (success) {
      jobList.value = data.data && Array.isArray(data.data) ? data.data : [];
    }
  }
  return {
    province,
    area,
    getArea,
    healthIndicatorsTemplate,
    getHealthIndicatorTemplate,
    stageList,
    getStageList,
    jobList,
    getJobList,
    jobMap,
  };
});
