<template>
  <u-dropdown-item
    :title="label"
    v-model="status"
    @change="handleChange"
    :options="getOptions"
  ></u-dropdown-item>
</template>
<script>
import { omit } from 'lodash-es'
export default {
  props: {
    options: {
      type: Array,
      default: () => [],
    },
    label: {
      type: String,
      default: '',
    },
    value: {
      type: [Array, Object, String, Number],
    },
    params: {
      type: Object,
      default: () => ({}),
    },
    labelField: {
      type: String,
      default: 'label',
    },
    valueField: {
      type: String,
      default: 'value',
    },
  },
  computed: {
    status: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('change', val)
        this.$emit('input', val)
      },
    },
    getOptions() {
      const { labelField, valueField } = this
      return this.options.reduce((prev, next) => {
        if (next) {
          const value = next[valueField]
          prev.push({
            ...omit(next, [labelField, valueField]),
            label: next[labelField],
            value: value,
          })
        }
        return prev
      }, [])
    },
  },
  data() {
    return {
      emitData: null,
      isFirstLoad: true,
    }
  },
  created() {
    this.fetch()
  },
  methods: {
    async fetch() {
      const data = this.options
      try {
        this.isFirstLoad = false
        if (Array.isArray(data)) {
          this.options = data
          this.emitChange()
          return
        }
        this.emitChange()
      } catch (error) {
        console.warn(error)
      }
    },
    emitChange() {
      this.$emit('options-change', this.getOptions)
    },
    handleChange(e) {
      const args = this.getOptions.filter((item) => item.value == e)
      this.emitData = args
    },
    isFunction(fn) {
      return typeof fn === 'function'
    },
  },
  watch: {
    params: {
      handler() {
        //
        !this.isFirstLoad && this.fetch()
      },
      deep: true,
    },
  },
}
</script>
