import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { getPlatFormTemplate as getPlatFormTemplateUrl } from "@/api/system.js";
import { getCorpTemplate as getCorpTemplateUrl, getCurrentTemplate } from "@/api/corp.js";
import { ElMessage } from "element-plus";

const tempOrder = {
  outpatient: 1,
  inhospital: 2,
  physicalExaminationTemplate: 3,
  healthProjectTemplate: 4,
};

export const templateStore = defineStore("template", () => {
  const col = { lg: 24, md: 24, span: 24 };
  const rowCol = { span: 24 };
  const corpTemplate = ref([]); // 不会被改变, 只用做展示的模版
  const needChangeCorpTemplate = ref([]); // 可能会改变的模板
  const platformTemplateList = ref([]);
  const corpTemplateList = computed(() => {
    return corpTemplate.value.map((item) => {
      return { ...item, templateList: addNewAttribute(item) };
    });
  });
  const templateObj = computed(() => {
    let obj = {};
    let needShowTemplates = corpTemplateList.value.filter((item) => item.templateType === "baseTemplate" || item.templateType === "internalTemplate");
    needShowTemplates.forEach((item) => {
      item.templateList.forEach((e) => {
        obj[e.title] = e.fieldStatus === "enable";
      });
    });
    return obj;
  });
  const loading = ref(false);
  async function getPlatFormTemplate() {
    let { data, success } = await getPlatFormTemplateUrl();
    if (success) {
      platformTemplateList.value = data.data;
    } else {
      platformTemplateList.value = [];
    }
  }
  async function getCorpTemplate() {
    if (loading.value) return;
    loading.value = true;
    const { data } = await getCorpTemplateUrl();
    const list = Array.isArray(data.data) ? data.data.map(formatTemp).sort((a, b) => (tempOrder[a.templateType] || 0) - (tempOrder[b.templateType] || 0)) : [];
    corpTemplate.value = JSON.parse(JSON.stringify(list));
    needChangeCorpTemplate.value = JSON.parse(JSON.stringify(list));
    loading.value = false;
  }

  function formatTemp(temp) {
    const templateList = Array.isArray(temp.templateList)
      ? temp.templateList
          .filter(Boolean)
          .sort((a, b) => a.sort - b.sort)
          .map((i) => {
            const { value, ...item } = i;
            return item;
          })
      : [];
    return { ...temp, templateList };
  }

  function addNewAttribute(item) {
    return item.templateList.map((e) => {
      e["col"] = col;
      if (e.type === "textarea" || e.type === "reference" || e.type === "files" || item.templateType === "internalTemplate") {
        e["col"] = rowCol;
      }
      return e;
    });
  }
  function templateSubscribe(callback) {
    this.$subscribe((mutation, state) => {
      callback && callback(state);
    });
  }
  function isShowCell(title) {
    return templateObj.value[title];
  }

  const typeLoading = {};
  async function getTempateByType(type) {
    if (!type || typeLoading[type]) return;
    typeLoading[type] = true;
    const { success, data, message } = await getCurrentTemplate(sessionStorage.getItem("corpId"), type);
    if (success && data && data.data) {
      const temp = formatTemp(data.data);
      const index = corpTemplate.value.findIndex((i) => i.templateType === type);
      if (index >= 0) corpTemplate.value[index] = temp;
    } else {
      ElMessage.error(message);
    }
    typeLoading[type] = false;
  }

  return {
    loading,
    getPlatFormTemplate,
    getCorpTemplate,
    corpTemplate,
    needChangeCorpTemplate,
    corpTemplateList,
    platformTemplateList,
    templateSubscribe,
    isShowCell,
    getTempateByType,
  };
});
