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 { useCatchStore } from '/src/store/modules/catchData';
import { useThrottleFn } from '@vueuse/core';
import CCascader from '/src/components/CCascader';

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 musics = ref('');
    const subjects = ref('');
    const forms = reactive({
      name: '',
      // grade: null as any,
      bookVersionId: '' as any,
      subjectId: null as any,
      // musicSheetCategoriesId: null,
      musicalInstrumentId: ''
    });

    const onSearch = (type?: string) => {
      emit('search', forms, type);
    };

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

    // const formatParentId = (id: any, list: any, ids = [] as any) => {
    //   for (const item of list) {
    //     if (item.children && item.children.length > 0) {
    //       const cIds: any = formatParentId(id, item.children, [
    //         ...ids,
    //         item.id
    //       ]);
    //       if (cIds.includes(id)) {
    //         return cIds;
    //       }
    //     }
    //     if (item.id === id) {
    //       return [...ids, id];
    //     }
    //   }
    //   return ids;
    // };

    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);

      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.getSubjects();
      _initSubjectTags();
      // 获取声部列表
      await catchStore.getSubjects();

      onSearch('time')
    });
    return () => (
      <>
        <div class={styles.searchGroup}>
          <div class={styles.searchSelect}>
            {props.type !== 'myMusic' && (
              <CCascader
                placeholder="全部版本"
                showPath
                v-model:value={musics.value}
                options={tagList.value}
                onUpdate:value={(value: any) => {
                  forms.bookVersionId = value || '';
                  onSearch();
                }}
              />
            )}
            <CCascader
              v-model:value={subjects.value}
              childShowAllCheck={false}
              placement="bottom-end"
              placeholder="全部声部"
              options={tagSubjectList.value}
              // onUpdate:value={() => {
              //   onSearch();
              // }}
              onMoreId={(val: any) => {
                forms.musicalInstrumentId = val.childId;
                forms.subjectId = val.parentId;
                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>
      </>
    );
  }
});
