<template>
  <div class="textarea-wrap bg-white" data-weiling-mobile-ui-wl-textarea>
    <div class="textarea flex-between">
      <textarea
        type="text"
        class="textarea-base"
        v-model="formValue"
        @input="onChange"
        :placeholder="placeholder"
        ref="textareaRef"
        :maxlength="maxlength"
        @focus="onFocus"
        @blur="onBlur"
      />
      <p
        class="pointer uno-w-18 uno-h-18"
        v-if="formValue && clearable"
        @click="onClear"
      >
        <WlPic :src="deleteIcon" />
      </p>
    </div>
    <p class="fs12 text-right text-base-color" v-if="maxlength > 0">
      {{ formValue.length }}/{{ maxlength }}
    </p>
  </div>
</template>

<script lang="ts">
/*然后不是以什么条件来说放到下周了吗
 * @Author: Liao.xiuli
 * @Date: 2021-09-18 11:18:59
 * @Last Modified by: Liao.xiuli
 * @Last Modified time: 2023-11-09 16:16:01
 */
export default {
  name: "WlTextarea",
};
</script>

<script setup lang="ts">
import { ref, watchEffect } from "vue";
import { onDebounce } from "@mobileUI/utils/index";
import deleteIcon from "@mobileUI/assets/images/delete.png";
import WlPic from "@mobileUI/components/WlPic/src/index.vue";
type Props = {
  modelValue: string;
  placeholder?: string;
  clearable?: boolean;
  needDebounce?: boolean;
  maxlength?: number;
};
const props = withDefaults(defineProps<Props>(), {
  modelValue: "",
  placeholder: "",
  clearable: true,
  needDebounce: true,
  maxlength: null,
});

const emit = defineEmits<{
  (e: "onBlur");
  (e: "onFocus");
  (e: "onChange", val: string);
  (e: "update:modelValue", val: string);
}>();

const formValue = ref("");
const textareaRef = ref<HTMLElement>(null);

const onBlur = emit("onBlur");

const onFocus = emit("onFocus");

const onClear = () => emit("update:modelValue", "");

const onTriggerFocus = () => {
  textareaRef.value.focus();
};

const onDebounceSave = onDebounce(() => {
  emit("onChange", formValue.value);
  emit("update:modelValue", formValue.value);
}, 500);

const onChange = () => {
  if (props.needDebounce) {
    onDebounceSave();
  } else {
    emit("onChange", formValue.value);
    emit("update:modelValue", formValue.value);
  }
};

watchEffect(() => {
  formValue.value = props.modelValue;
});

defineExpose({
  onTriggerFocus,
});
</script>
