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';
import { audioPlayType } from '/src/utils/contants';

export default defineComponent({
  name: 'resource-search-group',
  props: {
    type: {
      type: String as PropType<
        'relateResources' | 'shareResources' | 'myResources' | 'myCollect'
      >,
      default: 'shareResources'
    },
    subjectId: {
      type: String,
      default: ''
    },
    // 从哪里来的
    from: {
      type: String,
      default: ''
    }
  },
  emits: ['search'],
  setup(props, { emit }) {
    const subjectId = toRef(props.subjectId);
    const catchStore = useCatchStore();
    const forms = reactive({
      type: 'MUSIC', //
      name: '',
      audioPlayTypes:
        props.type === 'myResources' && props.from === 'class' ? 'PLAY' : '',
      subjectId: subjectId.value as any,
      bookVersionId: null
    });
    const resourceType = ref([] as any);
    const audioPlayTypeList = ref([] as any);

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

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

    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) {
          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]
        };
      });
      audioPlayTypeList.value = [{ name: '全部', value: '' }, ...tempAudio];
      resourceTypeArray.forEach((item: any) => {
        resourceType.value.push(item);
      });

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

      if (!props.subjectId) {
        formatFirstSubject();
      }

      catchStore.getSubjectInstruments.forEach((item: any) => {
        if (item.instruments?.length > 0) {
          item.instruments.forEach((child: any) => {
            if (child.id == props.subjectId) {
              forms.subjectId = child.value;
            }
          });
        } else {
          if (item.id == props.subjectId) {
            forms.subjectId = item.value;
          }
        }
      });
      onSearch('timer');
    });
    return () => (
      <div class={styles.searchGroup}>
        <NForm labelAlign="left" labelPlacement="left">
          {props.type !== 'myResources' && (
            <NFormItem label="场景：">
              <NSpace
                class={[
                  styles.spaceSection,
                  styles.spaceSection2,
                  'spaceSectionBox'
                ]}>
                {audioPlayTypeList.value.map((subject: any) => (
                  <span
                    class={[
                      styles.textBtn,

                      forms.audioPlayTypes === subject.value &&
                        styles.textBtnActive
                    ]}
                    onClick={() => {
                      forms.audioPlayTypes = subject.value;
                      // if (subject.value === 'SING') {
                      //   forms.subjectId = null;
                      // } else {
                      //   formatFirstSubject();
                      // }
                      onSearch();
                    }}>
                    {subject.name}
                  </span>
                ))}
              </NSpace>
            </NFormItem>
          )}
          {forms.audioPlayTypes !== 'SING' && (
            <NFormItem label="乐器：">
              <NSpace
                class={[
                  styles.spaceSection,
                  styles.spaceSection2,
                  'spaceSectionBox'
                ]}>
                {catchStore.getSubjectInstrumentOnly.map((subject: any) =>
                  subject.instruments && subject.instruments.length > 1 ? (
                    <NPopselect
                      options={subject.instruments}
                      trigger="hover"
                      scrollable
                      v-model:value={forms.subjectId}
                      onUpdate:value={() => {
                        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;
                        onSearch();
                      }}>
                      {subject.name}
                    </span>
                  )
                )}
              </NSpace>
            </NFormItem>
          )}

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