import {
  PropType,
  defineComponent,
  nextTick,
  onMounted,
  reactive,
  ref,
  toRef
} from 'vue';
import styles from './index.module.less';
import {
  NButton,
  NForm,
  NFormItem,
  NImage,
  NPopselect,
  NSpace
} from 'naive-ui';
import { resourceTypeArray } from '/src/utils/searchArray';
import { useCatchStore } from '/src/store/modules/catchData';
import { useThrottleFn } from '@vueuse/core';
import TheSearch from '/src/components/TheSearch';
import isCollaose from '/src/views/natural-resources/images/isCollaose.png';

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

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

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

    const collapseWrapRef = ref();
    const divDomList = ref([] as any);
    const orginHeight = ref(0);
    const hiddenHeight = ref(0);
    const line = ref(0);
    const isCollapse = ref(false);
    const loadingCollapse = ref(false); // 是否加载完成
    const musicCateRef = (el: any) => {
      if (el?.selfElRef) {
        divDomList.value.push(el.selfElRef.parentNode);
      }
    };
    const setCollapse = (flag: boolean) => {
      isCollapse.value = flag;
      getLive();
    };
    const getLive = () => {
      try {
        divDomList.value = [...new Set(divDomList.value)];
        let offsetLeft = -1;
        divDomList.value.forEach((item: any, index: number) => {
          if (index === 0) {
            line.value = 1;
            offsetLeft = item.offsetLeft;
          } else if (item.offsetLeft === offsetLeft && index != 0) {
            // 如果某个标签的offsetLeft和第一个标签的offsetLeft相等  说明增加了一行
            line.value++;
          }
          if (!isCollapse.value) {
            if (line.value > 1) {
              //从第3行开始 隐藏标签
              item.style.display = 'none';

              // 显示展开按钮  class名chu是在前面动态添加的
            } else {
              item.style.display = 'block';
            }
          } else {
            item.style.display = 'block';
          }
        });
        loadingCollapse.value = true;
      } catch {
        //
      }
    };

    const selectChildObj = (item: any) => {
      const obj: any = {};
      item?.forEach((child: any) => {
        if (child.id === forms.subjectId) {
          obj.selected = true;
          obj.name = child.name;
        }
      });
      return obj;
    };

    const onChangeSearch = (type: string, list: any) => {
      if (type === 'version') {
        console.log(list, 'list');
        state.gradeList = list || [];
        if (state.gradeList.length > 0) {
          forms.grade = state.gradeList[0].id;
          state.musicCategory = state.gradeList[0].children || [];
          if (state.musicCategory.length > 0) {
            forms.musicSheetCategoriesId = state.musicCategory[0].id;
          } else {
            forms.musicSheetCategoriesId = null;
          }
        } else {
          state.musicCategory = [] as any;
        }
      } else if (type === 'grade') {
        state.musicCategory = list || [];
        if (state.musicCategory.length > 0) {
          forms.musicSheetCategoriesId = state.musicCategory[0].id;
        } else {
          forms.musicSheetCategoriesId = null;
        }
      }
    };
    onMounted(async () => {
      // if (props.type === 'myCollect') {
      //   resourceType.value.push({
      //     label: '全部',
      //     value: ''
      //   });
      //   forms.type = ''; // 默认全部
      // }
      resourceTypeArray.forEach((item: any) => {
        // if (props.type === 'myResources') {
        //   item.value !== 'MUSIC' && resourceType.value.push(item);
        // } else {
        resourceType.value.push(item);
        // }
      });

      // // 获取教材分类列表
      // await catchStore.getMusicSheetCategory();
      await catchStore.getMusicTagTreeApi();
      // 获取声部
      await catchStore.getSubjects();

      // console.log(
      //   catchStore.getSubjectInstruments,
      //   'catchStore.getSubjectInstruments'
      // );
      // catchStore.getSubjectInstruments.forEach((item: any) => {
      //   if (item.id == props.subjectId && Array.isArray(item.instruments)) {
      //     if (item.instruments.length > 0) {
      //       forms.subjectId = item.instruments[0].value;
      //     } else {
      //       forms.subjectId = item.value;
      //     }
      //   }
      // });
      forms.subjectId = null;

      // 这里开始
      // musicCateRef
      if (forms.type === 'MUSIC') {
        orginHeight.value = collapseWrapRef.value?.offsetHeight;
        hiddenHeight.value = collapseWrapRef.value?.offsetHeight / line.value;
        // 默认隐藏
        getLive();

        const musicTagTreeList = catchStore.getMusicTagTree;
        if (musicTagTreeList.length > 0) {
          forms.bookVersionId = musicTagTreeList[0].id;
          state.gradeList = musicTagTreeList[0].children || [];
          if (state.gradeList.length > 0) {
            forms.grade = state.gradeList[0].id;
            state.musicCategory = state.gradeList[0].children || [];
            if (state.musicCategory.length > 0) {
              forms.musicSheetCategoriesId = state.musicCategory[0].id;
            }
          }
        }
      }

      if (props.type === 'shareResources') {
        onSearch('timer');
      }
    });
    return () => (
      <div class={styles.searchGroup}>
        <div class={styles.searchCatatory}>
          <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;
                  forms.subjectId = null;
                  onSearch();

                  try {
                    nextTick(() => {
                      if (forms.type === 'MUSIC') {
                        orginHeight.value = collapseWrapRef.value?.offsetHeight;
                        hiddenHeight.value =
                          collapseWrapRef.value?.offsetHeight / line.value;
                        // 默认隐藏
                        getLive();
                      } else {
                        divDomList.value = [];
                      }
                    });
                  } catch {
                    //
                  }
                }}>
                {item.label}
              </NButton>
            ))}
          </NSpace>

          <TheSearch
            class={styles.inputSearch}
            round
            onSearch={(val: string) => {
              forms.name = val;
              throttleFn();
            }}
          />
        </div>
        <NForm labelAlign="left" labelPlacement="left">
          {forms.type === 'MUSIC' && props.type === 'shareResources' && (
            <>
              <NFormItem label="版本：">
                <NSpace class={styles.spaceSection}>
                  {catchStore.getMusicTagTree.map((subject: any) => (
                    <span
                      class={[
                        styles.textBtn,
                        forms.bookVersionId === subject.id &&
                          styles.textBtnActive
                      ]}
                      onClick={() => {
                        forms.bookVersionId = subject.id;
                        onChangeSearch('version', subject.children || []);
                        onSearch();
                      }}>
                      {subject.name}
                    </span>
                  ))}
                </NSpace>
              </NFormItem>
              {state.gradeList.length > 0 && (
                <NFormItem label="年级：">
                  <NSpace class={styles.spaceSection}>
                    {state.gradeList.map((subject: any) => (
                      <span
                        class={[
                          styles.textBtn,
                          forms.grade === subject.id && styles.textBtnActive
                        ]}
                        onClick={() => {
                          forms.grade = subject.id;
                          onChangeSearch('grade', subject.children || []);
                          onSearch();
                        }}>
                        {subject.name}
                      </span>
                    ))}
                  </NSpace>
                </NFormItem>
              )}
              {state.musicCategory.length > 0 && (
                <div class={styles.collapsSection}>
                  <NFormItem label="教材：">
                    <div
                      class={[
                        styles.collapseWrap,
                        loadingCollapse.value ? '' : styles.hideButton,
                        isCollapse.value ? '' : styles.isHidden
                      ]}
                      ref={collapseWrapRef}>
                      <NSpace class={[styles.spaceSection]}>
                        {state.musicCategory.map((music: any) => (
                          <NButton
                            ref={musicCateRef}
                            secondary={
                              forms.musicSheetCategoriesId === music.id
                            }
                            quaternary={
                              forms.musicSheetCategoriesId !== music.id
                            }
                            strong
                            focusable={false}
                            type={
                              forms.musicSheetCategoriesId === music.id
                                ? 'primary'
                                : 'default'
                            }
                            onClick={() => {
                              forms.musicSheetCategoriesId = music.id;
                              onSearch();
                            }}>
                            {music.name}
                          </NButton>
                        ))}
                        {line.value > 1 && (
                          <div
                            class={styles.collaoseGroup}
                            onClick={() => {
                              setCollapse(!isCollapse.value);
                            }}>
                            <NImage
                              previewDisabled
                              src={isCollaose}
                              class={[
                                styles.collaoseBtn,
                                isCollapse.value ? styles.isStart : ''
                              ]}></NImage>
                          </div>
                        )}
                      </NSpace>
                    </div>
                  </NFormItem>
                </div>
              )}
            </>
          )}

          <NFormItem label="乐器：">
            <NSpace class={styles.spaceSection2}>
              {/* {catchStore.getSubjectAllList.map((music: any) => (
                <NButton
                  secondary={forms.subjectId === music.id}
                  quaternary={forms.subjectId !== music.id}
                  strong
                  focusable={false}
                  type={forms.subjectId === music.id ? 'primary' : 'default'}
                  onClick={() => {
                    forms.subjectId = music.id;
                    onSearch();
                  }}>
                  {music.name}
                </NButton>
              ))} */}
              {catchStore.getSubjectInstruments.map((subject: any) =>
                subject.instruments && subject.instruments.length > 1 ? (
                  <NPopselect
                    options={subject.instruments}
                    trigger="hover"
                    scrollable
                    v-model:value={state.tempSubjectId}
                    onUpdate:value={() => {
                      forms.subjectId = state.tempSubjectId;
                      onSearch();
                    }}
                    key={subject.value}
                    class={[styles.popSelect]}>
                    <span
                      class={[
                        styles.textBtn,
                        selectChildObj(subject.instruments).selected &&
                          styles.textBtnActive
                      ]}>
                      {selectChildObj(subject.instruments).name || subject.name}
                      <i class={styles.iconArrow}></i>
                    </span>
                  </NPopselect>
                ) : (
                  <span
                    class={[
                      styles.textBtn,

                      forms.subjectId === subject.value && styles.textBtnActive
                    ]}
                    onClick={() => {
                      forms.subjectId = subject.value;
                      state.tempSubjectId = null;
                      onSearch();
                    }}>
                    {subject.name}
                  </span>
                )
              )}
            </NSpace>
          </NFormItem>
        </NForm>
      </div>
    );
  }
});
