<template>
  <el-form
    :model="dynamicForm"
    size="small"
    :label-width="labelWidth"
    v-loading="loading"
    :disabled="disabled"
  >
    <dynamic-form
      v-for="item in formItemList"
      :key="item.columnName"
      :value="dynamicForm[item.columnName]"
      :columnName="item.columnName"
      :chooseType="item.chooseType"
      :columnMean="item.columnMean"
      :columnLength="item.columnLength"
      :chooseList="item.chooseList"
      @input="handleInput($event, item.columnName)"
    />
  </el-form>
</template>

<script>
import dynamicForm from './dynamic-form.vue'
export default {
  name: 'FormItem',
  components: { dynamicForm },
  props: {
    labelWidth: {
      type: String, //label长度
      default: '100px'
    },
    formItemList: {
      type: Array,
      default: function() {
        return []
      }
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dynamicForm: {},
      loading: false,
      dataList: []
    }
  },
  created() {
    this.formItemList.forEach(item => {
      if (item.chooseType === 4) {
        this.dynamicForm[item.columnName] = []
      } else {
        this.dynamicForm[item.columnName] = ''
      }
    })
  },
  methods: {
    init(dataList) {
      this.loading = true
      const formData = {}
      this.dataList = dataList
      this.formItemList.forEach(item => {
        if (item.chooseType === 4) {
          formData[item.columnName] = []
        } else {
          formData[item.columnName] = ''
        }
        const itemData = dataList.find(i => i.columnName === item.columnName)
        if (itemData && itemData.columnValue) {
          formData[item.columnName] = itemData.columnValue
          if (item.chooseType === 4) {
            formData[item.columnName] = itemData.columnValue.split(',')
          } else {
            formData[item.columnName] = itemData.columnValue
          }
        }
      })
      this.dynamicForm = formData
      this.$nextTick(() => {
        this.loading = false
      })
    },
    handleInput(val, key) {
      this.dynamicForm[key] = val
    },
    getDataForm() {
      const formList = []
      this.formItemList.forEach(item => {
        const params = {}
        params.columnName = item.columnName
        if (item.chooseType === 4) {
          params.columnValue = this.dynamicForm[item.columnName].join()
        } else {
          params.columnValue = this.dynamicForm[item.columnName]
        }
        if (this.dataList.length > 0) {
          const itemData = this.dataList.find(i => i.columnName === item.columnName)
          if (itemData && itemData.id) {
            params.id = itemData.id
          }
        }
        formList.push(params)
      })
      return formList
    }
  }
}
</script>

<style>
</style>