<template>
    <el-form-item :label="label ? `${label}：` : ''" :prop="prop">
      <component size="small" :is="`el-${component}`" v-model="currentValue" v-bind="options" v-on="$attrs.on">
        <template v-if="component === 'select'">
          <el-option
            v-for="(item, index) in $attrs.options"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </template>
      </component>
    </el-form-item>
  </template>
  
  <script>
  const defaultOptionMap = {
    input: {
      placeholder: label => `请输入${label}`,
    },
    select: {
      placeholder: label => `请选择${label}`,
    },
    'date-picker': {
      placeholder: label => `请选择${label}`,
      valueFormat: 'yyyy-MM-dd',
    },
    'date-picker-daterange': {
      valueFormat: 'yyyy-MM-dd',
      rangeSeparator: '至',
      startPlaceholder: '开始日期',
      endPlaceholder: '结束日期',
    },
  }
  
  export default {
    name: 'BaseFormItem',
    inheritAttrs: false,
    props: {
      value: null,
      label: String,
      prop: {
        type: String,
        required: true,
      },
      component: {
        type: String,
        required: true,
      },
    },
    computed: {
      currentValue: {
        get() {
          return this.value
        },
  
        set(val) {
          this.$emit('input', val)
        },
      },
      options() {
        const options = { ...this.$attrs }
        const defaultOption = this.getDefaultOption()
  
        return {
          ...defaultOption,
          clearable: true,
          ...options,
        }
      },
    },
    methods: {
      getDefaultOption() {
        const { type } = this.$attrs
        const key = type ? `${this.component}-${type}` : this.component
        const defaultOption = defaultOptionMap[key] || defaultOptionMap[this.component] || {}
        let placeholder = defaultOption.placeholder
        if (placeholder) {
          placeholder = typeof placeholder === 'function' ? placeholder(this.label) : placeholder
        }
        return { ...defaultOption, placeholder }
      },
    },
  }
  </script>
  