import { Button, Icon, Search } from 'vant';
import { PropType, defineComponent, reactive, ref, watch } from 'vue';
import styles from './index.module.less';
import iconSearch from '@/common/images/icon-search.svg';

type inputBackground = 'default' | 'white' | 'transparent';
export default defineComponent({
  name: 'm-search',
  props: {
    modelValue: {
      type: String,
      default: ''
    },
    shape: {
      type: String as PropType<'round' | 'square'>,
      default: 'round'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    clearable: {
      type: Boolean,
      default: true
    },
    autofocus: {
      // ios系统不支持
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: '请输入搜索关键词'
    },
    background: {
      type: String,
      default: '#fff'
    },
    searchIcon: {
      type: String,
      default: iconSearch
    },
    inputBackground: {
      type: String as PropType<inputBackground>,
      default: 'default'
    }
  },
  emits: ['search', 'focus', 'blur', 'searchUpdate'],
  setup(props, { slots, emit, expose }) {
    const forms = reactive({
      search: props.modelValue || '',
    });
    const searchRef = ref()
    watch(
      () => props.modelValue,
      () => {
        forms.search = props.modelValue;
      }
    );

    const searchBlur = () => {
      searchRef.value?.blur()
    }

    expose({
      searchBlur
    })
    return () => (
      <Search
        class={[styles['m-search'], styles[props.inputBackground]]}
        ref={searchRef}
        shape={props.shape}
        background={props.background}
        placeholder={props.placeholder}
        disabled={props.disabled}
        autofocus={props.autofocus}
        autocomplete="off"
        clearable={props.clearable}
        v-model={forms.search}
        clearTrigger="always"
        onClear={() => {
          console.log('clear');
          forms.search = '';
          emit('search', forms.search);
        }}
        onFocus={() => emit('focus')}
        onBlur={() => emit('blur', forms.search)}
        onSearch={() => emit('search', forms.search)}
        onUpdate:modelValue={(val: any) => {
          // 输入框内容变化时触发
          // console.log('搜索内容变化',val)
          emit('searchUpdate', val);
        }}>
        {{
          left: () => slots.left && slots.left(),
          'left-icon': () => (
            <Icon name={props.searchIcon} class={styles.leftIcon} />
          ),
          'right-icon': () => (
            <Button
              disabled={props.disabled}
              class={styles.searchBtn}
              round
              type="primary"
              size="mini"
              onClick={() => emit('search', forms.search)}>
              搜索
            </Button>
          )
        }}
      </Search>
    );
  }
});
