<template>
  <div class="ai-select">
    <el-select clearable class="w100"
               :value="value"
               :size="$attrs.size || 'small'"
               :filterable="isAction||filterable"
               :disabled="disabled"
               v-bind="$attrs"
               v-on="$listeners">
      <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 ops" :key="index"
                   :label="item.dictName||item[actionProp.label]"
                   :value="item.dictValue>-1?item.dictValue:item[actionProp.value]"
                   :disabled="check(item[actionProp.value])"/>
      </template>
    </el-select>
  </div>
</template>

<script>
import Dict from "../../lib/js/dict";

export default {
  name: 'AiSelect',
  model: {
    prop: 'value',
    event: 'change'
  },
  watch: {
    instance: {
      deep: true,
      handler(v) {
        v && this.isAction && !this.options.toString() && this.getOptions()
      }
    },
    action() {
      this.isAction && this.getOptions()
    },
    value(v) {
      this.handleSelect(v)
    }
  },
  props: {
    value: {default: null},
    selectList: {
      type: Array
    },
    width: {
      type: String,
      default: '216'
    },
    dict: String,
    instance: Function,
    action: {default: ""},
    prop: {
      default: () => ({})
    },
    filterable: Boolean,
    disabled: Boolean
  },
  data() {
    return {
      options: [],
      filter: "",
      Dict
    }
  },
  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
      }
    },
    ops: v => v.dict ? v.Dict.getDict(v.dict) : 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
        }
      }).then(() => this.handleSelect())
    },
    handleSelect(v = this.value) {
      this.disabled || this.$emit("select", this.isAction ? this.options.find(e => e[this.actionProp.value] == v) :
          this.ops.find(e => this.dict ? e.dictValue == v : e[this.actionProp.value] == v))
    },
    check(v) {
      return this.actionProp.disabled && [this.actionProp.disabled].flat().includes(v)
    }
  },
  created() {
    this.getOptions()
  }
}
</script>
