import { PropType, defineComponent, onMounted, reactive } from 'vue';
import styles from './index.module.less';
import { NButton, NCascader, 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',
  props: {
    type: {
      type: String as PropType<'myMusic' | 'sahreMusic' | 'collectMusic'>,
      default: 'myMusic'
    }
  },
  emits: ['search'],
  setup(props, { emit }) {
    const catchStore = useCatchStore();
    const forms = reactive({
      name: '',
      musicSheetCategoriesId: null,
      musicalInstrumentId: null
    });

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

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

    onMounted(async () => {
      // 获取教材分类列表
      await catchStore.getMusicSheetCategory();
      // 获取声部列表
      await catchStore.getSubjects();
    });
    return () => (
      <>
        <div class={styles.searchGroup}>
          {props.type !== 'myMusic' && (
            <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>
          )}

          <div class={styles.searchSelect}>
            <NCascader
              placeholder="全部乐器"
              v-model:value={forms.musicalInstrumentId}
              options={[...catchStore.getSubjectList]}
              checkStrategy="child"
              showPath={false}
              childrenField="instruments"
              expandTrigger="hover"
              clearable
              filterable
              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>
      </>
    );
  }
});
