<template>
  <section class="AiRange" :style="{width}">
    <el-input type="number" v-model.number="valueStart" size="small" :placeholder="startPlaceholder" @change="saveNum"/>
    <span class="separator">-</span>
    <el-input type="number" v-model.number="valueEnd" size="small" :placeholder="endPlaceholder" @change="saveNum"/>
    <span class="el-icon-circle-close" v-if="isUse" @click="shutoff"/>
    <div v-else/>
  </section>
</template>

<script>
export default {
  name: "AiRange",
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    width: {type: String, default: '200px'},
    startPlaceholder: String,
    endPlaceholder: String,
    value: {default: () => []},
  },
  computed: {
    isUse() {
      return !!this.valueStart || !!this.valueEnd
    },
  },
  data() {
    return {
      valueStart: null,
      valueEnd: null
    }
  },
  methods: {
    shutoff() {
      this.valueStart = null
      this.valueEnd = null
      this.saveNum()
    },
    saveNum() {
      this.$emit('change', [this.valueStart, this.valueEnd])
    },
    initValue() {
      let unwatch = this.$watch('value', (v) => {
        if (this.isUse) unwatch && unwatch()
        else if (!!v) {
          this.valueStart = v?.[0] || ""
          this.valueEnd = v?.[1] || ""
          unwatch && unwatch()
        }
      }, {immediate: true})
    },
  },
  created() {
    this.initValue()
  }
}
</script>

<style scoped lang="scss">
.AiRange {
  display: flex;
  border: 1px solid #D0D4DC;
  border-radius: 2px;
  align-items: center;
  height: 32px;
  box-sizing: border-box;

  ::v-deep.el-input {
    min-width: 80px;
    flex: 1;

    .el-input__inner {
      border: none;
      padding: 0;
      text-align: center;
      height: 100%;
      line-height: normal;
    }
  }

  .el-icon-circle-close {
    cursor: pointer;
    opacity: 0;
    margin-right: 4px;

    &:hover {
      color: #5088FF;
    }
  }

  &:hover {
    border-color: #5088FF;

    .el-icon-circle-close {
      opacity: 1;
    }
  }
}
</style>
