import {
  defineComponent,
  onMounted,
  onUnmounted,
  reactive,
  ref,
  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_chapterLessonCoursewareTag_queryAll,
  api_queryOpenCoursewareByPage
} from '../../api';
import { eventGlobal } from '/src/utils';
import dayjs from 'dayjs';

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 tagList = ref<any[]>([]);
    const forms = reactive({
      loading: false,
      finshed: false, // 是否加载完
      pagination: {
        page: 1,
        rows: 20
      },
      tableList: [] as any,
      searchGroup: {
        instrumentId: props.instrumentId ? props.instrumentId : '',
        chapterLessonCoursewareTagId: '',
        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,
            instrumentNames: item.instrumentNames,
            fromChapterLessonCoursewareId: item.fromChapterLessonCoursewareId,
            name: item.name,
            coverImg: firstItem?.bizInfo.coverImg,
            chapterLessonCoursewareTagName: item.chapterLessonCoursewareTagName,
            chapterLessonCoursewareTagColor:
              item.chapterLessonCoursewareTagColor,
            authorName: item.authorName,
            updateTime: item.updateTime
              ? dayjs(item.updateTime).format('YYYY-MM-DD')
              : '',
            type: firstItem?.bizInfo.type,
            isAdd: item.addFlag,
            isNotWork: item.lessonPreTrainingNum <= 0 ? true : false, // 是否布置作业
            coursewareType: item.coursewareType
          });
        });

        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);

    const getTagAll = async () => {
      const { data } = await api_chapterLessonCoursewareTag_queryAll();
      const result = data || [];

      tagList.value = [{ name: '全部', id: '' }, ...result];
    };

    getTagAll();

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

    onUnmounted(() => {
      eventGlobal.off('openCoursewareChanged', throttleFn);
    });
    return () => (
      <div class={styles.relatedClass}>
        <div class={styles.attendClassSearch}>
          <NSelect
            placeholder="全部"
            class={styles.searchSelect2}
            options={tagList.value}
            labelField="name"
            valueField="id"
            clearable
            v-model:value={forms.searchGroup.chapterLessonCoursewareTagId}
            onUpdate:value={() => {
              throttleFn();
            }}
          />
          <NCascader
            placeholder="全部乐器"
            clearable
            options={[
              { name: '全部乐器', id: '' },
              ...(props.instrumentList as any)
            ]}
            v-model:value={forms.searchGroup.instrumentId}
            onUpdate:value={() => throttleFn()}
            checkStrategy="child"
            showPath={false}
            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}
                          background={'#fff'}
                          onAdd={() => {
                            emit('add', item);
                          }}
                          onLook={() => emit('click', item)}
                        />
                      </div>
                    </div>
                  ))}
                </div>
              )}
              {!forms.loading && forms.tableList.length <= 0 && <TheEmpty />}
            </div>
          </NScrollbar>
        </NSpin>
      </div>
    );
  }
});
