import {
  PropType,
  defineComponent,
  onMounted,
  onUnmounted,
  reactive,
  toRefs
} from 'vue';
import ResourceSearchGroup from './resource-search-group';
import { NScrollbar, NSpin, useMessage } from 'naive-ui';
import styles from './index.module.less';
import CardType from '/src/components/card-type';
import { favorite, materialQueryPage } from '/src/views/natural-resources/api';
import TheEmpty from '/src/components/TheEmpty';
import { usePrepareStore } from '/src/store/modules/prepareLessons';
import { useDebounceFn, useResizeObserver } from '@vueuse/core';
import CardPreview from '/src/components/card-preview';
import { eventGlobal } from '/src/utils';
import ClassSearchGroup from './class-search-group';
import { useCatchStore } from '/src/store/modules/catchData';

const formatType = (type: string) => {
  if (type === 'shareResources') {
    return 2;
  } else if (type === 'myResources') {
    return 3;
  } else if (type === 'myCollect') {
    return 4;
  } else if (type === 'relateResources') {
    return 5;
  }
};

export default defineComponent({
  name: 'share-resources',
  props: {
    type: {
      type: String as PropType<
        'relateResources' | 'shareResources' | 'myResources' | 'myCollect'
      >,
      default: 'shareResources'
    },
    searchGroup: {
      type: Object,
      default: () => ({})
    },
    /** 从哪里使用 */
    from: {
      type: String,
      default: ''
    },
    instrumentId: {
      type: String,
      default: ''
    }
  },
  setup(props) {
    const prepareStore = usePrepareStore();
    const catchStore = useCatchStore();
    const { type } = toRefs(props);
    const className = 'resourceSearchGroup' + +new Date();
    const className2 = 'spinSearchGroup' + +new Date();
    const state = reactive({
      searchHeight: '0px',
      searchHeight2: '0px',
      loading: false,
      finshed: false, // 是否加载完
      pagination: {
        page: 1,
        rows: 20
      },
      searchGroup: {
        type: 'MUSIC', //
        name: '',
        materialTagId: null,
        bookVersionId: null,
        subjectId: null,
        audioPlayTypes: props.type === 'myResources' ? ['PLAY'] : [],
        sourceType: formatType(type.value),
        musicalInstrumentId: null as any,
        enableFlag: true
      },
      tableList: [] as any,
      show: false,
      item: {} as any
    });

    // 查询列表
    const getList = async () => {
      try {
        if (state.pagination.page === 1) {
          state.loading = true;
        }
        const { data } = await materialQueryPage({
          ...state.searchGroup,
          ...state.pagination,
          lessonCoursewareKnowledgeId:
            props.type === 'relateResources' || props.type === 'shareResources'
              ? prepareStore.getSelectKey
              : null,
          relateLessonCoursewareKnowledgeMaterialIds: getIds()
        });
        state.loading = false;
        const tempRows = data.rows || [];
        const temp: any = [];
        tempRows.forEach((row: any) => {
          temp.push({
            id: row.id,
            coverImg: row.coverImg,
            type: row.type,
            title: row.name,
            isCollect: !!row.favoriteFlag,
            isSelected: row.sourceFrom === 'PLATFORM' ? true : false,
            refFlag: row.refFlag,
            instrumentIds: row.instrumentIds,
            hasNotCheck: row.hasNotCheck,
            audioPlayTypeArray: row.audioPlayTypes
              ? row.audioPlayTypes.split(',')
              : [],
            containAccompaniment: row.containAccompaniment,
            content: row.content
          });
        });
        state.tableList.push(...temp);

        state.finshed = data.pages <= data.current ? true : false;
      } catch {
        state.loading = false;
      }
    };

    const onSearch = (item: any) => {
      state.pagination.page = 1;
      state.tableList = [];
      const { subjectId, ...res } = item;
      state.searchGroup = Object.assign(state.searchGroup, {
        ...res,
        musicalInstrumentId: subjectId,
        subjectId: null
      });
      getList();
    };
    const throttledFnSearch = useDebounceFn(item => {
      onSearch(item);
    }, 300);

    // 添加资源
    const onAdd = async (item: any) => {
      try {
        eventGlobal.emit('onPrepareAddItem', {
          materialId: item.id,
          coverImg: item.coverImg,
          type: item.type,
          title: item.title,
          refFlag: item.refFlag,
          isCollect: item.isCollect,
          isSelected: item.isSelected,
          audioPlayTypeArray: item.audioPlayTypeArray,
          instrumentIds: item.instrumentIds,
          hasNotCheck: item.hasNotCheck,
          content: item.content,
          removeFlag: false
        });
      } catch {
        //
      }
    };

    // 收藏
    const onCollect = async (item: any) => {
      try {
        await favorite({
          materialId: item.id,
          favoriteFlag: item.isCollect ? 0 : 1,
          type: item.type
        });
        item.isCollect = !item.isCollect;
      } catch {
        //
      }
    };

    const getIds = () => {
      let noRepeatIds: any = [];
      if (props.type === 'relateResources') {
        const materialIds: any = [];
        prepareStore.getCoursewareList.forEach((course: any) => {
          course.list?.forEach((item: any) => {
            materialIds.push(item.materialId);
          });
        });
        noRepeatIds = Array(...new Set(materialIds));
      }
      return noRepeatIds.join(',');
    };

    const onUpdate = () => {
      state.pagination.page = 1;
      state.tableList = [];
      getList();
    };

    onMounted(async () => {
      // 加载的时候判断是否有资源数据
      // 获取声部
      await catchStore.getSubjects();

      useResizeObserver(
        document.querySelector('.' + className) as HTMLElement,
        (entries: any) => {
          const entry = entries[0];
          const { height } = entry.contentRect;
          state.searchHeight = height + 'px';
        }
      );
      useResizeObserver(
        document.querySelector('.' + className2) as HTMLElement,
        (entries: any) => {
          const entry = entries[0];
          const { height } = entry.contentRect;
          state.searchHeight2 = height + 'px';
        }
      );

      // if (props.type !== 'shareResources' || props.from === 'class') {
      //   getList();
      // }

      if (props.type === 'relateResources') {
        eventGlobal.on('onCoursewareUpdate', onUpdate);
      }
    });
    onUnmounted(() => {
      eventGlobal.off('onCoursewareUpdate', onUpdate);
    });

    return () => (
      <div>
        {/* <div class={className}>
          {props.from !== 'class' && (
            <ResourceSearchGroup
              type={props.type}
              onSearch={(item: any, type: any) => {
                if (type) {
                  onSearch(item);
                  return;
                }
                throttledFnSearch(item);
              }}
            />
          )}
        </div> */}
        <NScrollbar
          class={[styles.listContainer, 'list_container']}
          style={{
            'max-height': `calc(var(--listContainerHeight) - var(--modal-lesson-tab-height) - ${state.searchHeight}) `
          }}
          onScroll={(e: any) => {
            const clientHeight = e.target?.clientHeight;
            const scrollTop = e.target?.scrollTop;
            const scrollHeight = e.target?.scrollHeight;
            // 是否到底，是否加载完
            if (
              clientHeight + scrollTop + 20 >= scrollHeight &&
              !state.finshed &&
              !state.loading
            ) {
              state.pagination.page = state.pagination.page + 1;
              getList();
            }
          }}>
          <div class={className2}>
            {props.from === 'class' ? (
              <ClassSearchGroup
                from={props.from}
                type={props.type}
                subjectId={
                  (prepareStore.getSubjectId as any) || props.instrumentId
                }
                onSearch={(item: any, type: any) => {
                  if (type) {
                    onSearch(item);
                    return;
                  }
                  throttledFnSearch(item);
                }}
              />
            ) : (
              <ResourceSearchGroup
                type={props.type}
                searchGroup={props.searchGroup}
                onSearch={(item: any, type: any) => {
                  if (type) {
                    onSearch(item);
                    return;
                  }
                  throttledFnSearch(item);
                }}
              />
            )}
          </div>
          <NSpin show={state.loading} size={'small'}>
            <div
              style={{
                'min-height': `calc(var(--listContainerHeight) - var(--modal-lesson-tab-height) - ${state.searchHeight} - ${state.searchHeight2})`
              }}
              class={[
                styles.listSection,
                !state.loading && state.tableList.length <= 0
                  ? styles.emptySection
                  : ''
              ]}>
              {state.tableList.length > 0 && (
                <div class={styles.list}>
                  {state.tableList.map((item: any) => (
                    <div class={[styles.itemWrap, 'selresources_item_Wrap']}>
                      <div class={styles.itemWrapBox}>
                        <CardType
                          isShowAdd={props.from === 'class' ? false : true}
                          item={item}
                          isShowCollect={true}
                          // isShowAddDisabled={!prepareStore.getIsEditResource}
                          onAdd={(item: any) => onAdd(item)}
                          disabledMouseHover={false}
                          onCollect={(item: any) => onCollect(item)}
                          onClick={() => {
                            if (item.type === 'IMG') return;
                            state.show = true;
                            state.item = {
                              instrumentId:
                                state.searchGroup.musicalInstrumentId,
                              ...item
                            };
                          }}
                        />
                      </div>
                    </div>
                  ))}
                </div>
              )}

              {!state.loading && state.tableList.length <= 0 && <TheEmpty />}
            </div>
          </NSpin>
        </NScrollbar>

        {/* 弹窗查看 */}
        <CardPreview
          size={props.from === 'class' ? 'large' : 'default'}
          v-model:show={state.show}
          from={props.from}
          item={state.item}
          isDownload={false}
        />
      </div>
    );
  }
});
