<template>
  <div class="custom-textarea-box">
    <TTextarea
      class="custom-t-textarea"
      v-model="textarea_value"
      :placeholder="placeholder"
      :maxcharacter="maxlength"
      :autosize="{
        maxRows: maxRows,
        minRows: minRows,
      }"
    ></TTextarea>
    <div class="position-text">
      <span> {{ textareaLength }}/{{ maxlength }}</span> ｜
      <span class="reset-btn" @click="reset">清空</span>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { Textarea as TTextarea } from 'tdesign-vue-next';
import { computed, ref, watch } from 'vue';

const props = withDefaults(
  defineProps<{
    modelValue: string;
    placeholder?: string;
    maxRows?: number;
    minRows?: number;
    maxlength?: number | null;
  }>(),
  {
    placeholder: '请输入',
    maxRows: 5,
    minRows: 5,
    maxlength: 500,
  }
);
const emit = defineEmits(['update:modelValue']);
const textarea_value = ref('');
const reset = () => {
  textarea_value.value = '';
};
const textareaLength = computed(() => {
  // 文本总长度
  const total_len = textarea_value.value.length;
  if (total_len) {
    // 获取中文文本的长度
    let re = /[\u4E00-\u9FA5]/g;
    let list = textarea_value.value.match(re);
    if (list && list.length) {
      // 加上其他字符的长度
      const other_len = total_len - list.length;
      return list.length * 2 + other_len;
    }
  }
  return total_len;
});
watch(
  () => textarea_value.value,
  (v) => {
    emit('update:modelValue', v);
  }
);
watch(
  () => props.modelValue,
  (v) => {
    textarea_value.value = v;
  }
);
</script>

<style lang="less">
@import '@/style/variables.less';
.custom-textarea-box {
  width: 100%;
  background: #181818;
  border: @main-border;
  color: white;
  resize: none;
  border-radius: 8px;
  transition: border 0.2s;
  &:focus-within {
    border-color: #00f9f9;
    transition: all 0.2s;
  }
  .custom-t-textarea {
    .t-textarea__inner {
      background: #181818;
      border: none;
      color: white;
      padding: 6px 12px;
      resize: none;
      border-radius: 8px;
      transition: border 0.2s;
      &::placeholder {
        color: #888fa2;
      }
    }
    .t-textarea__limit {
      display: none;
    }
    .t-is-focused {
      box-shadow: none;
    }
  }
  .position-text {
    font-size: @font-size-12;
    text-align: right;
    padding-right: 12px;
    padding-bottom: 6px;
    .reset-btn {
      cursor: pointer;
      user-select: none;
      color: #00f9f9;
    }
  }
}
</style>
