<template>
  <a-radio-group
    v-if="tagType === 'radio'"
    @change="handleInput"
    :value="value ? value : (dateValue = undefined)"
    :disabled="disabled"
  >
    <a-radio v-for="(item, key) in dictOptions" :key="key" :value="item.value">{{ item.text }}</a-radio>
  </a-radio-group>

  <a-select
    v-else-if="tagType === 'select'"
    :showSearch="showSearch"
    allowClear
    :placeholder="placeholder"
    :disabled="disabled"
    :value="value ? value : (dateValue = undefined)"
    @change="handleInput"
  >
    <a-select-option
      v-for="(item, key) in dictOptions"
      :key="key"
      :value="item.value"
      :disabled="disabledData.indexOf(item.value) !== -1"
    >
      <span style="display: inline-block; width: 100%" :title="item.text || item.label">
        {{ item.text || item.label }}
      </span>
    </a-select-option>
  </a-select>
</template>

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

export default {
  name: 'JDictSelectTag',
  props: {
    dictCode: String,
    placeholder: String,
    triggerChange: Boolean,
    disabled: Boolean,
    showSearch: {
      type: Boolean,
      required: false,
      default: () => {
        return false
      }
    },
    value: {
      type: String,
      default: ''
    },
    type: String,
    options: Array
  },
  data() {
    return {
      dictOptions: [],
      disabledData: ['email', 'shortMessage', 'wechatMessage'],
      tagType: '',
      dateValue: undefined
    }
  },
  watch: {
    dictCode: {
      immediate: true,
      handler() {
        if (this.dictCode) {
          this.initDictData()
        }
      }
    },
    options: {
      immediate: true,
      handler() {
        if (this.options && this.options.length > 0) {
          this.dateValue = undefined
          this.setCurrentDictOptions(this.options)
        }
      }
    }
  },
  created() {
    if (!this.type || this.type === 'list') {
      this.tagType = 'select'
    } else {
      this.tagType = this.type
    }
    //获取字典数据
    // this.initDictData();
  },
  methods: {
    initDictData() {
      //根据字典Code, 初始化字典数组
      ajaxGetDictItems(this.dictCode, null).then(res => {
        let result = this.$utils.requestResult(res)
        if (!result) return
        this.dictOptions = result
      })
    },
    handleInput(e) {
      let val
      if (this.tagType === 'radio') {
        val = e.target.value
      } else {
        val = e
      }
      if (this.triggerChange) {
        this.dateValue = val
        this.$emit('change', val)
      } else {
        this.$emit('input', val)
      }
    },
    setCurrentDictOptions(dictOptions) {
      this.dictOptions = dictOptions
    },
    getCurrentDictOptions() {
      return this.dictOptions
    }
  }
}
</script>
