import { PropType, defineComponent, onMounted, reactive, ref } from 'vue';
import styles from './index.module.less';
import {
  NButton,
  NCascader,
  NInput,
  NSelect,
  NSpace,
  NTreeSelect,
  TreeSelectOverrideNodeClickBehavior
} from 'naive-ui';
import { resourceTypeArray } from '/src/utils/searchArray';
import { useCatchStore } from '/src/store/modules/catchData';
import { useThrottleFn } from '@vueuse/core';
import CCascader from '/src/components/CCascader';

export default defineComponent({
  name: 'resource-search-group',
  emits: ['search'],
  props: {
    type: {
      type: String as PropType<
        'shareResources' | 'myResources' | 'myCollect' | 'relateResources'
      >,
      default: 'relateResources'
    }
  },
  setup(props, { emit }) {
    const catchStore = useCatchStore();
    const musics = ref('');
    const forms = reactive({
      type: 'MUSIC', //
      name: '',
      bookVersionId: null as any,
      // musicSheetCategoriesId: null,
      musicalInstrumentId: ''
    });
    const resourceType = ref([] as any);

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

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

    const tagList = ref<any[]>([]);
    const _initTags = () => {
      const tags = catchStore.getMusicTagTree;
      tagList.value = [
        {
          columnName: tags[0].columnName,
          name: '全部' + tags[0].columnName || '',
          id: ''
        },
        ...tags
      ];
    };
    const formatParentCurrentValue = (list: any) => {
      for (const item of list) {
        if (item.instruments && item.instruments.length > 0) {
          item.instruments.forEach((child: any) => {
            child.columnName = '乐器';
          });
          item.children = item.instruments;
          formatParentCurrentValue(item.instruments);
        }
      }
    };
    const tagSubjectList = ref<any[]>([]);
    const _initSubjectTags = () => {
      const tags = catchStore.getSubjectList;
      formatParentCurrentValue(tags);
      tagSubjectList.value = [
        {
          columnName: '声部',
          name: '全部声部',
          id: ''
        },
        ...tags
      ];
    };
    onMounted(async () => {
      // await catchStore.getMusicSheetCategory();
      await catchStore.getMusicTagTreeApi();
      _initTags();
      // 获取教材分类列表
      await catchStore.getSubjects();
      _initSubjectTags();

      resourceTypeArray.forEach((item: any) => {
        // if (props.type === 'myResources') {
        //   item.value !== 'MUSIC' && resourceType.value.push(item);
        // } else {
        resourceType.value.push(item);
        // }
      });
    });
    return () => (
      <>
        <div class={styles.searchGroup}>
          <NSpace size="small" class={styles.btnType}>
            {resourceType.value.map((item: any) => (
              <NButton
                type={forms.type === item.value ? 'primary' : 'default'}
                secondary={forms.type === item.value ? false : true}
                round
                size="small"
                focusable={false}
                onClick={() => {
                  forms.type = item.value;
                  debouncedRequest();
                }}>
                {item.label}
              </NButton>
            ))}
          </NSpace>

          <div class={styles.searchSelect}>
            {forms.type === 'MUSIC' && props.type === 'shareResources' && (
              <CCascader
                placeholder="全部教材"
                showPath
                v-model:value={musics.value}
                options={tagList.value}
                onUpdate:value={(value: any) => {
                  console.log(value, 'value');
                  forms.bookVersionId = value || '';
                  onSearch();
                }}
              />
            )}
            <CCascader
              placeholder="全部声部"
              v-model:value={forms.musicalInstrumentId}
              options={tagSubjectList.value}
              onUpdate:value={() => {
                onSearch();
              }}
            />
          </div>

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