import { defineComponent, onMounted, onUnmounted, reactive, watch } from 'vue';
import styles from './index.module.less';
import { NCascader, NInput, NScrollbar, NSelect, NSpin } from 'naive-ui';
import { useThrottleFn } from '@vueuse/core';
import CoursewareType from '../courseware-type';
import TheEmpty from '/src/components/TheEmpty';
import { api_queryOpenCoursewareByPage } from '../../api';
import { eventGlobal } from '/src/utils';

export default defineComponent({
  name: 'related-class',
  props: {
    tableList: {
      type: Array,
      default: () => []
    },
    instrumentList: {
      type: Array,
      default: () => []
    },
    instrumentId: {
      type: [String, Number],
      default: ''
    },
    coursewareDetailKnowledgeId: {
      type: [String, Number],
      default: ''
    }
  },
  emits: ['close', 'add', 'click'],
  setup(props, { emit }) {
    const forms = reactive({
      loading: false,
      finshed: false, // 是否加载完
      pagination: {
        page: 1,
        rows: 20
      },
      tableList: [] as any,
      searchGroup: {
        instrumentId: props.instrumentId ? Number(props.instrumentId) : '',
        keyword: null
      }
    });
    const getList = async () => {
      try {
        if (forms.pagination.page === 1) {
          forms.loading = true;
        }
        // 查询公开课件列表
        const { data } = await api_queryOpenCoursewareByPage({
          coursewareDetailKnowledgeId: props.coursewareDetailKnowledgeId,
          ...forms.searchGroup,
          ...forms.pagination
        });
        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,
            subjectNames: item.subjectNames,
            fromChapterLessonCoursewareId: item.fromChapterLessonCoursewareId,
            name: item.name,
            coverImg: firstItem?.bizInfo.coverImg,
            type: firstItem?.bizInfo.type,
            isAdd: item.addFlag,
            isNotWork: item.lessonPreTrainingNum <= 0 ? true : false // 是否布置作业
          });
        });

        forms.loading = false;
        forms.tableList.push(...tempList);

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

    // 检测数据是否存在
    // watch(
    //   () => props.tableList,
    //   () => {
    //     // fromChapterLessonCoursewareId;
    //     forms.tableList.forEach((item: any) => {
    //       const index = props.tableList.findIndex(
    //         (i: any) => i.fromChapterLessonCoursewareId === item.id
    //       );
    //       item.isAdd = index !== -1 ? true : false;
    //     });
    //   }
    // );

    const throttleFn = useThrottleFn(() => {
      forms.pagination.page = 1;
      forms.tableList = [];
      getList();
    }, 500);

    onMounted(() => {
      getList();
      eventGlobal.on('openCoursewareChanged', throttleFn);
    });

    onUnmounted(() => {
      eventGlobal.off('openCoursewareChanged', throttleFn);
    });
    return () => (
      <div class={styles.relatedClass}>
        <div class={styles.attendClassSearch}>
          <NCascader
            placeholder="全部声部"
            clearable
            options={[
              { name: '全部声部', id: '' },
              ...(props.instrumentList as any)
            ]}
            v-model:value={forms.searchGroup.instrumentId}
            onUpdate:value={() => throttleFn()}
            checkStrategy="child"
            showPath
            childrenField="instruments"
            expandTrigger="hover"
            labelField="name"
            valueField="id"
            filterable
            style={{ width: '200px' }}
          />
          <NInput
            placeholder="请输入课件标题关键词"
            clearable
            v-model:value={forms.searchGroup.keyword}
            onKeyup={(e: KeyboardEvent) => {
              if (e.code === 'Enter') {
                throttleFn();
              }
            }}
            onClear={() => throttleFn()}>
            {{
              prefix: () => (
                <span
                  class="icon-search-input"
                  style={{ cursor: 'pointer' }}
                  onClick={() => throttleFn()}></span>
              )
            }}
          </NInput>
        </div>

        <NSpin show={forms.loading} size={'small'}>
          <NScrollbar
            class={styles.classList}
            style={{
              'max-height': `60vh`
            }}
            onScroll={(e: any) => {
              const clientHeight = e.target?.clientHeight;
              const scrollTop = e.target?.scrollTop;
              const scrollHeight = e.target?.scrollHeight;
              // 是否到底，是否加载完
              if (
                clientHeight + scrollTop + 20 >= scrollHeight &&
                !forms.finshed &&
                !forms.loading
              ) {
                throttleFn();
              }
            }}>
            <div
              style={{
                'min-height': `60vh)`
              }}
              class={[
                styles.listSection,
                !forms.loading && forms.tableList.length <= 0
                  ? styles.emptySection
                  : ''
              ]}>
              {forms.tableList.length > 0 && (
                <div class={[styles.list]}>
                  {forms.tableList.map((item: any) => (
                    <div class={[styles.itemWrap, styles.itemBlock, 'row-nav']}>
                      <div class={styles.itemWrapBox}>
                        <CoursewareType
                          isHoverShowAdd={false}
                          isShowOpenFlag={false}
                          isShowAdd
                          item={item}
                          onAdd={() => {
                            emit('add', item);
                          }}
                          onLook={() => emit('click', item)}
                        />
                      </div>
                    </div>
                  ))}
                </div>
              )}
              {!forms.loading && forms.tableList.length <= 0 && <TheEmpty />}
            </div>
          </NScrollbar>
        </NSpin>
      </div>
    );
  }
});
