<template>
  <div class="ezj-form-pane">
    <!-- 多个表单 -->
    <template v-if="form.hasAdd">
      <template v-for="(item, index) in formModel">
        <form-form
          :options="form.options"
          :model="item"
          :items="form.items"
          @onSubmit="onSubmit"
          :key="index"
        >
          <el-button>增加一项</el-button>
          <el-button>保存</el-button>
        </form-form>
      </template>
    </template>

    <!-- 一个表单 -->
    <template v-else>
      <form-form
        :options="form.options"
        :model="formModel"
        :items="form.items"
        @onSubmit="onSubmit"
      ></form-form>
    </template>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'EzjFormPane',
  components: {},
  props: {
    title: String,
    get: {
      type: Object,
      default() {
        return {}
      }
    },
    update: {
      type: Object,
      default() {
        return {}
      }
    },
    data: Object,
    headers: Object,
    form: Object
  },
  data() {
    return {
      model: null
    }
  },
  computed: {
    isMultiple() {
      return Array.isArray(this.model)
    },
    formModel() {
      return this.model || this.form.model
    }
  },
  methods: {
    init() {
      this.getData()
    },
    // 获取
    getData() {
      const { action, data = {}, callback } = this.get
      axios.get(action, { params: data }).then(res => {
        let { data } = res
        if (callback) {
          data = callback(data)
        }
        this.model = data
      })
    },
    // 更新
    updateData(params) {
      const { action, data = {}, callback } = this.update
      params = Object.assign({}, params, data)
      if (callback) {
        params = callback(params)
      }
      axios.post(action, params).then(res => {
        this.$emit('update')
      })
    },
    onSubmit(data) {
      this.updateData(data)
    }
  },
  beforeMount() {
    this.init()
  }
}
</script>

<style lang="scss">
</style>
