import {
  PropType,
  defineComponent,
  onMounted,
  onUnmounted,
  reactive,
  watch
} from 'vue';
import ResourceSearchGroup from './resource-search-group';
import { NModal, NScrollbar, NSpin } from 'naive-ui';
import styles from './index.module.less';
import TheEmpty from '/src/components/TheEmpty';
import { useThrottleFn } from '@vueuse/core';
import { usePrepareStore } from '/src/store/modules/prepareLessons';
import { api_queryOpenCoursewareByPage } from '/src/views/prepare-lessons/api';
import Item from './item';
import { eventGlobal } from '/src/utils';

export default defineComponent({
  name: 'share-resources',
  emits: ['look', 'add'],
  setup(props, { emit }) {
    const prepareStore = usePrepareStore();
    const state = reactive({
      loading: false,
      finshed: false, // 是否加载完
      pagination: {
        page: 1,
        rows: 10
      },
      searchGroup: {
        keyword: ''
      },
      tableList: [] as any,
      editStatus: false,
      editItem: {} as any,
      show: false,
      item: {} as any
    });
    const getList = async () => {
      try {
        if (!prepareStore.getSelectKey) return;

        if (state.pagination.page === 1) {
          state.loading = true;
        }
        // 查询公开课件列表
        const { data } = await api_queryOpenCoursewareByPage({
          instrumentId: prepareStore.getInstrumentId,
          coursewareDetailKnowledgeId: prepareStore.getSelectKey,
          ...state.searchGroup,
          ...state.pagination
        });
        if (state.pagination.page === 1 && state.tableList.length > 0) {
          state.tableList = [];
        }
        const result = data.rows || [];
        const tempList: any = [];
        result.forEach((item: any) => {
          // const index = forms.tableList.findIndex(
          //   (i: any) => i.fromChapterLessonCoursewareId === item.id
          // );
          const firstItem: any =
            item.chapterKnowledgeList[0]?.chapterKnowledgeMaterialList[0];
          tempList.push({
            id: item.id,
            openFlag: item.openFlag,
            openFlagEnable: item.openFlagEnable,
            instrumentNames: item.instrumentNames,
            fromChapterLessonCoursewareId: item.fromChapterLessonCoursewareId,
            name: item.name,
            coverImg: firstItem?.bizInfo.coverImg,
            type: firstItem?.bizInfo.type,
            isAdd: item.addFlag,
            coursewareType: item.coursewareType
          });
        });

        state.loading = false;
        state.tableList.push(...tempList);
        // console.log(result, 'result', data);
        state.finshed = data.pages <= data.current ? true : false;
      } catch {
        state.loading = false;
      }
    };

    const onSearch = async (item: any) => {
      state.pagination.page = 1;
      state.tableList = [];
      state.searchGroup = Object.assign(state.searchGroup, item);
      getList();
    };

    // 声部变化时
    // watch(
    //   () => prepareStore.getSubjectId,
    //   () => {
    //     onSearch(state.searchGroup);
    //   }
    // );

    const throttledFn = useThrottleFn(() => {
      state.pagination.page = state.pagination.page + 1;
      getList();
    }, 500);

    const eventChanged = () => {
      onSearch(state.searchGroup);
    };
    onMounted(() => {
      getList();
      eventGlobal.on('openCoursewareChanged', eventChanged);
    });
    onUnmounted(() => {
      eventGlobal.off('openCoursewareChanged', eventChanged);
    });
    return () => (
      <div>
        <ResourceSearchGroup onSearch={(item: any) => onSearch(item)} />
        <NScrollbar
          class={[styles.listContainer, styles.listNoMusic]}
          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
            ) {
              throttledFn();
            }
          }}>
          <NSpin show={state.loading} size={'small'}>
            <div
              class={[
                styles.listSection,
                !state.loading && state.tableList.length <= 0
                  ? styles.emptySection
                  : ''
              ]}>
              {state.tableList.length > 0 && (
                <div class={styles.list}>
                  {state.tableList.map((item: any) => (
                    <Item
                      item={item}
                      onAdd={() => emit('add', item)}
                      onLook={() => emit('look', item)}
                    />
                  ))}
                </div>
              )}
              {!state.loading && state.tableList.length <= 0 && <TheEmpty />}
            </div>
          </NSpin>
        </NScrollbar>
      </div>
    );
  }
});
