<template>
  <div class="d-form-field mb-input">
    <van-field
      :readonly="readonly"
      v-model="formValue"
      :label="label"
      :name="name"
      :class="{
        'field-border': border,
        'field-large': size == 'large',
        'field-small': size == 'small',
      }"
      :type="type"
      :rows="rows"
      :maxlength="maxlength"
      :placeholder="placeholder"
      :required="_required"
      :disabled="disabled"
      :reset="reset"
      :rules="rules"
    />
    <slot name="button"></slot>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch } from "vue-property-decorator";
/**
 * @Description 通用表单
 * @Author ZPFly
 * @Date 2021/11/4 15:57
 */
@Component({
  name: "MobileInput",
})
export default class MobileInput extends Vue {
  @Prop({ default: "" }) value: string | undefined; // 输入框值
  @Prop({ default: "" }) label: string | undefined; // 输入框左侧文本
  @Prop({ default: "" }) placeholder: string | undefined; // 输入框占位提示文字
  @Prop({ default: "" }) name: string | undefined; // 名称，提交表单的标识符
  @Prop({ default: "" }) size: string | undefined; // 大小，可选值为 large
  @Prop({ default: false }) disabled: boolean | undefined; //是否禁用输入框
  @Prop({ default: false }) required: boolean | undefined; //是否显示表单必填星号
  @Prop({ default: false }) readonly: boolean | undefined; //只读
  @Prop({ default: false }) reset: boolean | undefined; //格式化
  @Prop({ default: true }) border: false | undefined; // 显示边框
  @Prop({ default: () => [] }) rules: any[] | undefined; // 校验规则
  @Prop({ default: "text" }) type: string | undefined; // 输入框类型
  @Prop({ default: 1 }) rows: number | undefined; // 文本域行数
  @Prop({ default: undefined }) maxlength: number | undefined; // 最大字符数

  formValue: any = ""; // 输入框值
  // 是否必输项
  get _required() {
    const rules = this.rules || [];
    let required = this.required || false;
    for (const item in rules) {
      required = required || rules[item].required;
    }
    return required;
  }
  @Watch("formValue")
  emitValue(val: any) {
    this.$emit("input", val);
  }

  @Watch("value")
  setValue(val: any) {
    if (val == "") {
      this.formValue = "";
    } else {
      this.formValue = val;
    }
  }

  @Watch("reset")
  valuedata() {
    if (this.reset == true) {
      this.formValue = "";
    }
  }

  mounted() {
    this.formValue = this.value || "";
  }
}
</script>

<style scoped lang="scss">
</style>
