<template>
  <div>
    <!-- 新增/修改模式 -->
    <a-input
      v-if="mode === '新增/修改'"
      v-model="singleValue"
      :read-only="readOnly"
      :disabled="disabled"
      style="width:100%"
      :placeholder="placeholder"
      @blur="handleBlur"
      @change="handleSingleChange"/>
    <!-- 查询模式 -->
    <a-input-group v-else compact>
      <a-input
        v-model="localValue[0]"
        class="intervalPicker-begin"
        :placeholder="startPlaceholder"
        @change="handleChange"/>
      <a-input
        class="intervalPicker-center"
        style="backgroundColor: #fff"
        placeholder="~"
        disabled
      />
      <a-input
        v-model="localValue[1]"
        class="intervalPicker-end"
        :placeholder="endPlaceholder"
        @change="handleChange"/>
    </a-input-group>
  </div>
</template>

<script>
export default {
  name: 'XIntervalPicker',
  props: {
    value: {
      type: [Array, String, Number],
      default: () => undefined
    },
    mode: {
      type: String,
      default: '查询'
    },
    readOnly: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: '请输入'
    },
    startPlaceholder: {
      type: String,
      default: '起始值'
    },
    endPlaceholder: {
      type: String,
      default: '结束值'
    }
  },
  data () {
    return {
      localValue: ['', ''],
      singleValue: ''
    }
  },
  watch: {
    value: {
      handler (newVal) {
        if (this.mode === '新增/修改') {
          this.singleValue = newVal || ''
        } else {
          this.localValue = Array.isArray(newVal) ? [...newVal] : ['', '']
        }
      },
      immediate: true
    }
  },
  methods: {
    handleChange () {
      // 如果两个输入框都为空或undefined，则发出undefined
      if (!this.localValue[0] && !this.localValue[1]) {
        this.$emit('input', undefined)
        return
      }
      // 否则发出当前数组值
      this.$emit('input', this.localValue)
    },
    handleSingleChange () {
      this.$emit('input', this.singleValue || undefined)
    },
    handleBlur (e) {
      this.$emit('blur', e)
    }
  }
}
</script>

<style lang="less" scoped>
.intervalPicker-begin {
  width: calc(50% - 14px);
}

.intervalPicker-center {
  width: 30px;
  border-left: 0;
  pointer-events: none;
}

.intervalPicker-end {
  width: calc(50% - 14px);
  border-left: 0;
}
</style>
