<template>
  <div class="ai-select">
    <el-select clearable :value="modelValue" :filterable="isAction||filterable" 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.label" :value="op[actionProp.value]"/>
      </template>
      <template v-else>
        <el-option v-for="(item, index) in selectList" :key="index"
                   :label="item[actionProp.label]"
                   :value="item[actionProp.value]"
                   :disabled="check(item[actionProp.value])"/>
      </template>
    </el-select>
  </div>
</template>

<script>
export default {
  name: 'AiSelect',
  watch: {
    instance: {
      deep: true,
      handler(v) {
        v && this.isAction && !this.options.toString() && this.getOptions()
      }
    },
    action() {
      this.isAction && this.getOptions()
    },
    modelValue(v) {
      this.handleSelect(v)
    }
  },
  props: {
    modelValue: {default: null},
    selectList: {type: Array},
    instance: Function,
    action: {default: ""},
    prop: {default: () => ({})},
    filterable: Boolean,
  },
  data() {
    return {
      options: [],
      filter: "",
    }
  },
  computed: {
    isAction: v => !!v.action,
    actionOps() {
      const {filter} = this
      const LABEL = this.actionProp.label
      return this.options.map(e => ({
        ...e,
        label: typeof LABEL == "function" ? LABEL?.(e) : e[LABEL]
      })).filter(e => !filter || e.label.indexOf(filter) > -1)
    },
    actionProp() {
      return {
        label: 'label',
        value: 'id',
        ...this.prop
      }
    },
  },
  methods: {
    getOptions() {
      this.instance?.post(this.action, null, {
        params: {size: 999}
      }).then(res => {
        if (res?.data) {
          this.options = res.data.records || res.data
        }
      }).then(() => this.handleSelect())
    },
    handleSelect(v = this.modelValue) {
      this.disabled || this.$emit("select", this.isAction ? this.options.find(e => e[this.actionProp.value] == v) :
          this.selectList.find(e => e[this.actionProp.value] == v))
    },
    check(v) {
      return this.actionProp.disabled && [this.actionProp.disabled].flat().includes(v)
    }
  },
  created() {
    this.getOptions()
  }
}
</script>
<style lang="scss" scoped>
.ai-select {
  width: 100%;

  :deep(.el-select) {
    width: 100%;

    .el-input__wrapper {
      background: transparent;
    }
  }
}
</style>
