<template>
  <section class="AiSelect">
    <picker :range="options" :range-key="labelName" @change="handleConfirm" :disabled="disabled" :mode="mode">
      <div class="display" v-if="$slots.default">
        <slot/>
      </div>
      <div v-else class="display">
        <u-icon v-if="selectedLabel" :label="selectedLabel" label-pos="left" name="arrow-right" color="#ddd"/>
        <u-icon v-else :label="placeholder" label-pos="left" name="arrow-right" color="#ddd" label-color="#999"/>
      </div>
    </picker>
  </section>
</template>

<script>
export default {
  name: "AiSelect",
  model: {
    event: "input",
    prop: "value"
  },
  props: {
    value: String,
    placeholder: {default: "请选择"},
    list: {default: () => []},
    mode: {default: "selector"},
    dict: {default: ""},
    disabled: Boolean,
    labelName: {default: "label"},
    valueName: {default: "value"},
  },
  computed: {
    selectedLabel() {
      let str = this.options.find(e => e?.[this.valueName] == this.value)?.[this.labelName]
      return this.selected?.[this.labelName] || str
    },
    options() {
      return this.dictKey ? this.$dict.getDict(this.dict).map(e => ({
        value: e.dictValue,
        label: e.dictName
      })) : this.list || []
    }
  },
  data() {
    return {
      dictKey: '',
      selected: {}
    }
  },
  created() {
    this.dict && this.$dict.load(this.dict).then(() => {
      this.dictKey = this.dict
    })
  },
  methods: {
    handleConfirm(v) {
      if (this.mode == "selector") {
        this.selected = this.options?.[v.detail?.value] || {}
        this.$emit("data", this.selected)
        this.$emit("input", this.selected?.[this.valueName])
      }

    }
  }
}
</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>
