<template>
  <a-select
    :value="value ? value : modelValue"
    :showSearch="showSearch"
    allowClear
    :placeholder="placeholder"
    @change="selectChange"
    style="width: 100%"
  >
    <a-select-option v-for="item in dictOptions" :key="item[replaceFields.key]" :value="item[replaceFields.key]">
      {{ item[replaceFields.value] }}
    </a-select-option>
  </a-select>
</template>

<script>
import { find } from 'lodash'
import { ajaxGetDictItems } from '@/api/services/base'

export default {
  name: 'HSelect',
  props: {
    value: {
      type: String,
      required: false,
      default: ''
    },
    defaultValue: {
      type: [String, Number],
      required: false,
      default: ''
    },
    showSearch: {
      type: Boolean,
      required: false,
      default: () => false
    },
    placeholder: {
      type: String,
      required: false,
      default: '请选择'
    },
    dictCode: {
      type: String,
      required: false,
      default: ''
    },
    replaceFields: {
      type: Object,
      required: false,
      default: () => ({
        key: 'value',
        value: 'text'
      })
    },
    options: {
      type: Array,
      required: false,
      default: () => []
    }
  },
  data() {
    return {
      modelValue: undefined,
      dictOptions: []
    }
  },
  watch: {
    value(val) {
      if (!val) this.modelValue = undefined
    },
    dictCode: {
      handler() {
        if (this.dictCode) {
          this.initDictConfig()
        }
      },
      immediate: true
    },
    options: {
      handler() {
        if (this.options && this.options.length > 0) {
          this.dictOptions = this.options
          if (this.defaultValue && String(this.defaultValue) !== '0') {
            this.modelValue = this.defaultValue
          }
          if (String(this.defaultValue) === '0') {
            this.modelValue = this.options[0][this.replaceFields.key]
            this.$emit('input', this.modelValue)
          }
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    initDictConfig() {
      ajaxGetDictItems(this.dictCode, null).then(res => {
        this.dictOptions = res.value
        if (this.defaultValue && String(this.defaultValue) !== '0') {
          this.modelValue = this.defaultValue
        }
        if (String(this.defaultValue) === '0') {
          this.modelValue = res.value[0][this.replaceFields.key]
          this.$emit('input', this.modelValue)
        }
      })
    },
    selectChange(value) {
      this.modelValue = value
      this.$emit('input', value)
      const options = find(this.dictOptions, { [this.replaceFields.key]: value })
      this.$emit('change', options || {})
    }
  }
}
</script>
