import { PropType, defineComponent, onMounted, reactive, ref } from 'vue';
import styles from './index.module.less';
import {
  NButton,
  NInput,
  NSpace
} from 'naive-ui';
import { resourceTypeArray2 } 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 subjects = ref('');
    const materials = ref('')
    const forms = reactive({
      type: 'IMG', //
      name: '',
      bookVersionId: null as any,
      subjectId: null as any,
      audioPlayTypes: props.type === 'myResources' ? 'PLAY' : '',
      // musicSheetCategoriesId: null,
      musicalInstrumentId: '',
      materialTagId: null
    });
    const resourceType = ref([] as any);

    const onSearch = (type?: string) => {
      emit('search', {
        ...forms,
        audioPlayTypes:
          forms.type === 'MUSIC'
            ? forms.audioPlayTypes
              ? forms.audioPlayTypes === 'PLAY_SING'
                ? ['PLAY', 'SING']
                : [forms.audioPlayTypes]
              : []
            : []
      }, type);
    };

    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 materialTagList = ref<any[]>([]);
    const _initMaterialTag = () => {
      const tags = catchStore.getMaterialTags;
      tags.forEach((item: any) => {
        item.columnName = '标签';
        item.name = item.label;
        item.id = item.value;
      });
      materialTagList.value = [
        {
          columnName: '标签',
          name: '全部标签',
          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);
      if (tags.length > 0) {
        tags[0].columnName = '声部';

        const firstChild = tags[0];
        forms.subjectId = firstChild.value;
        forms.musicalInstrumentId = firstChild.children[0]?.value;
        subjects.value = firstChild.children[0]?.value
      }
      tagSubjectList.value = tags

    };
    onMounted(async () => {
      // await catchStore.getMusicSheetCategory();
      await catchStore.getMusicTagTreeApi();
      _initTags();
      await catchStore.getMaterialTagsApi();
      _initMaterialTag();
      // 获取教材分类列表
      await catchStore.getSubjects();
      _initSubjectTags();

      resourceTypeArray2.forEach((item: any) => {
        // if (props.type === 'myResources') {
        //   item.value !== 'MUSIC' && resourceType.value.push(item);
        // } else {
        resourceType.value.push(item);
        // }
      });
      console.log(resourceType.value, "resourceType---1111")

      onSearch()
    });
    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) => {
                forms.bookVersionId = value || '';
                onSearch();
              }}
            />
          )}
          {forms.type !== 'MUSIC' && (
            <CCascader
              placeholder="全部标签"
              showPath
              v-model:value={materials.value}
              options={materialTagList.value}
              onUpdate:value={(value: any) => {
                forms.materialTagId = value || '';
                onSearch();
              }}
            />
          )}
          <CCascader
            placeholder="全部声部"
            childShowAllCheck={false}
            showPath
            showAudioPlayType={props.type === 'myResources' || forms.type !== 'MUSIC' ? false : true}
            v-model:value={subjects.value}
            options={tagSubjectList.value}
            onMoreId={(val: any) => {
              forms.musicalInstrumentId = val.childId;
              forms.subjectId = val.parentId;
              if (props.type !== 'myResources') {
                forms.audioPlayTypes = val.audioPlayTypes;
              }
              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>
    );
  }
});
