<script lang="ts" setup>
import { ref, watch } from 'vue';
import ErrorIcon from '@/components/ErrorIcon/ErrorIcon.vue';
import SearchIcon from '@/components/SearchIcon/SearchIcon.vue';
import ClearableIcon from '@/components/ClearableIcon/ClearableIcon.vue';

const emits = defineEmits(['input', 'change', 'blur', 'focus', 'clear', 'keyupEnter']);

const props = defineProps({
  value: {
    type: String,
    required: false,
    default: ''
  },
  idStr: {
    type: String,
    required: false,
    default: 'search'
  },
  placeholder: {
    type: String,
    required: false,
    default: ''
  }
});

const mouseFlag = ref(false);
const focusState = ref(false);

watch(
  () => props.value,
  (val: any) => {
    searchValue.value = val;
  }
);

const searchValue = ref(props.value);

function input(value: string) {
  emits('input', value);
}

function change(value: string) {
  emits('change', value);
}

function blur(event: any) {
  focusState.value = false;
  emits('blur', searchValue.value, event);
}

function focus(event: any) {
  focusState.value = true;
  emits('focus', searchValue.value);
}

function clear(event: any) {
  emits('clear', '');
}

// 回车事件
function keyupEnter() {
  emits('keyupEnter', searchValue.value);
}
</script>

<template>
  <el-input
    v-model="searchValue"
    v-addId.input="idStr"
    v-clearable
    clearable
    type="text"
    :class="[
      'input-of-search',
      (searchValue || searchValue === 0) && (mouseFlag || focusState) ? 'have-text' : ''
    ]"
    :placeholder="placeholder"
    @input="input"
    @change="change"
    @focus="focus"
    @blur="blur"
    @clear="clear"
    @keyup.enter="keyupEnter"
    @mouseenter="mouseFlag = true"
    @mouseleave="mouseFlag = false"
  >
    <template #prefix>
      <SearchIcon @click="keyupEnter" />
    </template>
    <template #suffix>
      <ClearableIcon />
    </template>
  </el-input>
</template>

<style lang="scss" scoped>
.input-of-search.el-input--prefix {
  width: 296px;

  :deep(.el-input__wrapper) {
    display: flex;
    padding-left: 0 !important;
  }

  :deep(.el-input__inner) {
    position: relative;
    left: -23px;
    padding-left: 11px !important;
  }

  :deep(.el-input__prefix) {
    position: relative;
    left: calc(100% - 28px);
  }

  :deep(.el-input__suffix) {
    position: relative;
    right: 24px !important;

    .icon-x-solid-box::before {
      content: '';
      position: absolute;
      top: 2px;
      right: -6px;
      display: inline-block;
      width: 1px;
      height: 12px;
      background-color: var(--o-border-color-lighter);
    }
  }

  :deep(.icon-search-box) {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .icon-search {
      font-size: 16px;
      cursor: pointer;
    }
  }
}

.input-of-search.have-text {
  :deep(.icon-x-solid-box) {
    opacity: 1 !important;
  }
}
</style>