<template>
  <div class="search-wrap">
    <div :class="`search ${is_focus ? 'search-focus' : ''}`">
      <div class="search-icon">
        <WlPic :src="icon" />
      </div>
      <div class="search-input">
        <input
          type="text"
          :placeholder="placeholder"
          v-model="fieldValue"
          @input="onSave"
          @focus="is_focus = true"
          @blur="is_focus = false"
        />
      </div>
      <div class="search-close-icon" v-if="closable && fieldValue" @click="onClear">
        <WlPic :src="require('@/assets/images/delete.png')" />
      </div>
    </div>
    <div class="action">
      <slot name="action"></slot>
    </div>
  </div>
</template>

<script>
/*
 * @Author: Liao.xiuli
 * @Date: 2021-09-18 11:18:59
 * @Last Modified by: yangxin
 * @Last Modified time: 2022-07-21 16:15:34
 */
import WlPic from "@packages/components/Common/WlPic/src/index.vue";
import { onDebounce } from "@packages/utils/index.js";
export default {
  name: "WlSearch",
  components: { WlPic },
  props: {
    value: {
      type: String,
      default: "",
    },
    icon: {
      type: String,
      default: require("@/assets/images/search-icon.png"),
    },
    placeholder: {
      type: String,
      default: "搜索",
    },
    closable: {
      type: Boolean,
      default: true,
    },
    needDebounce: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      fieldValue: "",
      is_focus: false,
    };
  },
  methods: {
    onInput() {
      if (!this.fieldValue) return;
      this.$emit("input", this.fieldValue);
    },
    onClear() {
      this.fieldValue = "";
      this.$emit("onClear");
      this.$emit("onChange", "");
    },
    onDebounceSave: onDebounce(function(event) {
      this.$emit("input", event.target.value);
      this.$emit("onChange", event.target.value);
    }, 500),
    onSave(event) {
      if (this.needDebounce) {
        this.onDebounceSave(event);
      } else {
        this.$emit("input", event.target.value);
        this.$emit("onChange", event.target.value);
      }
    },
  },
  watch: {
    value: {
      handler(val) {
        this.fieldValue = val;
      },
      immediate: true,
    },
  },
};
</script>

<style lang="scss" scoped>
.search-wrap {
  @extend %flex-middle;
  .search {
    flex: 1;
    height: 42px;
    border-radius: j(10);
    overflow: hidden;
    border: j(1) solid #dce1e5;
    @extend %flex-middle;
    &.search-focus {
      border-color: $theme-blue-color;
    }
    .search-icon {
      width: j(16);
      height: j(16);
      margin: j(6) j(2) j(6) j(8);
    }
    .search-input {
      flex: 1;
      > input {
        width: 100%;
        background-color: transparent;
      }
    }
    .search-close-icon {
      width: 18px;
      height: 18px;
      box-sizing: content-box;
      padding: j(10);
      cursor: pointer;
    }
  }
  .action {
    flex-shrink: 0;
  }
}
</style>
