import { computed, defineComponent, watch } from 'vue';
import { debounce } from 'lodash-es';
import { useNamespace } from '@ibiz-template/vue-util';
import '@/styles/components/common/quick-search/quick-search.scss';

export const QuickSearch = defineComponent({
  name: 'QuickSearch',
  props: {
    value: {
      type: String,
    },
    viewMode: {
      type: String,
      required: true,
    },
    placeholder: {
      type: String,
    },
  },
  setup(props, { emit }) {
    const ns = useNamespace('quick-search');
    const valu = computed({
      get() {
        return props.value;
      },
      set(val: string | undefined) {
        emit('update', val!);
      },
    });
    const search = debounce(() => {
      emit('search');
    }, 500);
    const onChange = (e: InputEvent) => {
      if (e.target) {
        valu.value = (e.target as unknown as { value: string }).value;
      }
    };
    watch(
      () => props.value,
      () => {
        search();
      },
    );
    return { ns, valu, search, onChange };
  },
  render() {
    return (
      <i-input
        value={this.value}
        class={[this.ns.b(), this.ns.m(this.viewMode.toLowerCase())]}
        search={true}
        placeholder={this.placeholder}
        on-on-change={this.onChange}
        on-on-enter={this.search}
        on-on-search={this.search}
      ></i-input>
    );
  },
});

export default QuickSearch;
