import { defineComponent, onMounted, reactive } from 'vue';
import styles from './index.module.less';
import { NButton, NInput, NSelect, NSpace } from 'naive-ui';
import { useCatchStore } from '/src/store/modules/catchData';
import { useThrottleFn } from '@vueuse/core';

export default defineComponent({
  name: 'resource-search-group',
  emits: ['search'],
  setup(props, { emit }) {
    const catchStore = useCatchStore();
    const forms = reactive({
      name: '',
      musicSheetCategoriesId: null
    });

    const onSearch = () => {
      emit('search', forms);
    };

    const throttledFn = useThrottleFn(() => onSearch(), 500);

    onMounted(async () => {
      // 获取教材分类列表
      await catchStore.getMusicSheetCategory();
      // 获取声部列表
      await catchStore.getSubjects();
    });
    return () => (
      <>
        <div class={styles.searchGroup}>
          <div class={styles.searchSelect}>
            <NSelect
              placeholder="全部教材"
              options={[
                { name: '全部教材', id: null },
                ...catchStore.getMusicCategories
              ]}
              clearable
              labelField="name"
              valueField="id"
              v-model:value={forms.musicSheetCategoriesId}
              onUpdate:value={() => {
                onSearch();
              }}
            />
          </div>

          <NInput
            type="text"
            placeholder="请输入搜索关键词"
            clearable
            v-model:value={forms.name}
            class={styles.inputSearch}
            onKeyup={(e: KeyboardEvent) => {
              if (e.code === 'Enter') {
                throttledFn();
              }
            }}
            onClear={() => {
              forms.name = '';
              throttledFn();
            }}>
            {{
              prefix: () => (
                <span
                  class={'icon-search-input'}
                  onClick={() => throttledFn()}></span>
              )
            }}
          </NInput>
        </div>
      </>
    );
  }
});
