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

const ChildNodeSearch = defineComponent({
  name: 'ChildNodeSearch',
  props: {
    activeRow: {
      type: Object,
      default: () => ({})
    },
    list: {
      type: Array,
      default: () => []
    }
  },
  emits: ['selectChildTag'],
  setup(props, { emit }) {
    const { activeRow } = toRefs(props);
    const selectItem = ref({});

    watch(
      () => props.activeRow,
      () => {
        activeRow.value = props.activeRow;
        selectItem.value = {};
      }
    );
    return () => (
      <>
        {activeRow.value?.id && (
          <>
            <NFormItem label={activeRow.value.columnName + '：'}>
              <NSpace class={styles.spaceSection2}>
                {activeRow.value?.children.map((subject: any) => (
                  <span
                    class={[
                      styles.textBtn,
                      (activeRow.value.activeIndex || '') == subject.id &&
                        styles.textBtnActive
                    ]}
                    onClick={() => {
                      activeRow.value.activeIndex = subject.id;
                      let children: any;
                      let columnName = '';
                      if (subject.children) {
                        children = [
                          {
                            columnName: subject.children[0].columnName,
                            name: '全部',
                            id: ''
                          },
                          ...subject.children
                        ];
                        columnName = subject.children[0].columnName;

                        selectItem.value = {
                          ...subject,
                          columnName,
                          activeIndex: '',
                          children
                        };
                      } else {
                        selectItem.value = {};
                      }
                      emit('selectChildTag', activeRow.value.activeIndex);
                    }}>
                    {subject.name}
                  </span>
                ))}
              </NSpace>
            </NFormItem>

            <ChildNodeSearch
              activeRow={selectItem.value}
              onSelectChildTag={(item: any) => {
                emit('selectChildTag', item || activeRow.value.activeIndex);
              }}
            />
          </>
        )}
      </>
    );
  }
});

export default defineComponent({
  name: 'search-group',
  props: {
    type: {
      type: String,
      default: ''
    }
  },
  emits: ['search', 'add'],
  setup(props, { emit }) {
    const catchStore = useCatchStore();
    const forms = reactive({
      name: '',
      // grade: null as any,
      bookVersionId: null as any,
      // musicSheetCategoriesId: null as any,
      musicalInstrumentId: null
    });

    const state = reactive({
      tempSubjectId: null,
      gradeList: [] as any[],
      musicCategory: [] as any
    });
    const data = reactive({
      selectParents: {}, // 选中的数据
      tags: [] as any[],
      tagActiveId: '' as any,
      tagActive: {} as any,
      childSelectId: null as any
    });

    const onSearch = (type?: string) => {
      emit(
        'search',
        {
          ...forms,
          bookVersionId: data.childSelectId || data.tagActiveId
        },
        type
      );
    };

    const throttledFn = 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.musicalInstrumentId) {
          obj.selected = true;
          obj.name = child.name;
        }
      });
      return obj;
    };

    const _initTags = () => {
      const tags = catchStore.getMusicTagTree;
      data.tags = [
        {
          columnName: tags[0].columnName,
          name: '全部',
          id: ''
        },
        ...tags
      ];
      data.tagActiveId = data.tags[0].id;
    };

    const changeTag = (item: any) => {
      data.tagActiveId = item.id;
      data.childSelectId = null;
      let children: any;
      let columnName = '';
      if (item.children) {
        children = [
          {
            columnName: item.children[0].columnName,
            name: '全部',
            id: ''
          },
          ...item.children
        ];
        columnName = item.children[0].columnName;
        data.selectParents = {
          ...item,
          columnName,
          activeIndex: '',
          children
        };
      } else {
        data.selectParents = {};
      }

      onSearch();
    };

    /** 默认选中第一个声部 */
    const formatFirstSubject = () => {
      const tempSubjects = catchStore.getSubjectInstrumentOnly;
      if (tempSubjects.length > 0) {
        const firstSubject = tempSubjects[0];
        if (firstSubject.instruments && firstSubject.instruments.length > 1) {
          state.tempSubjectId = firstSubject.instruments[0]?.value;
          forms.musicalInstrumentId = firstSubject.instruments[0]?.value;
        } else {
          forms.musicalInstrumentId = firstSubject.value;
        }
      }
    };

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

      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;
      //     }
      //   }
      // }
      // console.log(state.musicCategory, 'state.musicCategory');

      formatFirstSubject();

      onSearch('timer');
    });
    return () => (
      <div class={styles.searchGroup}>
        <NForm labelAlign="left" labelPlacement="left">
          <div
            class={[
              styles.collapsSection,
              props.type === 'myResources' && styles.collapsSectionEmpty
            ]}>
            <NFormItem label={data.tags[0]?.columnName + '：'}>
              <NSpace class={styles.spaceSection2}>
                {data.tags.map((subject: any) => (
                  <span
                    class={[
                      styles.textBtn,
                      data.tagActiveId === subject.id && styles.textBtnActive
                    ]}
                    onClick={() => {
                      changeTag(subject);
                    }}>
                    {subject.name}
                  </span>
                ))}
              </NSpace>
            </NFormItem>

            <ChildNodeSearch
              activeRow={data.selectParents}
              onSelectChildTag={(val: any) => {
                data.childSelectId = val;
                onSearch();
              }}
            />
            {/* {state.gradeList.length > 0 && (
              <NFormItem label="年级：">
                <NSpace class={styles.spaceSection2}>
                  {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>
            )} */}
          </div>
          {/* {state.musicCategory.length > 0 && (
            <div
              class={[
                styles.collapsSection,
                props.type === 'myResources' && styles.collapsSectionEmpty
              ]}>
              <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;
                          throttledFn();
                        }}>
                        {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.getSubjectInstrumentOnly.map((subject: any) =>
                subject.instruments && subject.instruments.length > 1 ? (
                  <NPopselect
                    options={subject.instruments}
                    trigger="hover"
                    scrollable
                    v-model:value={state.tempSubjectId}
                    onUpdate:value={() => {
                      forms.musicalInstrumentId = 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.musicalInstrumentId === subject.value &&
                        styles.textBtnActive
                    ]}
                    onClick={() => {
                      forms.musicalInstrumentId = subject.value;

                      state.tempSubjectId = null;
                      onSearch();
                    }}>
                    {subject.name}
                  </span>
                )
              )}
            </NSpace>
          </NFormItem>
          {/* <NFormItem label="教材：">
            <NSpace class={styles.spaceSection}>
              {catchStore.getAllMusicCategories.map((music: any) => (
                <NButton
                  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;
                    throttledFn();
                  }}>
                  {music.name}
                </NButton>
              ))}
            </NSpace>
          </NFormItem> */}
          <TheSearch
            class={[styles.inputSearch]}
            round
            onSearch={(val: string) => {
              forms.name = val;
              throttledFn();
            }}
          />
        </NForm>
      </div>
    );
  }
});
