import { PropType, defineComponent, reactive, watch } from 'vue';
import styles from './index.module.less';
import { InputProps, NButton, NInput } from 'naive-ui';
import icon_search from '/src/common/images/icon_search.png';
import icon_searchActive from '/src/common/images/icon_searchActive.png';

export default defineComponent({
  name: 'TheSearch',
  props: {
    /** 圆角 */
    round: {
      type: Boolean as PropType<InputProps['round']>,
      default: false
    },
    border: {
      type: Boolean,
      default: true
    },
    placeholder: {
      type: String,
      default: '请输入搜索关键词'
    },
    value: {
      type: String,
      default: ''
    }
  },
  emits: ['search', 'update:value'],
  setup(props, { emit }) {
    const searchData = reactive({
      value: props.value || ''
    });

    watch(() => props.value, () => {
      searchData.value = props.value
    })
    return () => (
      <NInput
        class={[
          styles.TheSearch,
          props.border ? '' : styles.noBorder,
          'TheSearch'
        ]}
        round={props.round}
        placeholder={props.placeholder}
        clearable
        v-model:value={searchData.value}
        onUpdate:value={(val: string) => {
          emit("update:value", val)
        }}
        onClear={() => emit('search', '')}
        onKeyup={(e: KeyboardEvent) => {
          e.stopPropagation();
          if (e.code === 'Enter') {
            emit('search', searchData.value ? searchData.value.trim() : '');
          }
        }}>
        {{
          prefix: () => (
            <>
              <img class={styles.default} src={icon_search} />
              <img class={styles.active} src={icon_searchActive} />
            </>
          ),
          suffix: () => (
            <NButton
              size="small"
              round
              type="primary"
              onClick={() =>
                emit('search', searchData.value ? searchData.value.trim() : '')
              }>
              搜索
            </NButton>
          )
        }}
      </NInput>
    );
  }
});
