<template>
  <div class="input-wrap">
    <input
      ref="inputRef"
      v-model="formValue"
      @input="onChange"
      v-bind="$attrs"
      @focus="onFocus"
      @blur="onBlur"
      :type="type"
      :minlength="minlength"
      :maxlength="maxlength"
    />
    <p class="icon-wrap" v-if="formValue && closeable" @click.stop="onClear">
      <i class="iconfont icon-mobile-ui-guanbi2fill"></i>
    </p>
  </div>
</template>

<script>
import { onDebounce } from "@packages/utils/index";
export default {
  name: "WlInput",
  props: {
    value: {
      type: [String, Number],
      default: "",
    },
    closeable: {
      type: Boolean,
      default: true,
    },
    needDebounce: {
      type: Boolean,
      default: true,
    },
    type: {
      type: String,
      default: "",
    },
    minlength: {
      type: Number,
      default: 0,
    },
    maxlength: {
      type: Number,
      default: null,
    },
  },
  data() {
    return {
      formValue: "",
    };
  },
  methods: {
    onClear() {
      this.$emit("input", "");
      this.focus();
      this.$emit("onClear");
    },
    onBlur() {
      this.$emit("onBlur", "");
    },
    onFocus() {
      this.$emit("onFocus", "");
    },
    onDebounceSave: onDebounce(function(event) {
      this.$emit("onChange", event.target.value);
      this.$emit("input", event.target.value);
    }, 500),
    onChange(event) {
      if (this.type === "digit") {
        this.formValue = parseInt(this.formValue);
      }
      if (this.needDebounce) {
        this.onDebounceSave(event);
      } else {
        this.$emit("onChange", event.target.value);
        this.$emit("input", event.target.value);
      }
    },
    focus() {
      this.$refs.inputRef.focus();
    },
  },
  watch: {
    value: {
      handler(val) {
        this.formValue = val;
      },
      immediate: true,
    },
  },
};
</script>

<style lang="scss" scoped>
.input-wrap {
  height: j(50);
  padding: 0 j(12);
  background-color: #fff;
  @extend %flex-between;
  > input {
    width: 100%;
  }
  .icon-wrap {
    cursor: pointer;
    .iconfont {
      color: #c2c8cc;
      font-size: j(18);
    }
  }
}
</style>
