<template>
  <el-form-item :label="showLabel ? label: ''" :rules="requireRule(!disabled && required, label)" :prop="prop" :label-width="labelWidth" >
    <el-select ref="select" v-model="formRef.model[prop]" @change="handleChange" :multiple="multiple" @clear="clear"
               :clearable="clearable" filterable :disabled="disabled" :style="{width}" :allow-create="allowCreate">
      <el-option v-if="showEmpty" :label="emptyLabel" :value="undefined" key="select" />
      <el-option v-for="item in selections" :key="item.value" :value="item[valueProp]" :label="item.label" />
    </el-select>
  </el-form-item>
</template>

<script>
import mixin from './mixin'
import { mapGetters } from 'vuex'
import {isBlank} from "../../../../utils";
/**
 * 下拉框组件
 */
export default {
  mixins: [mixin],
  props: {
    multiple: {
      type: Boolean,
      default: false,
    },
    labelWidth: {
      type: String
    },
    dictType: {
      type: String,
      required: true,
    },
    showEmpty: {
      type: Boolean,
      default: false,
    },
    emptyLabel: {
      type: String,
      default: '全部',
    },
    exclude: {
      type: Array,
      default: () => []
    },
    labelProp: {
      type: String
    },
    defaultValue:{
      type: String,
      default:''
    },
    valueProp:{
      type: String,
      default: 'value'
    },
    span: {
      type: Number,
      default: 8
    },
    allowCreate:{
      type: Boolean,
      default: false,
    },
  },
  computed: {
    ...mapGetters(['dict']),
    selections() {
      return (this.dict[this.dictType] || [])
      .filter(({ value,status}) => status !== '1' && (this.exclude.length === 0 || !this.exclude.includes(value)))
    },
    selectedLabel() {
      return this.$refs.select && this.$refs.select.selectedLabel
    },
  },
  mounted() {

  },
  created(){
    this.handleChange(this.formRef.model[this.prop])
    if(!isBlank(this.defaultValue)){
      this.formRef.model[this.prop] = this.defaultValue
    }
  },
  methods: {
    handleChange(cellValue) {
      const target = this.selections.filter(({ value }) => String(value) === String(cellValue))
      let res = target && target.length > 0 ? target[0] : ''
      this.$nextTick(() => {
        this.$emit('change', res)
      })

      if (this.labelProp) {
        this.$set(this.formRef.model, this.labelProp, res.label)
      }
    },
    clear(){
      this.$emit('clear')
    }
  },
}
</script>
