<template>
  <section class="AiSelect">
    <div class="display" v-if="$slots.default" @tap="handleShowOptions">
      <slot/>
    </div>
    <div v-else class="display" @tap="handleShowOptions">
      <u-icon :label="selectedLabel||placeholder" label-post="left" name="arrow-right" color="#ddd"/>
    </div>
    <u-select v-model="show" :list="options" :mode="mode" @confirm="handleConfirm"/>
  </section>
</template>

<script>
export default {
  name: "AiSelect",
  model: {
    event: "input",
    prop: "value"
  },
  props: {
    value: String,
    placeholder: {default: "请选择"},
    list: {default: () => []},
    mode: {default: "single-column"},
    dict: {default: ""},
    disabled: Boolean
  },
  computed: {
    selectedLabel() {
      let label = this.options.find(e => e.value == this.value)?.label
      return this.selected?.map(e => e.label)?.join(",") || label
    },
    options() {
      return this.dictKey ? this.$dict.getDict(this.dict).map(e => ({
        value: e.dictValue,
        label: e.dictName
      })) : this.list || []
    }
  },
  data() {
    return {
      show: false,
      dictKey: '',
      selected: []
    }
  },

  mounted() {
    this.dict && this.$dict.load(this.dict).then(() => {
      this.dictKey = this.dict
    })
  },
  methods: {
    handleConfirm(v) {
      this.selected = v
      this.$emit("data", this.selected)
      this.$emit("input", v[0].value)
      this.$forceUpdate()
    },
    handleShowOptions() {
      if (!this.disabled) this.show = true
    }
  }
}
</script>

<style lang="scss" scoped>
.AiSelect {
  max-width: 100%;

  ::v-deep .u-icon {
    margin-left: 8px;
  }

  .display {
    display: flex;
    align-items: center;

    .selectedLabel {
      flex: 1;
      min-width: 0;
      overflow: hidden;
      text-overflow: ellipsis;
      font-size: 30px;
      color: #333;
      white-space: nowrap;
    }
  }

  i {
    font-style: normal;
    font-size: 30px;
    color: $uni-text-color-grey;
  }
}
</style>
