import { addPatient } from "@/api/patient.js"

import FormTab from "./FormTab"
import { mapGetters } from "vuex"
import { getCurrentFormByType } from "@/api/coop-group.js"
export default {
  components: { FormTab },
  data() {
    return {
      activeName: "index0",
      fromLoading: false,
      patientStandbyId: null, // 备用id
      formTabs: [],
      formTabsList: [],
      isUpdated: false,
    }
  },
  computed: {
    ...mapGetters({
      group: ["user/group"],
    }),
  },

  methods: {
    handleTabClick({ index, name }) {
      const { formId, id, silent } = this.formTabs[index]
      if (formId && silent) {
        this.formTabs[index]["silent"] = false //控制是否获取接口数据
        return
      }
      this.formTabs.splice(index, 1, {
        ...this.formTabsList.find((_) => _.id === id),
      })
    },
    async addPatient(data, done, cb, type) {
      addPatient(data, type)
        .then((res) => {
          this.$message.success("操作成功")
          if (res.data) {
            this.isUpdated = true
            this.patientStandbyId = res.data.patientId
            if (
              cb &&
              Object.prototype.toString.call(cb) === "[object Function]"
            ) {
              cb(res)
            }
          }
        })
        .finally((e) => {
          done()
        })
    },

    // json存储
    setFormJson(formJson) {
      const idx = this.activeName.replace("index", "")
      this.formTabs[idx].formJson = formJson
      this.formTabsList[idx].formJson = formJson
    },

    getCurrentFormByType(type = 1) {
      this.fromLoading = true
      getCurrentFormByType({
        type,
        groupId: this.group.groupId,
      })
        .then((res) => {
          if (res.code === 1) {
            const formTabs = []
            this.formTabsList = res.data.map((item, index) => {
              if (index === 0) {
                formTabs.push({
                  silent: false,
                  ...item,
                  label: item.tabName,
                })
              } else {
                formTabs.push({
                  id: item.id,
                  silent: true,
                  label: item.tabName,
                })
              }
              return {
                ...item,
                silent: false,
                label: item.tabName,
              }
            })
            this.formTabs = formTabs
          }
        })
        .finally(() => {
          this.fromLoading = false
        })
    },
  },
}
