<template>
  <a-input
    v-model:value="modelV.value"
    :placeholder="placeholder"
    :show-count="showCount"
    :maxlength="maxlength"
  />
  <div style="color: red; font-size: 10px" v-if="modelV.value && validated===0 && isExistName">
    名称重复，请重新输入
  </div>
</template>
<script setup>
import {defineProps, defineEmits, watch, ref, onMounted} from "vue";
import {validateName} from "@/api/index1";
import {Form} from "ant-design-vue";

const props = defineProps({
  value: {
    type: String,
  },
  id: {
    type: String,
  },
  placeholder: {
    type: String,
  },
  type: {
    type: Number,
    default: 1,
  },
  maxlength: {
    type: Number,
    default: 30,
  },
  showCount: {
    type: Boolean,
    default: false,
  },
  validated: {
    type: Number,
    default: 0,
  },
  onceName: {
    type: String,
  },
});

const emit = defineEmits(["update:value",'update:validated']);

const modelV = ref({
  value: props.value
});

const isExistName = ref(true);

const rulesRef = ref({
  value: [{
    required: true,
    validator: validateValue,
    trigger: "change",
    message: "请输入名称",
  },
  ],
});

Form.useForm(modelV, rulesRef, { debounce: { wait: 800 } });

onMounted(() => {
  if(props.onceName==modelV.value.value){
    isExistName.value = false;
  }else{
    isExistName.value = true;
  }
})

watch(props, () => {
  if(props.onceName==modelV.value.value){
    isExistName.value = false;
  }else{
    isExistName.value = true;
  }
  modelV.value.value = props.value;
});

watch(() => modelV.value.value, () => {
  emit("update:validated", 1);
  emit("update:value", modelV.value.value);
});

async function validateValue() {
  if (!modelV.value.value) {
    return Promise.reject("请输入名称");
  }
  return validateName({ name: modelV.value.value, type: props.type, id: props.id }).then(res => {
      if (res.data.data === 1 && isExistName.value) {
        emit("update:validated", 0);
        return Promise.reject("名称重复");
      }
      emit("update:validated", 2);
      return Promise.resolve();
    }
  );
}
</script>
<style lang="scss">

.pro {
  .ant-input-affix-wrapper {
    padding: 4px 8px;
    border-radius: 8px;

  }
}

.road {
  .ant-input-affix-wrapper {
    padding: 0px 8px;
    border-radius: 8px;
  }
}


.b_input,
.i1_input {
  .ant-input-affix-wrapper {
    position: relative;
    display: inline-block;
    width: 88%;
    min-width: 0;
    padding: 8px 17px;
    color: rgba(0, 0, 0, 0.85);
    font-size: 14px;
    line-height: 1.5715;
    background-color: #fff;
    background-image: none;
    border: 1px solid #d9d9d9;
    border-radius: 8px;
    transition: all 0.3s;
    display: inline-flex;
  }
}
</style>