<template>
  <div class="textarea-wrap">
    <textarea
      type="text"
      v-model="formValue"
      @input="onChange"
      :placeholder="placeholder"
      :minlength="minlength"
      :maxlength="maxlength"
      ref="textareaRef"
      @focus="onFocus"
      @blur="onBlur"
    />
    <p class="icon-wrap" v-if="formValue" @click="onClear">
      <i class="iconfont icon-mobile-ui-guanbi2fill"></i>
    </p>
  </div>
</template>

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

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