import { defineComponent, nextTick, onMounted, reactive, ref } 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 { resourceTypeArray } from '/src/utils/searchArray';
import { useCatchStore } from '/src/store/modules/catchData';
import isCollaose from '../../images/isCollaose.png';
import { audioPlayType } from '/src/utils/contants';

export default defineComponent({
  name: 'search-group',
  emits: ['search'],
  setup(props, { emit }) {
    const catchStore = useCatchStore();
    const resourceList = ref([] as any[]);
    const forms = reactive({
      type: 'MUSIC', //
      name: '',
      audioPlayTypes: '',
      bookVersionId: null,
      subjectId: null
    });
    const state = reactive({
      tempSubjectId: null
    });
    const data = reactive({
      audioPlayTypeList: [] as any
    });

    const onSearch = () => {
      emit('search', {
        ...forms,
        subjectId: forms.audioPlayTypes !== 'SING' ? forms.subjectId : null,
        audioPlayTypes: forms.audioPlayTypes
          ? forms.audioPlayTypes === 'PLAY_SING'
            ? ['PLAY', 'SING']
            : [forms.audioPlayTypes]
          : []
      });
    };

    const collapseWrapRef = ref();
    const divDomList = ref([] as any);
    const orginHeight = 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 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.subjectId = firstSubject.instruments[0]?.value;
        } else {
          forms.subjectId = firstSubject.value;
        }
      }
    };

    onMounted(async () => {
      // 场景
      const tempAudio = Object.keys(audioPlayType).map(key => {
        return {
          value: key,
          name: audioPlayType[key]
        };
      });
      data.audioPlayTypeList = [{ name: '全部', value: '' }, ...tempAudio];
      resourceList.value = [
        // {
        //   label: '全部',
        //   value: ''
        // },
        ...resourceTypeArray
      ];

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

      // 这里开始
      // if (forms.type === 'MUSIC') {
      //   orginHeight.value = collapseWrapRef.value.offsetHeight;
      //   // 默认隐藏
      //   getLive();
      // }
      formatFirstSubject();
      onSearch();
    });
    return () => (
      <div class={styles.searchGroup}>
        <div class={styles.searchCatatory}>
          <NSpace size="small" class={styles.btnType}>
            {resourceList.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.audioPlayTypes = '';
                  formatFirstSubject();
                  onSearch();

                  nextTick(() => {
                    if (forms.type === 'MUSIC') {
                      orginHeight.value = collapseWrapRef.value?.offsetHeight;
                      // hiddenHeight.value =
                      //   collapseWrapRef.value.offsetHeight / line.value || 0;
                      // 默认隐藏
                      getLive();
                    } else {
                      divDomList.value = [];
                    }
                  });
                }}>
                {item.label}
              </NButton>
            ))}
          </NSpace>
        </div>
        <NForm labelAlign="left" labelPlacement="left">
          {/* {forms.type === 'MUSIC' && (
            <div class={[styles.collapsSection]}>
              <NFormItem label="教材：">
                <div
                  class={[
                    styles.collapseWrap,
                    loadingCollapse.value ? '' : styles.hideButton,
                    isCollapse.value ? '' : styles.isHidden
                  ]}
                  ref={collapseWrapRef}>
                  <NSpace class={[styles.spaceSection]}>
                    {catchStore.getAllMusicCategories.map((music: any) => (
                      <NButton
                        data-id={music.id}
                        ref={musicCateRef}
                        secondary={forms.bookVersionId === music.id}
                        quaternary={forms.bookVersionId !== music.id}
                        strong
                        focusable={false}
                        type={
                          forms.bookVersionId === music.id
                            ? 'primary'
                            : 'default'
                        }
                        onClick={() => {
                          forms.bookVersionId = 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>
          )} */}
          {forms.type === 'MUSIC' && (
            <NFormItem label="场景：">
              <NSpace class={styles.spaceSection}>
                {data.audioPlayTypeList.map((subject: any) => (
                  <span
                    class={[
                      styles.textBtn,

                      forms.audioPlayTypes === subject.value &&
                        styles.textBtnActive
                    ]}
                    onClick={() => {
                      forms.audioPlayTypes = subject.value;
                      // if (subject.value === 'SING') {
                      //   state.tempSubjectId = null;
                      //   forms.subjectId = null;
                      // } else {
                      //   formatFirstSubject();
                      // }
                      onSearch();
                    }}>
                    {subject.name}
                  </span>
                ))}
              </NSpace>
            </NFormItem>
          )}

          {forms.audioPlayTypes !== 'SING' && (
            <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.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>
          )}

          <TheSearch
            class={styles.inputSearch}
            round
            onSearch={(val: string) => {
              forms.name = val;
              onSearch();
            }}
          />
        </NForm>
      </div>
    );
  }
});
