import { Button, Icon, Search } from 'vant'
import { defineComponent, PropType } from 'vue'
import styles from './index.module.less'
import iconSearch from '@common/images/icon_search.png'
import iconFilter from '@common/images/icon_filter.png'

type inputBackground = 'default' | 'white'

export default defineComponent({
  name: 'ColSearch',
  props: {
    modelValue: {
      type: String,
      default: ''
    },
    showAction: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    autofocus: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: '请输入搜索关键词'
    },
    background: {
      type: String,
      default: '#fff'
    },
    inputBackground: {
      type: String as PropType<inputBackground>,
      default: 'default'
    },
    onSearch: {
      type: Function,
      default: (val: any) => {}
    },
    onFilter: {
      type: Function,
      default: () => {}
    },
    filterDot: {
      type: Boolean,
      default: false
    }
  },
  emits: ['click'],
  watch: {
    modelValue() {
      this.search = this.modelValue
    }
  },
  data() {
    return {
      search: this.modelValue || ''
    }
  },
  render() {
    return (
      <div>
        <Search
          class={[styles['col-search'], styles[this.inputBackground]]}
          v-model={this.search}
          background={this.background}
          showAction={this.showAction}
          shape="round"
          placeholder={this.placeholder}
          disabled={this.disabled}
          autofocus={this.autofocus}
          onSearch={(val: string) => {
            this.onSearch(val)
          }}
          onClear={() => {
            this.search = ''
            this.onSearch()
          }}
          onClick={() => this.$emit('click')}
          v-slots={{
            left: () => this.$slots.left && this.$slots.left(),
            'left-icon': () => <Icon name={iconSearch} size={16} />,
            'right-icon': () => (
              <Button
                class={styles.searchBtn}
                round
                type="primary"
                size="mini"
                onClick={() => {
                  this.onSearch(this.search)
                }}
              >
                搜索
              </Button>
            ),
            action: () => (
              <Icon
                name={iconFilter}
                size={28}
                dot={this.filterDot}
                onClick={() => {
                  this.onFilter()
                }}
              />
            )
          }}
        />
      </div>
    )
  }
})
