<template>
  <div class="common-search">
    <img class="search-icon" :src="icon" alt="" />
    <div class="search-input">
      <input type="text" :placeholder="placeholder" v-model="fieldValue" />
    </div>

    <img
      v-if="closable && fieldValue"
      class="search-close-icon"
      @click="onClear"
      alt=""
      :src="delIcon"
    />
  </div>
</template>

<script lang="ts">
/**
 * 搜索组件
 */
import { defineComponent, watch, ref } from "vue";
import { formatCosUrl } from "../utils/dict";
export default defineComponent({
  name: "Search",
  props: {
    value: {
      type: String,
      default: ""
    },
    icon: {
      type: String,
      default: formatCosUrl("/worktable-h5/icon/search-icon.png")
    },
    placeholder: {
      type: String,
      default: "搜索"
    },
    closable: {
      type: Boolean,
      default: true
    }
  },
  setup(props, { emit }) {
    const fieldValue = ref("");
    const delIcon = ref(formatCosUrl("/worktable-h5/icon/search_delete01.png"));
    const onInput = () => {
      if (!fieldValue.value) return;
      emit("update:value", fieldValue.value);
    };

    const onClear = () => {
      fieldValue.value = "";
      emit("onClear");
    };

    watch(
      () => props.value,
      val => (fieldValue.value = val),
      { immediate: true }
    );

    watch(
      () => fieldValue.value,
      val => {
        emit("update:value", val);
        emit("onChange", val);
      }
    );

    return {
      fieldValue,
      onInput,
      onClear,
      delIcon
    };
  }
});
</script>

<style lang="scss" scoped>
.common-search {
  height: 42px;
  border-radius: j(10);
  overflow: hidden;
  background-color: #f6f6f6;
  display: flex;
  align-items: center;

  .search-icon {
    width: j(16);
    height: j(16);
    margin: j(6) j(2) j(6) j(8);

    img {
      width: 100%;
      height: 100%;
      vertical-align: middle;
    }
  }

  .search-input {
    flex: 1;

    > input {
      width: 100%;
    }
  }

  input {
    background: transparent;
  }

  .search-close-icon {
    width: 18px;
    height: 18px;
    margin-right: j(10);
    cursor: pointer;

    img {
      width: 100%;
      height: 100%;
      vertical-align: middle;
    }
  }
}
</style>
