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: {
    nextTab() {
      let i = this.activeName.split("index")[1] - 0
      i++
      if (i == 5) {
        return
      } else {
        this.activeName = "index" + i
        this.handleTabClick({ index: i, name: "" })
      }
    },
    prevTab(done) {
      let i = this.activeName.split("index")[1] - 0
      i--
      this.activeName = "index" + i
      this.handleTabClick({ index: i, name: "" })
      done()
    },
    handleTabClick({ index, name }) {
      const { formId, id, silent } = this.formTabs[index]
      console.log('表单项', this.formTabs)
      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()
          this.nextTab()
        })
    },

    // 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
        })
    },
  },
}
