<template>
  <view class="w-full">
    <view @click="show = true">
      <u-input
        class="w-full !pointer-events-none"
        :placeholder="placeholder"
        :value="showText"
        type="select"
      />
    </view>
    <u-select
      @confirm="handleConfirm"
      :default-value="defaultValue"
      v-model="show"
      :list="getOptions"
    ></u-select>
  </view>
</template>
<script>
import { omit } from 'lodash-es'
export default {
  props: {
    api: {
      type: Function,
      default: () => {},
    },
    value: {
      type: [Array, Object, String, Number],
    },
    params: {
      type: Object,
      default: () => ({}),
    },
    labelField: {
      type: String,
      default: 'label',
    },
    valueField: {
      type: String,
      default: 'value',
    },
    placeholder: {
      type: String,
      default: '请选择',
    },
  },

  data() {
    return {
      show: false,
      isFirstLoad: true,
      options: [],
    }
  },
  computed: {
    currentOption() {
      const item = this.getOptions.find((e) => e.value == this.value)
      return item ?? {}
    },
    showText() {
      return this.currentOption?.label ?? this.value
    },
    defaultValue() {
      const index = this.getOptions.findIndex((e) => e.value == this.value)
      return [index > -1 ? index : 0]
    },
    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
      }, [])
    },
  },
  created() {
    this.fetch()
  },
  methods: {
    async fetch() {
      const api = this.api
      if (!api || !this.isFunction(api)) return
      this.options = []
      try {
        const data = await api(this.params)
        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)
    },
    handleConfirm(e) {
      if (!e.length) return
      const { value } = e[0]
      if (value == null) return
      this.$emit('change', value)
      this.$emit('input', value)
    },
    isFunction(fn) {
      return typeof fn === 'function'
    },
  },
  watch: {
    params: {
      handler() {
        !this.isFirstLoad && this.fetch()
      },
      deep: true,
    },
  },
}
</script>
