<template>
  <el-form-item v-show="show" :label="label" :prop="prop" :rules="rules">
    <template v-if="component === 'MUpload'">
      <m-upload :value.sync="currentValue" v-bind="options" v-on="$attrs.on" />
    </template>
    <template v-else>
      <component :is="`el-${component}`" size="small" v-model="currentValue" v-bind="options" style="width: 100%;" 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>
        <template v-if="component === 'input'">
          <template v-if="$attrs.appendText" slot="append">{{ $attrs.appendText }}</template>
          <template v-if="$attrs.prependText" slot="prepend">{{ $attrs.prependText }}</template>
        </template>
      </component>
    </template>
    <div v-if="$attrs.helpMessage" class="el-help-message">{{ $attrs.helpMessage }}</div>
  </el-form-item>
</template>

<script>
import MUpload from '@/components/McUpload'

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',
  components: { MUpload },
  inheritAttrs: false,
  props: {
    value: {
      type: [String, Number, Object, Array],
      default: () => '',
    },
    label: String,
    prop: {
      type: String,
      required: true,
    },
    component: {
      type: String,
      required: true,
    },
    rules: {
      type: [Object, Array],
      default: () => [],
    },
    show: {
      type: Boolean,
      default: 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>

<style lang="less" scoped>
.el-help-message {
  color: #999;
  font-size: 12px;
}
</style>
