<template>
  <div class="KuSelect">
    <el-select clearable :modelValue="modelValue" :filterable="isAction" v-bind="$attrs"
               @change="v=>$emit('update:modelValue',v)">
      <template v-if="isAction">
        <el-option v-for="op in actionOps" :key="op.id" :label="op[actionProp.label]" :value="op[actionProp.value]"/>
      </template>
      <template v-else>
        <el-option v-for="(v, k) in ops" :key="k" :label="v" :value="k"/>
      </template>
    </el-select>
  </div>
</template>

<script>
export default {
  name: 'KuSelect',
  watch: {
    instance: {
      deep: true,
      handler(v) {
        v && this.isAction && !this.options.toString() && this.getOptions()
      }
    },
    modelValue(v) {
      this.$emit("select", this.isAction ? this.options.find(e => e[this.actionProp.value] == v) :
          this.selectList.find(e => e.dictValue == v))
    }
  },
  props: {
    modelValue: {default: null},
    selectList: {default: () => []},
    instance: Function,
    action: {default: ""},
    prop: {default: () => ({})},
    dict: String
  },
  emits: ['update:modelValue'],
  data() {
    return {
      options: [],
      filter: ""
    }
  },
  computed: {
    isAction: v => !!v.action,
    actionOps() {
      return this.options.filter(e => !this.filter || e[this.actionProp.label].indexOf(this.filter) > -1)
    },
    actionProp() {
      return {
        label: 'label',
        value: 'id',
        ...this.prop
      }
    },
    ops: v => {
      if (v.dict) {
        const options = {}
        v.$dict.getDict(v.dict).map(e => options[e.dictValue] = e.dictName)
        return options
      } else return v.selectList
    }
  },
  methods: {
    getOptions() {
      this.instance?.post(this.action, null, {
        params: {size: 999}
      }).then(res => {
        if (res?.data) {
          this.options = res.data.records || res.data
        }
      })
    }
  },
  created() {
    this.getOptions()
  }
}
</script>

<style lang="scss" scoped>
.KuSelect {
  width: 100%;

  :deep(.el-select) {
    width: inherit;
  }

}
</style>
