<script setup>
import { computed, ref, watch } from "vue";
const props=defineProps({
  defaultVal:{
    type:String,
    default:''
  },
  placeholder:{
    type:String,
    default:'请输入关键词'
  },
  disabled:{//是否禁用
    type:Boolean,
    default:false
  },
  autoFocus:{
    type:Boolean,
    default:false
  }
})

const emit = defineEmits(["search",'clean','blur'])
let searchData = ref(props.defaultVal||"");
let isFocus=ref(false)
let showClean = computed(() => {
  return searchData.value.length > 0 ? true : false;
});
const handleFocus = () => {
  //聚焦到input框上,样式改变
  isFocus.value=true
};
const handleBlur = () => {
  isFocus.value=false
};
const handleClean = () => {
  searchData.value = "";
  emit('clean')
};
const handleSearch = ()=>{
  if(!searchData.value.length){
    emit('clean')
    return
  }
  emit('search',searchData.value)
}

watch(
  ()=>props.defaultVal,
  ()=>{
    searchData.value=props.defaultVal
  }
)
</script>
<template>
  <div :class="['search-wrap',(isFocus||searchData)&&'focus']">
    <span v-show="!isFocus&&!searchData"></span>
    <input
      type="text"
      :placeholder="props.placeholder"
      :autofocus="props.autoFocus"
      v-model="searchData"
      @blur="handleBlur"
      @focus="handleFocus"
      @keyup.enter="handleSearch"
      :disabled="props.disabled"
    />
    <span class="clean" v-show="showClean" @click="handleClean"></span>
  </div>
</template>



<style lang="scss" scoped>
.search-wrap {
  display: flex;
  align-items: center;
  padding: 10px 20px;
  // position: absolute;
  // right: 160px;
  width: 300px;
  height: 40px;
  // top: 50%;
  // margin-top: -20px;
  border-radius: 20px;
  background-color: #ebebeb;
  border: 1px solid #ebebeb;
  transition: 0.3s;
  &.focus {
    background: #ffffff;
    border: 1px solid #f3a52f;
  }
  span {
    display: inline-block;
    width: 14px;
    height: 14px;
    background: no-repeat center/cover url("../assets/icon-search.png");
    margin-right: 6px;
    &.clean {
      width: 20px;
      height: 20px;
      margin-right: 0;
      cursor: pointer;
      background: no-repeat center/cover url("../assets/icon-close.png");
    }
  }
  input {
    flex: 1;
    background: none;
    outline: none;
    border: none;
  }
}
</style>